blob: c41b6c7c29b3d47de6aa5ccba03cf33582d05104 [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
drhe4a08f92016-01-08 19:17:30 +0000440 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
441#else
442 { "mmap", (sqlite3_syscall_ptr)0, 0 },
443#endif
drh6226ca22015-11-24 15:06:28 +0000444#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000445
drhe4a08f92016-01-08 19:17:30 +0000446#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000447 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000448#else
449 { "munmap", (sqlite3_syscall_ptr), 0 },
450#endif
drh6226ca22015-11-24 15:06:28 +0000451#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000452
drhe4a08f92016-01-08 19:17:30 +0000453#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000454 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
455#else
456 { "mremap", (sqlite3_syscall_ptr)0, 0 },
457#endif
drh6226ca22015-11-24 15:06:28 +0000458#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
459
danbc760632014-03-20 09:42:09 +0000460 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh6226ca22015-11-24 15:06:28 +0000461#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000462
dan245fdc62015-10-31 17:58:33 +0000463 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drh6226ca22015-11-24 15:06:28 +0000464#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000465
dan702eec12014-06-23 10:04:58 +0000466
drhe562be52011-03-02 18:01:10 +0000467}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000468
drh6226ca22015-11-24 15:06:28 +0000469
470/*
471** On some systems, calls to fchown() will trigger a message in a security
472** log if they come from non-root processes. So avoid calling fchown() if
473** we are not running as root.
474*/
475static int robustFchown(int fd, uid_t uid, gid_t gid){
476#if OS_VXWORKS
477 return 0;
478#else
479 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
480#endif
481}
482
drh99ab3b12011-03-02 15:09:07 +0000483/*
484** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000485** "unix" VFSes. Return SQLITE_OK opon successfully updating the
486** system call pointer, or SQLITE_NOTFOUND if there is no configurable
487** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000488*/
489static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000490 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
491 const char *zName, /* Name of system call to override */
492 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000493){
drh58ad5802011-03-23 22:02:23 +0000494 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000495 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000496
497 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000498 if( zName==0 ){
499 /* If no zName is given, restore all system calls to their default
500 ** settings and return NULL
501 */
dan51438a72011-04-02 17:00:47 +0000502 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000503 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
504 if( aSyscall[i].pDefault ){
505 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000506 }
507 }
508 }else{
509 /* If zName is specified, operate on only the one system call
510 ** specified.
511 */
512 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
513 if( strcmp(zName, aSyscall[i].zName)==0 ){
514 if( aSyscall[i].pDefault==0 ){
515 aSyscall[i].pDefault = aSyscall[i].pCurrent;
516 }
drh1df30962011-03-02 19:06:42 +0000517 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000518 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
519 aSyscall[i].pCurrent = pNewFunc;
520 break;
521 }
522 }
523 }
524 return rc;
525}
526
drh1df30962011-03-02 19:06:42 +0000527/*
528** Return the value of a system call. Return NULL if zName is not a
529** recognized system call name. NULL is also returned if the system call
530** is currently undefined.
531*/
drh58ad5802011-03-23 22:02:23 +0000532static sqlite3_syscall_ptr unixGetSystemCall(
533 sqlite3_vfs *pNotUsed,
534 const char *zName
535){
536 unsigned int i;
537
538 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000539 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
540 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
541 }
542 return 0;
543}
544
545/*
546** Return the name of the first system call after zName. If zName==NULL
547** then return the name of the first system call. Return NULL if zName
548** is the last system call or if zName is not the name of a valid
549** system call.
550*/
551static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000552 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000553
554 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000555 if( zName ){
556 for(i=0; i<ArraySize(aSyscall)-1; i++){
557 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000558 }
559 }
dan0fd7d862011-03-29 10:04:23 +0000560 for(i++; i<ArraySize(aSyscall); i++){
561 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000562 }
563 return 0;
564}
565
drhad4f1e52011-03-04 15:43:57 +0000566/*
drh77a3fdc2013-08-30 14:24:12 +0000567** Do not accept any file descriptor less than this value, in order to avoid
568** opening database file using file descriptors that are commonly used for
569** standard input, output, and error.
570*/
571#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
572# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
573#endif
574
575/*
drh8c815d12012-02-13 20:16:37 +0000576** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000577** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000578**
579** If the file creation mode "m" is 0 then set it to the default for
580** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
581** 0644) as modified by the system umask. If m is not 0, then
582** make the file creation mode be exactly m ignoring the umask.
583**
584** The m parameter will be non-zero only when creating -wal, -journal,
585** and -shm files. We want those files to have *exactly* the same
586** permissions as their original database, unadulterated by the umask.
587** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
588** transaction crashes and leaves behind hot journals, then any
589** process that is able to write to the database will also be able to
590** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000591*/
drh8c815d12012-02-13 20:16:37 +0000592static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000593 int fd;
drhe1186ab2013-01-04 20:45:13 +0000594 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000595 while(1){
drh5adc60b2012-04-14 13:25:11 +0000596#if defined(O_CLOEXEC)
597 fd = osOpen(z,f|O_CLOEXEC,m2);
598#else
599 fd = osOpen(z,f,m2);
600#endif
drh5128d002013-08-30 06:20:23 +0000601 if( fd<0 ){
602 if( errno==EINTR ) continue;
603 break;
604 }
drh77a3fdc2013-08-30 14:24:12 +0000605 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000606 osClose(fd);
607 sqlite3_log(SQLITE_WARNING,
608 "attempt to open \"%s\" as file descriptor %d", z, fd);
609 fd = -1;
610 if( osOpen("/dev/null", f, m)<0 ) break;
611 }
drhe1186ab2013-01-04 20:45:13 +0000612 if( fd>=0 ){
613 if( m!=0 ){
614 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000615 if( osFstat(fd, &statbuf)==0
616 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000617 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000618 ){
drhe1186ab2013-01-04 20:45:13 +0000619 osFchmod(fd, m);
620 }
621 }
drh5adc60b2012-04-14 13:25:11 +0000622#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000623 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000624#endif
drhe1186ab2013-01-04 20:45:13 +0000625 }
drh5adc60b2012-04-14 13:25:11 +0000626 return fd;
drhad4f1e52011-03-04 15:43:57 +0000627}
danielk197713adf8a2004-06-03 16:08:41 +0000628
drh107886a2008-11-21 22:21:50 +0000629/*
dan9359c7b2009-08-21 08:29:10 +0000630** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000631** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000632** vxworksFileId objects used by this file, all of which may be
633** shared by multiple threads.
634**
635** Function unixMutexHeld() is used to assert() that the global mutex
636** is held when required. This function is only used as part of assert()
637** statements. e.g.
638**
639** unixEnterMutex()
640** assert( unixMutexHeld() );
641** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000642*/
643static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000644 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000645}
646static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000647 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000648}
dan9359c7b2009-08-21 08:29:10 +0000649#ifdef SQLITE_DEBUG
650static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000651 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000652}
653#endif
drh107886a2008-11-21 22:21:50 +0000654
drh734c9862008-11-28 15:37:20 +0000655
mistachkinfb383e92015-04-16 03:24:38 +0000656#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000657/*
658** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000659** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000660** integer lock-type.
661*/
drh308c2a52010-05-14 11:30:18 +0000662static const char *azFileLock(int eFileLock){
663 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000664 case NO_LOCK: return "NONE";
665 case SHARED_LOCK: return "SHARED";
666 case RESERVED_LOCK: return "RESERVED";
667 case PENDING_LOCK: return "PENDING";
668 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000669 }
670 return "ERROR";
671}
672#endif
673
674#ifdef SQLITE_LOCK_TRACE
675/*
676** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000677**
drh734c9862008-11-28 15:37:20 +0000678** This routine is used for troubleshooting locks on multithreaded
679** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
680** command-line option on the compiler. This code is normally
681** turned off.
682*/
683static int lockTrace(int fd, int op, struct flock *p){
684 char *zOpName, *zType;
685 int s;
686 int savedErrno;
687 if( op==F_GETLK ){
688 zOpName = "GETLK";
689 }else if( op==F_SETLK ){
690 zOpName = "SETLK";
691 }else{
drh99ab3b12011-03-02 15:09:07 +0000692 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000693 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
694 return s;
695 }
696 if( p->l_type==F_RDLCK ){
697 zType = "RDLCK";
698 }else if( p->l_type==F_WRLCK ){
699 zType = "WRLCK";
700 }else if( p->l_type==F_UNLCK ){
701 zType = "UNLCK";
702 }else{
703 assert( 0 );
704 }
705 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000706 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000707 savedErrno = errno;
708 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
709 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
710 (int)p->l_pid, s);
711 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
712 struct flock l2;
713 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000714 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000715 if( l2.l_type==F_RDLCK ){
716 zType = "RDLCK";
717 }else if( l2.l_type==F_WRLCK ){
718 zType = "WRLCK";
719 }else if( l2.l_type==F_UNLCK ){
720 zType = "UNLCK";
721 }else{
722 assert( 0 );
723 }
724 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
725 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
726 }
727 errno = savedErrno;
728 return s;
729}
drh99ab3b12011-03-02 15:09:07 +0000730#undef osFcntl
731#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000732#endif /* SQLITE_LOCK_TRACE */
733
drhff812312011-02-23 13:33:46 +0000734/*
735** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000736**
drhe6d41732015-02-21 00:49:00 +0000737** All calls to ftruncate() within this file should be made through
738** this wrapper. On the Android platform, bypassing the logic below
739** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000740*/
drhff812312011-02-23 13:33:46 +0000741static int robust_ftruncate(int h, sqlite3_int64 sz){
742 int rc;
dan2ee53412014-09-06 16:49:40 +0000743#ifdef __ANDROID__
744 /* On Android, ftruncate() always uses 32-bit offsets, even if
745 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000746 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000747 ** such attempts. */
748 if( sz>(sqlite3_int64)0x7FFFFFFF ){
749 rc = SQLITE_OK;
750 }else
751#endif
drh99ab3b12011-03-02 15:09:07 +0000752 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000753 return rc;
754}
drh734c9862008-11-28 15:37:20 +0000755
756/*
757** This routine translates a standard POSIX errno code into something
758** useful to the clients of the sqlite3 functions. Specifically, it is
759** intended to translate a variety of "try again" errors into SQLITE_BUSY
760** and a variety of "please close the file descriptor NOW" errors into
761** SQLITE_IOERR
762**
763** Errors during initialization of locks, or file system support for locks,
764** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
765*/
766static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000767 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
768 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
769 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
770 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000771 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000772 case EACCES:
drh734c9862008-11-28 15:37:20 +0000773 case EAGAIN:
774 case ETIMEDOUT:
775 case EBUSY:
776 case EINTR:
777 case ENOLCK:
778 /* random NFS retry error, unless during file system support
779 * introspection, in which it actually means what it says */
780 return SQLITE_BUSY;
781
drh734c9862008-11-28 15:37:20 +0000782 case EPERM:
783 return SQLITE_PERM;
784
drh734c9862008-11-28 15:37:20 +0000785 default:
786 return sqliteIOErr;
787 }
788}
789
790
drh734c9862008-11-28 15:37:20 +0000791/******************************************************************************
792****************** Begin Unique File ID Utility Used By VxWorks ***************
793**
794** On most versions of unix, we can get a unique ID for a file by concatenating
795** the device number and the inode number. But this does not work on VxWorks.
796** On VxWorks, a unique file id must be based on the canonical filename.
797**
798** A pointer to an instance of the following structure can be used as a
799** unique file ID in VxWorks. Each instance of this structure contains
800** a copy of the canonical filename. There is also a reference count.
801** The structure is reclaimed when the number of pointers to it drops to
802** zero.
803**
804** There are never very many files open at one time and lookups are not
805** a performance-critical path, so it is sufficient to put these
806** structures on a linked list.
807*/
808struct vxworksFileId {
809 struct vxworksFileId *pNext; /* Next in a list of them all */
810 int nRef; /* Number of references to this one */
811 int nName; /* Length of the zCanonicalName[] string */
812 char *zCanonicalName; /* Canonical filename */
813};
814
815#if OS_VXWORKS
816/*
drh9b35ea62008-11-29 02:20:26 +0000817** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000818** variable:
819*/
820static struct vxworksFileId *vxworksFileList = 0;
821
822/*
823** Simplify a filename into its canonical form
824** by making the following changes:
825**
826** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000827** * convert /./ into just /
828** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000829**
830** Changes are made in-place. Return the new name length.
831**
832** The original filename is in z[0..n-1]. Return the number of
833** characters in the simplified name.
834*/
835static int vxworksSimplifyName(char *z, int n){
836 int i, j;
837 while( n>1 && z[n-1]=='/' ){ n--; }
838 for(i=j=0; i<n; i++){
839 if( z[i]=='/' ){
840 if( z[i+1]=='/' ) continue;
841 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
842 i += 1;
843 continue;
844 }
845 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
846 while( j>0 && z[j-1]!='/' ){ j--; }
847 if( j>0 ){ j--; }
848 i += 2;
849 continue;
850 }
851 }
852 z[j++] = z[i];
853 }
854 z[j] = 0;
855 return j;
856}
857
858/*
859** Find a unique file ID for the given absolute pathname. Return
860** a pointer to the vxworksFileId object. This pointer is the unique
861** file ID.
862**
863** The nRef field of the vxworksFileId object is incremented before
864** the object is returned. A new vxworksFileId object is created
865** and added to the global list if necessary.
866**
867** If a memory allocation error occurs, return NULL.
868*/
869static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
870 struct vxworksFileId *pNew; /* search key and new file ID */
871 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
872 int n; /* Length of zAbsoluteName string */
873
874 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000875 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000876 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000877 if( pNew==0 ) return 0;
878 pNew->zCanonicalName = (char*)&pNew[1];
879 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
880 n = vxworksSimplifyName(pNew->zCanonicalName, n);
881
882 /* Search for an existing entry that matching the canonical name.
883 ** If found, increment the reference count and return a pointer to
884 ** the existing file ID.
885 */
886 unixEnterMutex();
887 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
888 if( pCandidate->nName==n
889 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
890 ){
891 sqlite3_free(pNew);
892 pCandidate->nRef++;
893 unixLeaveMutex();
894 return pCandidate;
895 }
896 }
897
898 /* No match was found. We will make a new file ID */
899 pNew->nRef = 1;
900 pNew->nName = n;
901 pNew->pNext = vxworksFileList;
902 vxworksFileList = pNew;
903 unixLeaveMutex();
904 return pNew;
905}
906
907/*
908** Decrement the reference count on a vxworksFileId object. Free
909** the object when the reference count reaches zero.
910*/
911static void vxworksReleaseFileId(struct vxworksFileId *pId){
912 unixEnterMutex();
913 assert( pId->nRef>0 );
914 pId->nRef--;
915 if( pId->nRef==0 ){
916 struct vxworksFileId **pp;
917 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
918 assert( *pp==pId );
919 *pp = pId->pNext;
920 sqlite3_free(pId);
921 }
922 unixLeaveMutex();
923}
924#endif /* OS_VXWORKS */
925/*************** End of Unique File ID Utility Used By VxWorks ****************
926******************************************************************************/
927
928
929/******************************************************************************
930*************************** Posix Advisory Locking ****************************
931**
drh9b35ea62008-11-29 02:20:26 +0000932** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000933** section 6.5.2.2 lines 483 through 490 specify that when a process
934** sets or clears a lock, that operation overrides any prior locks set
935** by the same process. It does not explicitly say so, but this implies
936** that it overrides locks set by the same process using a different
937** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000938**
939** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000940** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
941**
942** Suppose ./file1 and ./file2 are really the same file (because
943** one is a hard or symbolic link to the other) then if you set
944** an exclusive lock on fd1, then try to get an exclusive lock
945** on fd2, it works. I would have expected the second lock to
946** fail since there was already a lock on the file due to fd1.
947** But not so. Since both locks came from the same process, the
948** second overrides the first, even though they were on different
949** file descriptors opened on different file names.
950**
drh734c9862008-11-28 15:37:20 +0000951** This means that we cannot use POSIX locks to synchronize file access
952** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000953** to synchronize access for threads in separate processes, but not
954** threads within the same process.
955**
956** To work around the problem, SQLite has to manage file locks internally
957** on its own. Whenever a new database is opened, we have to find the
958** specific inode of the database file (the inode is determined by the
959** st_dev and st_ino fields of the stat structure that fstat() fills in)
960** and check for locks already existing on that inode. When locks are
961** created or removed, we have to look at our own internal record of the
962** locks to see if another thread has previously set a lock on that same
963** inode.
964**
drh9b35ea62008-11-29 02:20:26 +0000965** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
966** For VxWorks, we have to use the alternative unique ID system based on
967** canonical filename and implemented in the previous division.)
968**
danielk1977ad94b582007-08-20 06:44:22 +0000969** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000970** descriptor. It is now a structure that holds the integer file
971** descriptor and a pointer to a structure that describes the internal
972** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000973** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000974** point to the same locking structure. The locking structure keeps
975** a reference count (so we will know when to delete it) and a "cnt"
976** field that tells us its internal lock status. cnt==0 means the
977** file is unlocked. cnt==-1 means the file has an exclusive lock.
978** cnt>0 means there are cnt shared locks on the file.
979**
980** Any attempt to lock or unlock a file first checks the locking
981** structure. The fcntl() system call is only invoked to set a
982** POSIX lock if the internal lock structure transitions between
983** a locked and an unlocked state.
984**
drh734c9862008-11-28 15:37:20 +0000985** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000986**
987** If you close a file descriptor that points to a file that has locks,
988** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000989** released. To work around this problem, each unixInodeInfo object
990** maintains a count of the number of pending locks on tha inode.
991** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000992** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000993** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000994** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000995** be closed and that list is walked (and cleared) when the last lock
996** clears.
997**
drh9b35ea62008-11-29 02:20:26 +0000998** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000999**
drh9b35ea62008-11-29 02:20:26 +00001000** Many older versions of linux use the LinuxThreads library which is
1001** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001002** A cannot be modified or overridden by a different thread B.
1003** Only thread A can modify the lock. Locking behavior is correct
1004** if the appliation uses the newer Native Posix Thread Library (NPTL)
1005** on linux - with NPTL a lock created by thread A can override locks
1006** in thread B. But there is no way to know at compile-time which
1007** threading library is being used. So there is no way to know at
1008** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001009** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001010** current process.
drh5fdae772004-06-29 03:29:00 +00001011**
drh8af6c222010-05-14 12:43:01 +00001012** SQLite used to support LinuxThreads. But support for LinuxThreads
1013** was dropped beginning with version 3.7.0. SQLite will still work with
1014** LinuxThreads provided that (1) there is no more than one connection
1015** per database file in the same process and (2) database connections
1016** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001017*/
1018
1019/*
1020** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001021** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001022*/
1023struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001024 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001025#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001026 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001027#else
drh107886a2008-11-21 22:21:50 +00001028 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001029#endif
1030};
1031
1032/*
drhbbd42a62004-05-22 17:41:58 +00001033** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001034** inode. Or, on LinuxThreads, there is one of these structures for
1035** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001036**
danielk1977ad94b582007-08-20 06:44:22 +00001037** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001038** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001039** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001040*/
drh8af6c222010-05-14 12:43:01 +00001041struct unixInodeInfo {
1042 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001043 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001044 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1045 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001046 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001047 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1048 int nLock; /* Number of outstanding file locks */
1049 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1050 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1051 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001052#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001053 unsigned long long sharedByte; /* for AFP simulated shared lock */
1054#endif
drh6c7d5c52008-11-21 20:32:33 +00001055#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001056 sem_t *pSem; /* Named POSIX semaphore */
1057 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001058#endif
drhbbd42a62004-05-22 17:41:58 +00001059};
1060
drhda0e7682008-07-30 15:27:54 +00001061/*
drh8af6c222010-05-14 12:43:01 +00001062** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001063*/
drhd91c68f2010-05-14 14:52:25 +00001064static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001065
drh5fdae772004-06-29 03:29:00 +00001066/*
dane18d4952011-02-21 11:46:24 +00001067**
drhaaeaa182015-11-24 15:12:47 +00001068** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001069** unixLogError().
1070**
1071** It is invoked after an error occurs in an OS function and errno has been
1072** set. It logs a message using sqlite3_log() containing the current value of
1073** errno and, if possible, the human-readable equivalent from strerror() or
1074** strerror_r().
1075**
1076** The first argument passed to the macro should be the error code that
1077** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1078** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001079** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001080** if any.
1081*/
drh0e9365c2011-03-02 02:08:13 +00001082#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1083static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001084 int errcode, /* SQLite error code */
1085 const char *zFunc, /* Name of OS function that failed */
1086 const char *zPath, /* File path associated with error */
1087 int iLine /* Source line number where error occurred */
1088){
1089 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001090 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001091
1092 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1093 ** the strerror() function to obtain the human-readable error message
1094 ** equivalent to errno. Otherwise, use strerror_r().
1095 */
1096#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1097 char aErr[80];
1098 memset(aErr, 0, sizeof(aErr));
1099 zErr = aErr;
1100
1101 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001102 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001103 ** returns a pointer to a buffer containing the error message. That pointer
1104 ** may point to aErr[], or it may point to some static storage somewhere.
1105 ** Otherwise, assume that the system provides the POSIX version of
1106 ** strerror_r(), which always writes an error message into aErr[].
1107 **
1108 ** If the code incorrectly assumes that it is the POSIX version that is
1109 ** available, the error message will often be an empty string. Not a
1110 ** huge problem. Incorrectly concluding that the GNU version is available
1111 ** could lead to a segfault though.
1112 */
1113#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1114 zErr =
1115# endif
drh0e9365c2011-03-02 02:08:13 +00001116 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001117
1118#elif SQLITE_THREADSAFE
1119 /* This is a threadsafe build, but strerror_r() is not available. */
1120 zErr = "";
1121#else
1122 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001123 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001124#endif
1125
drh0e9365c2011-03-02 02:08:13 +00001126 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001127 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001128 "os_unix.c:%d: (%d) %s(%s) - %s",
1129 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001130 );
1131
1132 return errcode;
1133}
1134
drh0e9365c2011-03-02 02:08:13 +00001135/*
1136** Close a file descriptor.
1137**
1138** We assume that close() almost always works, since it is only in a
1139** very sick application or on a very sick platform that it might fail.
1140** If it does fail, simply leak the file descriptor, but do log the
1141** error.
1142**
1143** Note that it is not safe to retry close() after EINTR since the
1144** file descriptor might have already been reused by another thread.
1145** So we don't even try to recover from an EINTR. Just log the error
1146** and move on.
1147*/
1148static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001149 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001150 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1151 pFile ? pFile->zPath : 0, lineno);
1152 }
1153}
dane18d4952011-02-21 11:46:24 +00001154
1155/*
drhe6d41732015-02-21 00:49:00 +00001156** Set the pFile->lastErrno. Do this in a subroutine as that provides
1157** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001158*/
1159static void storeLastErrno(unixFile *pFile, int error){
1160 pFile->lastErrno = error;
1161}
1162
1163/*
danb0ac3e32010-06-16 10:55:42 +00001164** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001165*/
drh0e9365c2011-03-02 02:08:13 +00001166static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001167 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001168 UnixUnusedFd *p;
1169 UnixUnusedFd *pNext;
1170 for(p=pInode->pUnused; p; p=pNext){
1171 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001172 robust_close(pFile, p->fd, __LINE__);
1173 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001174 }
drh0e9365c2011-03-02 02:08:13 +00001175 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001176}
1177
1178/*
drh8af6c222010-05-14 12:43:01 +00001179** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001180**
1181** The mutex entered using the unixEnterMutex() function must be held
1182** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001183*/
danb0ac3e32010-06-16 10:55:42 +00001184static void releaseInodeInfo(unixFile *pFile){
1185 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001186 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001187 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001188 pInode->nRef--;
1189 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001190 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001191 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001192 if( pInode->pPrev ){
1193 assert( pInode->pPrev->pNext==pInode );
1194 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001195 }else{
drh8af6c222010-05-14 12:43:01 +00001196 assert( inodeList==pInode );
1197 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001198 }
drh8af6c222010-05-14 12:43:01 +00001199 if( pInode->pNext ){
1200 assert( pInode->pNext->pPrev==pInode );
1201 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001202 }
drh8af6c222010-05-14 12:43:01 +00001203 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001204 }
drhbbd42a62004-05-22 17:41:58 +00001205 }
1206}
1207
1208/*
drh8af6c222010-05-14 12:43:01 +00001209** Given a file descriptor, locate the unixInodeInfo object that
1210** describes that file descriptor. Create a new one if necessary. The
1211** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001212**
dan9359c7b2009-08-21 08:29:10 +00001213** The mutex entered using the unixEnterMutex() function must be held
1214** when this function is called.
1215**
drh6c7d5c52008-11-21 20:32:33 +00001216** Return an appropriate error code.
1217*/
drh8af6c222010-05-14 12:43:01 +00001218static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001219 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001220 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001221){
1222 int rc; /* System call return code */
1223 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001224 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1225 struct stat statbuf; /* Low-level file information */
1226 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001227
dan9359c7b2009-08-21 08:29:10 +00001228 assert( unixMutexHeld() );
1229
drh6c7d5c52008-11-21 20:32:33 +00001230 /* Get low-level information about the file that we can used to
1231 ** create a unique name for the file.
1232 */
1233 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001234 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001235 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001236 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001237#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001238 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1239#endif
1240 return SQLITE_IOERR;
1241 }
1242
drheb0d74f2009-02-03 15:27:02 +00001243#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001244 /* On OS X on an msdos filesystem, the inode number is reported
1245 ** incorrectly for zero-size files. See ticket #3260. To work
1246 ** around this problem (we consider it a bug in OS X, not SQLite)
1247 ** we always increase the file size to 1 by writing a single byte
1248 ** prior to accessing the inode number. The one byte written is
1249 ** an ASCII 'S' character which also happens to be the first byte
1250 ** in the header of every SQLite database. In this way, if there
1251 ** is a race condition such that another thread has already populated
1252 ** the first page of the database, no damage is done.
1253 */
drh7ed97b92010-01-20 13:07:21 +00001254 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001255 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001256 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001257 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001258 return SQLITE_IOERR;
1259 }
drh99ab3b12011-03-02 15:09:07 +00001260 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001261 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001262 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001263 return SQLITE_IOERR;
1264 }
1265 }
drheb0d74f2009-02-03 15:27:02 +00001266#endif
drh6c7d5c52008-11-21 20:32:33 +00001267
drh8af6c222010-05-14 12:43:01 +00001268 memset(&fileId, 0, sizeof(fileId));
1269 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001270#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001271 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001272#else
drh8af6c222010-05-14 12:43:01 +00001273 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001274#endif
drh8af6c222010-05-14 12:43:01 +00001275 pInode = inodeList;
1276 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1277 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001278 }
drh8af6c222010-05-14 12:43:01 +00001279 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001280 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001281 if( pInode==0 ){
1282 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001283 }
drh8af6c222010-05-14 12:43:01 +00001284 memset(pInode, 0, sizeof(*pInode));
1285 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1286 pInode->nRef = 1;
1287 pInode->pNext = inodeList;
1288 pInode->pPrev = 0;
1289 if( inodeList ) inodeList->pPrev = pInode;
1290 inodeList = pInode;
1291 }else{
1292 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001293 }
drh8af6c222010-05-14 12:43:01 +00001294 *ppInode = pInode;
1295 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001296}
drh6c7d5c52008-11-21 20:32:33 +00001297
drhb959a012013-12-07 12:29:22 +00001298/*
1299** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1300*/
1301static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001302#if OS_VXWORKS
1303 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1304#else
drhb959a012013-12-07 12:29:22 +00001305 struct stat buf;
1306 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001307 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001308#endif
drhb959a012013-12-07 12:29:22 +00001309}
1310
aswift5b1a2562008-08-22 00:22:35 +00001311
1312/*
drhfbc7e882013-04-11 01:16:15 +00001313** Check a unixFile that is a database. Verify the following:
1314**
1315** (1) There is exactly one hard link on the file
1316** (2) The file is not a symbolic link
1317** (3) The file has not been renamed or unlinked
1318**
1319** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1320*/
1321static void verifyDbFile(unixFile *pFile){
1322 struct stat buf;
1323 int rc;
drhfbc7e882013-04-11 01:16:15 +00001324 rc = osFstat(pFile->h, &buf);
1325 if( rc!=0 ){
1326 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001327 return;
1328 }
drh3044b512014-06-16 16:41:52 +00001329 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001330 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001331 return;
1332 }
1333 if( buf.st_nlink>1 ){
1334 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001335 return;
1336 }
drhb959a012013-12-07 12:29:22 +00001337 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001338 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001339 return;
1340 }
1341}
1342
1343
1344/*
danielk197713adf8a2004-06-03 16:08:41 +00001345** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001346** file by this or any other process. If such a lock is held, set *pResOut
1347** to a non-zero value otherwise *pResOut is set to zero. The return value
1348** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001349*/
danielk1977861f7452008-06-05 11:39:11 +00001350static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001351 int rc = SQLITE_OK;
1352 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001353 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001354
danielk1977861f7452008-06-05 11:39:11 +00001355 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1356
drh054889e2005-11-30 03:20:31 +00001357 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001358 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001359 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001360
1361 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001362 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001363 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001364 }
1365
drh2ac3ee92004-06-07 16:27:46 +00001366 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001367 */
danielk197709480a92009-02-09 05:32:32 +00001368#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001369 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001370 struct flock lock;
1371 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001372 lock.l_start = RESERVED_BYTE;
1373 lock.l_len = 1;
1374 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001375 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1376 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001377 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001378 } else if( lock.l_type!=F_UNLCK ){
1379 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001380 }
1381 }
danielk197709480a92009-02-09 05:32:32 +00001382#endif
danielk197713adf8a2004-06-03 16:08:41 +00001383
drh6c7d5c52008-11-21 20:32:33 +00001384 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001385 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001386
aswift5b1a2562008-08-22 00:22:35 +00001387 *pResOut = reserved;
1388 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001389}
1390
1391/*
drha7e61d82011-03-12 17:02:57 +00001392** Attempt to set a system-lock on the file pFile. The lock is
1393** described by pLock.
1394**
drh77197112011-03-15 19:08:48 +00001395** If the pFile was opened read/write from unix-excl, then the only lock
1396** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001397** the first time any lock is attempted. All subsequent system locking
1398** operations become no-ops. Locking operations still happen internally,
1399** in order to coordinate access between separate database connections
1400** within this process, but all of that is handled in memory and the
1401** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001402**
1403** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1404** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1405** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001406**
1407** Zero is returned if the call completes successfully, or -1 if a call
1408** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001409*/
1410static int unixFileLock(unixFile *pFile, struct flock *pLock){
1411 int rc;
drh3cb93392011-03-12 18:10:44 +00001412 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001413 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001414 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001415 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001416 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001417 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001418 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001419 lock.l_whence = SEEK_SET;
1420 lock.l_start = SHARED_FIRST;
1421 lock.l_len = SHARED_SIZE;
1422 lock.l_type = F_WRLCK;
1423 rc = osFcntl(pFile->h, F_SETLK, &lock);
1424 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001425 pInode->bProcessLock = 1;
1426 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001427 }else{
1428 rc = 0;
1429 }
1430 }else{
1431 rc = osFcntl(pFile->h, F_SETLK, pLock);
1432 }
1433 return rc;
1434}
1435
1436/*
drh308c2a52010-05-14 11:30:18 +00001437** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001438** of the following:
1439**
drh2ac3ee92004-06-07 16:27:46 +00001440** (1) SHARED_LOCK
1441** (2) RESERVED_LOCK
1442** (3) PENDING_LOCK
1443** (4) EXCLUSIVE_LOCK
1444**
drhb3e04342004-06-08 00:47:47 +00001445** Sometimes when requesting one lock state, additional lock states
1446** are inserted in between. The locking might fail on one of the later
1447** transitions leaving the lock state different from what it started but
1448** still short of its goal. The following chart shows the allowed
1449** transitions and the inserted intermediate states:
1450**
1451** UNLOCKED -> SHARED
1452** SHARED -> RESERVED
1453** SHARED -> (PENDING) -> EXCLUSIVE
1454** RESERVED -> (PENDING) -> EXCLUSIVE
1455** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001456**
drha6abd042004-06-09 17:37:22 +00001457** This routine will only increase a lock. Use the sqlite3OsUnlock()
1458** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001459*/
drh308c2a52010-05-14 11:30:18 +00001460static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001461 /* The following describes the implementation of the various locks and
1462 ** lock transitions in terms of the POSIX advisory shared and exclusive
1463 ** lock primitives (called read-locks and write-locks below, to avoid
1464 ** confusion with SQLite lock names). The algorithms are complicated
1465 ** slightly in order to be compatible with windows systems simultaneously
1466 ** accessing the same database file, in case that is ever required.
1467 **
1468 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1469 ** byte', each single bytes at well known offsets, and the 'shared byte
1470 ** range', a range of 510 bytes at a well known offset.
1471 **
1472 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1473 ** byte'. If this is successful, a random byte from the 'shared byte
1474 ** range' is read-locked and the lock on the 'pending byte' released.
1475 **
danielk197790ba3bd2004-06-25 08:32:25 +00001476 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1477 ** A RESERVED lock is implemented by grabbing a write-lock on the
1478 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001479 **
1480 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001481 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1482 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1483 ** obtained, but existing SHARED locks are allowed to persist. A process
1484 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1485 ** This property is used by the algorithm for rolling back a journal file
1486 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001487 **
danielk197790ba3bd2004-06-25 08:32:25 +00001488 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1489 ** implemented by obtaining a write-lock on the entire 'shared byte
1490 ** range'. Since all other locks require a read-lock on one of the bytes
1491 ** within this range, this ensures that no other locks are held on the
1492 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001493 **
1494 ** The reason a single byte cannot be used instead of the 'shared byte
1495 ** range' is that some versions of windows do not support read-locks. By
1496 ** locking a random byte from a range, concurrent SHARED locks may exist
1497 ** even if the locking primitive used is always a write-lock.
1498 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001499 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001500 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001501 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001502 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001503 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001504
drh054889e2005-11-30 03:20:31 +00001505 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001506 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1507 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001508 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001509 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001510
1511 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001512 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001513 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001514 */
drh308c2a52010-05-14 11:30:18 +00001515 if( pFile->eFileLock>=eFileLock ){
1516 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1517 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001518 return SQLITE_OK;
1519 }
1520
drh0c2694b2009-09-03 16:23:44 +00001521 /* Make sure the locking sequence is correct.
1522 ** (1) We never move from unlocked to anything higher than shared lock.
1523 ** (2) SQLite never explicitly requests a pendig lock.
1524 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001525 */
drh308c2a52010-05-14 11:30:18 +00001526 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1527 assert( eFileLock!=PENDING_LOCK );
1528 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001529
drh8af6c222010-05-14 12:43:01 +00001530 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001531 */
drh6c7d5c52008-11-21 20:32:33 +00001532 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001533 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001534
danielk1977ad94b582007-08-20 06:44:22 +00001535 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001536 ** handle that precludes the requested lock, return BUSY.
1537 */
drh8af6c222010-05-14 12:43:01 +00001538 if( (pFile->eFileLock!=pInode->eFileLock &&
1539 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001540 ){
1541 rc = SQLITE_BUSY;
1542 goto end_lock;
1543 }
1544
1545 /* If a SHARED lock is requested, and some thread using this PID already
1546 ** has a SHARED or RESERVED lock, then increment reference counts and
1547 ** return SQLITE_OK.
1548 */
drh308c2a52010-05-14 11:30:18 +00001549 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001550 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001551 assert( eFileLock==SHARED_LOCK );
1552 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001553 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001554 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001555 pInode->nShared++;
1556 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001557 goto end_lock;
1558 }
1559
danielk19779a1d0ab2004-06-01 14:09:28 +00001560
drh3cde3bb2004-06-12 02:17:14 +00001561 /* A PENDING lock is needed before acquiring a SHARED lock and before
1562 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1563 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001564 */
drh0c2694b2009-09-03 16:23:44 +00001565 lock.l_len = 1L;
1566 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001567 if( eFileLock==SHARED_LOCK
1568 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001569 ){
drh308c2a52010-05-14 11:30:18 +00001570 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001571 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001572 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001573 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001574 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001575 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001576 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001577 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001578 goto end_lock;
1579 }
drh3cde3bb2004-06-12 02:17:14 +00001580 }
1581
1582
1583 /* If control gets to this point, then actually go ahead and make
1584 ** operating system calls for the specified lock.
1585 */
drh308c2a52010-05-14 11:30:18 +00001586 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001587 assert( pInode->nShared==0 );
1588 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001589 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001590
drh2ac3ee92004-06-07 16:27:46 +00001591 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001592 lock.l_start = SHARED_FIRST;
1593 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001594 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001595 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001596 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001597 }
dan661d71a2011-03-30 19:08:03 +00001598
drh2ac3ee92004-06-07 16:27:46 +00001599 /* Drop the temporary PENDING lock */
1600 lock.l_start = PENDING_BYTE;
1601 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001602 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001603 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1604 /* This could happen with a network mount */
1605 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001606 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001607 }
dan661d71a2011-03-30 19:08:03 +00001608
1609 if( rc ){
1610 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001611 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001612 }
dan661d71a2011-03-30 19:08:03 +00001613 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001614 }else{
drh308c2a52010-05-14 11:30:18 +00001615 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001616 pInode->nLock++;
1617 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001618 }
drh8af6c222010-05-14 12:43:01 +00001619 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001620 /* We are trying for an exclusive lock but another thread in this
1621 ** same process is still holding a shared lock. */
1622 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001623 }else{
drh3cde3bb2004-06-12 02:17:14 +00001624 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001625 ** assumed that there is a SHARED or greater lock on the file
1626 ** already.
1627 */
drh308c2a52010-05-14 11:30:18 +00001628 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001629 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001630
1631 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1632 if( eFileLock==RESERVED_LOCK ){
1633 lock.l_start = RESERVED_BYTE;
1634 lock.l_len = 1L;
1635 }else{
1636 lock.l_start = SHARED_FIRST;
1637 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001638 }
dan661d71a2011-03-30 19:08:03 +00001639
1640 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001641 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001642 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001643 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001644 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001645 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001646 }
drhbbd42a62004-05-22 17:41:58 +00001647 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001648
drh8f941bc2009-01-14 23:03:40 +00001649
drhd3d8c042012-05-29 17:02:40 +00001650#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001651 /* Set up the transaction-counter change checking flags when
1652 ** transitioning from a SHARED to a RESERVED lock. The change
1653 ** from SHARED to RESERVED marks the beginning of a normal
1654 ** write operation (not a hot journal rollback).
1655 */
1656 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001657 && pFile->eFileLock<=SHARED_LOCK
1658 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001659 ){
1660 pFile->transCntrChng = 0;
1661 pFile->dbUpdate = 0;
1662 pFile->inNormalWrite = 1;
1663 }
1664#endif
1665
1666
danielk1977ecb2a962004-06-02 06:30:16 +00001667 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001668 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001669 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001670 }else if( eFileLock==EXCLUSIVE_LOCK ){
1671 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001672 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001673 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001674
1675end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001676 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001677 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1678 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001679 return rc;
1680}
1681
1682/*
dan08da86a2009-08-21 17:18:03 +00001683** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001684** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001685*/
1686static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001687 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001688 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001689 p->pNext = pInode->pUnused;
1690 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001691 pFile->h = -1;
1692 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001693}
1694
1695/*
drh308c2a52010-05-14 11:30:18 +00001696** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001697** must be either NO_LOCK or SHARED_LOCK.
1698**
1699** If the locking level of the file descriptor is already at or below
1700** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001701**
1702** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1703** the byte range is divided into 2 parts and the first part is unlocked then
1704** set to a read lock, then the other part is simply unlocked. This works
1705** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1706** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001707*/
drha7e61d82011-03-12 17:02:57 +00001708static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001709 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001710 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001711 struct flock lock;
1712 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001713
drh054889e2005-11-30 03:20:31 +00001714 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001715 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001716 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001717 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001718
drh308c2a52010-05-14 11:30:18 +00001719 assert( eFileLock<=SHARED_LOCK );
1720 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001721 return SQLITE_OK;
1722 }
drh6c7d5c52008-11-21 20:32:33 +00001723 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001724 pInode = pFile->pInode;
1725 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001726 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001727 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001728
drhd3d8c042012-05-29 17:02:40 +00001729#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001730 /* When reducing a lock such that other processes can start
1731 ** reading the database file again, make sure that the
1732 ** transaction counter was updated if any part of the database
1733 ** file changed. If the transaction counter is not updated,
1734 ** other connections to the same file might not realize that
1735 ** the file has changed and hence might not know to flush their
1736 ** cache. The use of a stale cache can lead to database corruption.
1737 */
drh8f941bc2009-01-14 23:03:40 +00001738 pFile->inNormalWrite = 0;
1739#endif
1740
drh7ed97b92010-01-20 13:07:21 +00001741 /* downgrading to a shared lock on NFS involves clearing the write lock
1742 ** before establishing the readlock - to avoid a race condition we downgrade
1743 ** the lock in 2 blocks, so that part of the range will be covered by a
1744 ** write lock until the rest is covered by a read lock:
1745 ** 1: [WWWWW]
1746 ** 2: [....W]
1747 ** 3: [RRRRW]
1748 ** 4: [RRRR.]
1749 */
drh308c2a52010-05-14 11:30:18 +00001750 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001751#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001752 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001753 assert( handleNFSUnlock==0 );
1754#endif
1755#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001756 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001757 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001758 off_t divSize = SHARED_SIZE - 1;
1759
1760 lock.l_type = F_UNLCK;
1761 lock.l_whence = SEEK_SET;
1762 lock.l_start = SHARED_FIRST;
1763 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001764 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001765 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001766 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001767 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001768 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001769 }
drh7ed97b92010-01-20 13:07:21 +00001770 lock.l_type = F_RDLCK;
1771 lock.l_whence = SEEK_SET;
1772 lock.l_start = SHARED_FIRST;
1773 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001774 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001775 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001776 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1777 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001778 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001779 }
1780 goto end_unlock;
1781 }
1782 lock.l_type = F_UNLCK;
1783 lock.l_whence = SEEK_SET;
1784 lock.l_start = SHARED_FIRST+divSize;
1785 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001786 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001787 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001788 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001789 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001790 goto end_unlock;
1791 }
drh30f776f2011-02-25 03:25:07 +00001792 }else
1793#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1794 {
drh7ed97b92010-01-20 13:07:21 +00001795 lock.l_type = F_RDLCK;
1796 lock.l_whence = SEEK_SET;
1797 lock.l_start = SHARED_FIRST;
1798 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001799 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001800 /* In theory, the call to unixFileLock() cannot fail because another
1801 ** process is holding an incompatible lock. If it does, this
1802 ** indicates that the other process is not following the locking
1803 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1804 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1805 ** an assert to fail). */
1806 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001807 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001808 goto end_unlock;
1809 }
drh9c105bb2004-10-02 20:38:28 +00001810 }
1811 }
drhbbd42a62004-05-22 17:41:58 +00001812 lock.l_type = F_UNLCK;
1813 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001814 lock.l_start = PENDING_BYTE;
1815 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001816 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001817 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001818 }else{
danea83bc62011-04-01 11:56:32 +00001819 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001820 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001821 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001822 }
drhbbd42a62004-05-22 17:41:58 +00001823 }
drh308c2a52010-05-14 11:30:18 +00001824 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001825 /* Decrement the shared lock counter. Release the lock using an
1826 ** OS call only when all threads in this same process have released
1827 ** the lock.
1828 */
drh8af6c222010-05-14 12:43:01 +00001829 pInode->nShared--;
1830 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001831 lock.l_type = F_UNLCK;
1832 lock.l_whence = SEEK_SET;
1833 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001834 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001835 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001836 }else{
danea83bc62011-04-01 11:56:32 +00001837 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001838 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001839 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001840 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001841 }
drha6abd042004-06-09 17:37:22 +00001842 }
1843
drhbbd42a62004-05-22 17:41:58 +00001844 /* Decrement the count of locks against this same file. When the
1845 ** count reaches zero, close any other file descriptors whose close
1846 ** was deferred because of outstanding locks.
1847 */
drh8af6c222010-05-14 12:43:01 +00001848 pInode->nLock--;
1849 assert( pInode->nLock>=0 );
1850 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001851 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001852 }
1853 }
drhf2f105d2012-08-20 15:53:54 +00001854
aswift5b1a2562008-08-22 00:22:35 +00001855end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001856 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001857 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001858 return rc;
drhbbd42a62004-05-22 17:41:58 +00001859}
1860
1861/*
drh308c2a52010-05-14 11:30:18 +00001862** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001863** must be either NO_LOCK or SHARED_LOCK.
1864**
1865** If the locking level of the file descriptor is already at or below
1866** the requested locking level, this routine is a no-op.
1867*/
drh308c2a52010-05-14 11:30:18 +00001868static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001869#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001870 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001871#endif
drha7e61d82011-03-12 17:02:57 +00001872 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001873}
1874
mistachkine98844f2013-08-24 00:59:24 +00001875#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001876static int unixMapfile(unixFile *pFd, i64 nByte);
1877static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001878#endif
danf23da962013-03-23 21:00:41 +00001879
drh7ed97b92010-01-20 13:07:21 +00001880/*
danielk1977e339d652008-06-28 11:23:00 +00001881** This function performs the parts of the "close file" operation
1882** common to all locking schemes. It closes the directory and file
1883** handles, if they are valid, and sets all fields of the unixFile
1884** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001885**
1886** It is *not* necessary to hold the mutex when this routine is called,
1887** even on VxWorks. A mutex will be acquired on VxWorks by the
1888** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001889*/
1890static int closeUnixFile(sqlite3_file *id){
1891 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001892#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001893 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001894#endif
dan661d71a2011-03-30 19:08:03 +00001895 if( pFile->h>=0 ){
1896 robust_close(pFile, pFile->h, __LINE__);
1897 pFile->h = -1;
1898 }
1899#if OS_VXWORKS
1900 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001901 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001902 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001903 }
1904 vxworksReleaseFileId(pFile->pId);
1905 pFile->pId = 0;
1906 }
1907#endif
drh0bdbc902014-06-16 18:35:06 +00001908#ifdef SQLITE_UNLINK_AFTER_CLOSE
1909 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1910 osUnlink(pFile->zPath);
1911 sqlite3_free(*(char**)&pFile->zPath);
1912 pFile->zPath = 0;
1913 }
1914#endif
dan661d71a2011-03-30 19:08:03 +00001915 OSTRACE(("CLOSE %-3d\n", pFile->h));
1916 OpenCounter(-1);
1917 sqlite3_free(pFile->pUnused);
1918 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001919 return SQLITE_OK;
1920}
1921
1922/*
danielk1977e3026632004-06-22 11:29:02 +00001923** Close a file.
1924*/
danielk197762079062007-08-15 17:08:46 +00001925static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001926 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001927 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001928 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001929 unixUnlock(id, NO_LOCK);
1930 unixEnterMutex();
1931
1932 /* unixFile.pInode is always valid here. Otherwise, a different close
1933 ** routine (e.g. nolockClose()) would be called instead.
1934 */
1935 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1936 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1937 /* If there are outstanding locks, do not actually close the file just
1938 ** yet because that would clear those locks. Instead, add the file
1939 ** descriptor to pInode->pUnused list. It will be automatically closed
1940 ** when the last lock is cleared.
1941 */
1942 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001943 }
dan661d71a2011-03-30 19:08:03 +00001944 releaseInodeInfo(pFile);
1945 rc = closeUnixFile(id);
1946 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001947 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001948}
1949
drh734c9862008-11-28 15:37:20 +00001950/************** End of the posix advisory lock implementation *****************
1951******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001952
drh734c9862008-11-28 15:37:20 +00001953/******************************************************************************
1954****************************** No-op Locking **********************************
1955**
1956** Of the various locking implementations available, this is by far the
1957** simplest: locking is ignored. No attempt is made to lock the database
1958** file for reading or writing.
1959**
1960** This locking mode is appropriate for use on read-only databases
1961** (ex: databases that are burned into CD-ROM, for example.) It can
1962** also be used if the application employs some external mechanism to
1963** prevent simultaneous access of the same database by two or more
1964** database connections. But there is a serious risk of database
1965** corruption if this locking mode is used in situations where multiple
1966** database connections are accessing the same database file at the same
1967** time and one or more of those connections are writing.
1968*/
drhbfe66312006-10-03 17:40:40 +00001969
drh734c9862008-11-28 15:37:20 +00001970static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1971 UNUSED_PARAMETER(NotUsed);
1972 *pResOut = 0;
1973 return SQLITE_OK;
1974}
drh734c9862008-11-28 15:37:20 +00001975static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1976 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1977 return SQLITE_OK;
1978}
drh734c9862008-11-28 15:37:20 +00001979static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1980 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1981 return SQLITE_OK;
1982}
1983
1984/*
drh9b35ea62008-11-29 02:20:26 +00001985** Close the file.
drh734c9862008-11-28 15:37:20 +00001986*/
1987static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001988 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001989}
1990
1991/******************* End of the no-op lock implementation *********************
1992******************************************************************************/
1993
1994/******************************************************************************
1995************************* Begin dot-file Locking ******************************
1996**
mistachkin48864df2013-03-21 21:20:32 +00001997** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001998** files (really a directory) to control access to the database. This works
1999** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002000**
2001** (1) There is zero concurrency. A single reader blocks all other
2002** connections from reading or writing the database.
2003**
2004** (2) An application crash or power loss can leave stale lock files
2005** sitting around that need to be cleared manually.
2006**
2007** Nevertheless, a dotlock is an appropriate locking mode for use if no
2008** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002009**
drh9ef6bc42011-11-04 02:24:02 +00002010** Dotfile locking works by creating a subdirectory in the same directory as
2011** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002012** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002013** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002014*/
2015
2016/*
2017** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002018** lock directory.
drh734c9862008-11-28 15:37:20 +00002019*/
2020#define DOTLOCK_SUFFIX ".lock"
2021
drh7708e972008-11-29 00:56:52 +00002022/*
2023** This routine checks if there is a RESERVED lock held on the specified
2024** file by this or any other process. If such a lock is held, set *pResOut
2025** to a non-zero value otherwise *pResOut is set to zero. The return value
2026** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2027**
2028** In dotfile locking, either a lock exists or it does not. So in this
2029** variation of CheckReservedLock(), *pResOut is set to true if any lock
2030** is held on the file and false if the file is unlocked.
2031*/
drh734c9862008-11-28 15:37:20 +00002032static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2033 int rc = SQLITE_OK;
2034 int reserved = 0;
2035 unixFile *pFile = (unixFile*)id;
2036
2037 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2038
2039 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002040 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002041 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002042 *pResOut = reserved;
2043 return rc;
2044}
2045
drh7708e972008-11-29 00:56:52 +00002046/*
drh308c2a52010-05-14 11:30:18 +00002047** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002048** of the following:
2049**
2050** (1) SHARED_LOCK
2051** (2) RESERVED_LOCK
2052** (3) PENDING_LOCK
2053** (4) EXCLUSIVE_LOCK
2054**
2055** Sometimes when requesting one lock state, additional lock states
2056** are inserted in between. The locking might fail on one of the later
2057** transitions leaving the lock state different from what it started but
2058** still short of its goal. The following chart shows the allowed
2059** transitions and the inserted intermediate states:
2060**
2061** UNLOCKED -> SHARED
2062** SHARED -> RESERVED
2063** SHARED -> (PENDING) -> EXCLUSIVE
2064** RESERVED -> (PENDING) -> EXCLUSIVE
2065** PENDING -> EXCLUSIVE
2066**
2067** This routine will only increase a lock. Use the sqlite3OsUnlock()
2068** routine to lower a locking level.
2069**
2070** With dotfile locking, we really only support state (4): EXCLUSIVE.
2071** But we track the other locking levels internally.
2072*/
drh308c2a52010-05-14 11:30:18 +00002073static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002074 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002075 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002076 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002077
drh7708e972008-11-29 00:56:52 +00002078
2079 /* If we have any lock, then the lock file already exists. All we have
2080 ** to do is adjust our internal record of the lock level.
2081 */
drh308c2a52010-05-14 11:30:18 +00002082 if( pFile->eFileLock > NO_LOCK ){
2083 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002084 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002085#ifdef HAVE_UTIME
2086 utime(zLockFile, NULL);
2087#else
drh734c9862008-11-28 15:37:20 +00002088 utimes(zLockFile, NULL);
2089#endif
drh7708e972008-11-29 00:56:52 +00002090 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002091 }
2092
2093 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002094 rc = osMkdir(zLockFile, 0777);
2095 if( rc<0 ){
2096 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002097 int tErrno = errno;
2098 if( EEXIST == tErrno ){
2099 rc = SQLITE_BUSY;
2100 } else {
2101 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002102 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002103 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002104 }
2105 }
drh7708e972008-11-29 00:56:52 +00002106 return rc;
drh734c9862008-11-28 15:37:20 +00002107 }
drh734c9862008-11-28 15:37:20 +00002108
2109 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002110 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002111 return rc;
2112}
2113
drh7708e972008-11-29 00:56:52 +00002114/*
drh308c2a52010-05-14 11:30:18 +00002115** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002116** must be either NO_LOCK or SHARED_LOCK.
2117**
2118** If the locking level of the file descriptor is already at or below
2119** the requested locking level, this routine is a no-op.
2120**
2121** When the locking level reaches NO_LOCK, delete the lock file.
2122*/
drh308c2a52010-05-14 11:30:18 +00002123static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002124 unixFile *pFile = (unixFile*)id;
2125 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002126 int rc;
drh734c9862008-11-28 15:37:20 +00002127
2128 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002129 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002130 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002131 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002132
2133 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002134 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002135 return SQLITE_OK;
2136 }
drh7708e972008-11-29 00:56:52 +00002137
2138 /* To downgrade to shared, simply update our internal notion of the
2139 ** lock state. No need to mess with the file on disk.
2140 */
drh308c2a52010-05-14 11:30:18 +00002141 if( eFileLock==SHARED_LOCK ){
2142 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002143 return SQLITE_OK;
2144 }
2145
drh7708e972008-11-29 00:56:52 +00002146 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002147 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002148 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002149 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002150 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002151 if( tErrno==ENOENT ){
2152 rc = SQLITE_OK;
2153 }else{
danea83bc62011-04-01 11:56:32 +00002154 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002155 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002156 }
2157 return rc;
2158 }
drh308c2a52010-05-14 11:30:18 +00002159 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002160 return SQLITE_OK;
2161}
2162
2163/*
drh9b35ea62008-11-29 02:20:26 +00002164** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002165*/
2166static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002167 unixFile *pFile = (unixFile*)id;
2168 assert( id!=0 );
2169 dotlockUnlock(id, NO_LOCK);
2170 sqlite3_free(pFile->lockingContext);
2171 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002172}
2173/****************** End of the dot-file lock implementation *******************
2174******************************************************************************/
2175
2176/******************************************************************************
2177************************** Begin flock Locking ********************************
2178**
2179** Use the flock() system call to do file locking.
2180**
drh6b9d6dd2008-12-03 19:34:47 +00002181** flock() locking is like dot-file locking in that the various
2182** fine-grain locking levels supported by SQLite are collapsed into
2183** a single exclusive lock. In other words, SHARED, RESERVED, and
2184** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2185** still works when you do this, but concurrency is reduced since
2186** only a single process can be reading the database at a time.
2187**
drhe89b2912015-03-03 20:42:01 +00002188** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002189*/
drhe89b2912015-03-03 20:42:01 +00002190#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002191
drh6b9d6dd2008-12-03 19:34:47 +00002192/*
drhff812312011-02-23 13:33:46 +00002193** Retry flock() calls that fail with EINTR
2194*/
2195#ifdef EINTR
2196static int robust_flock(int fd, int op){
2197 int rc;
2198 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2199 return rc;
2200}
2201#else
drh5c819272011-02-23 14:00:12 +00002202# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002203#endif
2204
2205
2206/*
drh6b9d6dd2008-12-03 19:34:47 +00002207** This routine checks if there is a RESERVED lock held on the specified
2208** file by this or any other process. If such a lock is held, set *pResOut
2209** to a non-zero value otherwise *pResOut is set to zero. The return value
2210** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2211*/
drh734c9862008-11-28 15:37:20 +00002212static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2213 int rc = SQLITE_OK;
2214 int reserved = 0;
2215 unixFile *pFile = (unixFile*)id;
2216
2217 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2218
2219 assert( pFile );
2220
2221 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002222 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002223 reserved = 1;
2224 }
2225
2226 /* Otherwise see if some other process holds it. */
2227 if( !reserved ){
2228 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002229 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002230 if( !lrc ){
2231 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002232 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002233 if ( lrc ) {
2234 int tErrno = errno;
2235 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002236 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002237 storeLastErrno(pFile, tErrno);
2238 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002239 }
2240 } else {
2241 int tErrno = errno;
2242 reserved = 1;
2243 /* someone else might have it reserved */
2244 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2245 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002246 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002247 rc = lrc;
2248 }
2249 }
2250 }
drh308c2a52010-05-14 11:30:18 +00002251 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002252
2253#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2254 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2255 rc = SQLITE_OK;
2256 reserved=1;
2257 }
2258#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2259 *pResOut = reserved;
2260 return rc;
2261}
2262
drh6b9d6dd2008-12-03 19:34:47 +00002263/*
drh308c2a52010-05-14 11:30:18 +00002264** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002265** of the following:
2266**
2267** (1) SHARED_LOCK
2268** (2) RESERVED_LOCK
2269** (3) PENDING_LOCK
2270** (4) EXCLUSIVE_LOCK
2271**
2272** Sometimes when requesting one lock state, additional lock states
2273** are inserted in between. The locking might fail on one of the later
2274** transitions leaving the lock state different from what it started but
2275** still short of its goal. The following chart shows the allowed
2276** transitions and the inserted intermediate states:
2277**
2278** UNLOCKED -> SHARED
2279** SHARED -> RESERVED
2280** SHARED -> (PENDING) -> EXCLUSIVE
2281** RESERVED -> (PENDING) -> EXCLUSIVE
2282** PENDING -> EXCLUSIVE
2283**
2284** flock() only really support EXCLUSIVE locks. We track intermediate
2285** lock states in the sqlite3_file structure, but all locks SHARED or
2286** above are really EXCLUSIVE locks and exclude all other processes from
2287** access the file.
2288**
2289** This routine will only increase a lock. Use the sqlite3OsUnlock()
2290** routine to lower a locking level.
2291*/
drh308c2a52010-05-14 11:30:18 +00002292static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002293 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002294 unixFile *pFile = (unixFile*)id;
2295
2296 assert( pFile );
2297
2298 /* if we already have a lock, it is exclusive.
2299 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002300 if (pFile->eFileLock > NO_LOCK) {
2301 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002302 return SQLITE_OK;
2303 }
2304
2305 /* grab an exclusive lock */
2306
drhff812312011-02-23 13:33:46 +00002307 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002308 int tErrno = errno;
2309 /* didn't get, must be busy */
2310 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2311 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002312 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002313 }
2314 } else {
2315 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002316 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002317 }
drh308c2a52010-05-14 11:30:18 +00002318 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2319 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002320#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2321 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2322 rc = SQLITE_BUSY;
2323 }
2324#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2325 return rc;
2326}
2327
drh6b9d6dd2008-12-03 19:34:47 +00002328
2329/*
drh308c2a52010-05-14 11:30:18 +00002330** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002331** must be either NO_LOCK or SHARED_LOCK.
2332**
2333** If the locking level of the file descriptor is already at or below
2334** the requested locking level, this routine is a no-op.
2335*/
drh308c2a52010-05-14 11:30:18 +00002336static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002337 unixFile *pFile = (unixFile*)id;
2338
2339 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002340 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002341 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002342 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002343
2344 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002345 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002346 return SQLITE_OK;
2347 }
2348
2349 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002350 if (eFileLock==SHARED_LOCK) {
2351 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002352 return SQLITE_OK;
2353 }
2354
2355 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002356 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002357#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002358 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002359#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002360 return SQLITE_IOERR_UNLOCK;
2361 }else{
drh308c2a52010-05-14 11:30:18 +00002362 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002363 return SQLITE_OK;
2364 }
2365}
2366
2367/*
2368** Close a file.
2369*/
2370static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002371 assert( id!=0 );
2372 flockUnlock(id, NO_LOCK);
2373 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002374}
2375
2376#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2377
2378/******************* End of the flock lock implementation *********************
2379******************************************************************************/
2380
2381/******************************************************************************
2382************************ Begin Named Semaphore Locking ************************
2383**
2384** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002385**
2386** Semaphore locking is like dot-lock and flock in that it really only
2387** supports EXCLUSIVE locking. Only a single process can read or write
2388** the database file at a time. This reduces potential concurrency, but
2389** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002390*/
2391#if OS_VXWORKS
2392
drh6b9d6dd2008-12-03 19:34:47 +00002393/*
2394** This routine checks if there is a RESERVED lock held on the specified
2395** file by this or any other process. If such a lock is held, set *pResOut
2396** to a non-zero value otherwise *pResOut is set to zero. The return value
2397** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2398*/
drh8cd5b252015-03-02 22:06:43 +00002399static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002400 int rc = SQLITE_OK;
2401 int reserved = 0;
2402 unixFile *pFile = (unixFile*)id;
2403
2404 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2405
2406 assert( pFile );
2407
2408 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002409 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002410 reserved = 1;
2411 }
2412
2413 /* Otherwise see if some other process holds it. */
2414 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002415 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002416
2417 if( sem_trywait(pSem)==-1 ){
2418 int tErrno = errno;
2419 if( EAGAIN != tErrno ){
2420 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002421 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002422 } else {
2423 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002424 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002425 }
2426 }else{
2427 /* we could have it if we want it */
2428 sem_post(pSem);
2429 }
2430 }
drh308c2a52010-05-14 11:30:18 +00002431 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002432
2433 *pResOut = reserved;
2434 return rc;
2435}
2436
drh6b9d6dd2008-12-03 19:34:47 +00002437/*
drh308c2a52010-05-14 11:30:18 +00002438** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002439** of the following:
2440**
2441** (1) SHARED_LOCK
2442** (2) RESERVED_LOCK
2443** (3) PENDING_LOCK
2444** (4) EXCLUSIVE_LOCK
2445**
2446** Sometimes when requesting one lock state, additional lock states
2447** are inserted in between. The locking might fail on one of the later
2448** transitions leaving the lock state different from what it started but
2449** still short of its goal. The following chart shows the allowed
2450** transitions and the inserted intermediate states:
2451**
2452** UNLOCKED -> SHARED
2453** SHARED -> RESERVED
2454** SHARED -> (PENDING) -> EXCLUSIVE
2455** RESERVED -> (PENDING) -> EXCLUSIVE
2456** PENDING -> EXCLUSIVE
2457**
2458** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2459** lock states in the sqlite3_file structure, but all locks SHARED or
2460** above are really EXCLUSIVE locks and exclude all other processes from
2461** access the file.
2462**
2463** This routine will only increase a lock. Use the sqlite3OsUnlock()
2464** routine to lower a locking level.
2465*/
drh8cd5b252015-03-02 22:06:43 +00002466static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002467 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002468 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002469 int rc = SQLITE_OK;
2470
2471 /* if we already have a lock, it is exclusive.
2472 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002473 if (pFile->eFileLock > NO_LOCK) {
2474 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002475 rc = SQLITE_OK;
2476 goto sem_end_lock;
2477 }
2478
2479 /* lock semaphore now but bail out when already locked. */
2480 if( sem_trywait(pSem)==-1 ){
2481 rc = SQLITE_BUSY;
2482 goto sem_end_lock;
2483 }
2484
2485 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002486 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002487
2488 sem_end_lock:
2489 return rc;
2490}
2491
drh6b9d6dd2008-12-03 19:34:47 +00002492/*
drh308c2a52010-05-14 11:30:18 +00002493** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002494** must be either NO_LOCK or SHARED_LOCK.
2495**
2496** If the locking level of the file descriptor is already at or below
2497** the requested locking level, this routine is a no-op.
2498*/
drh8cd5b252015-03-02 22:06:43 +00002499static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002500 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002501 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002502
2503 assert( pFile );
2504 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002505 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002506 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002507 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002508
2509 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002510 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002511 return SQLITE_OK;
2512 }
2513
2514 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002515 if (eFileLock==SHARED_LOCK) {
2516 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002517 return SQLITE_OK;
2518 }
2519
2520 /* no, really unlock. */
2521 if ( sem_post(pSem)==-1 ) {
2522 int rc, tErrno = errno;
2523 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2524 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002525 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002526 }
2527 return rc;
2528 }
drh308c2a52010-05-14 11:30:18 +00002529 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002530 return SQLITE_OK;
2531}
2532
2533/*
2534 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002535 */
drh8cd5b252015-03-02 22:06:43 +00002536static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002537 if( id ){
2538 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002539 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002540 assert( pFile );
2541 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002542 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002543 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002544 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002545 }
2546 return SQLITE_OK;
2547}
2548
2549#endif /* OS_VXWORKS */
2550/*
2551** Named semaphore locking is only available on VxWorks.
2552**
2553*************** End of the named semaphore lock implementation ****************
2554******************************************************************************/
2555
2556
2557/******************************************************************************
2558*************************** Begin AFP Locking *********************************
2559**
2560** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2561** on Apple Macintosh computers - both OS9 and OSX.
2562**
2563** Third-party implementations of AFP are available. But this code here
2564** only works on OSX.
2565*/
2566
drhd2cb50b2009-01-09 21:41:17 +00002567#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002568/*
2569** The afpLockingContext structure contains all afp lock specific state
2570*/
drhbfe66312006-10-03 17:40:40 +00002571typedef struct afpLockingContext afpLockingContext;
2572struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002573 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002574 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002575};
2576
2577struct ByteRangeLockPB2
2578{
2579 unsigned long long offset; /* offset to first byte to lock */
2580 unsigned long long length; /* nbr of bytes to lock */
2581 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2582 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2583 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2584 int fd; /* file desc to assoc this lock with */
2585};
2586
drhfd131da2007-08-07 17:13:03 +00002587#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002588
drh6b9d6dd2008-12-03 19:34:47 +00002589/*
2590** This is a utility for setting or clearing a bit-range lock on an
2591** AFP filesystem.
2592**
2593** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2594*/
2595static int afpSetLock(
2596 const char *path, /* Name of the file to be locked or unlocked */
2597 unixFile *pFile, /* Open file descriptor on path */
2598 unsigned long long offset, /* First byte to be locked */
2599 unsigned long long length, /* Number of bytes to lock */
2600 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002601){
drh6b9d6dd2008-12-03 19:34:47 +00002602 struct ByteRangeLockPB2 pb;
2603 int err;
drhbfe66312006-10-03 17:40:40 +00002604
2605 pb.unLockFlag = setLockFlag ? 0 : 1;
2606 pb.startEndFlag = 0;
2607 pb.offset = offset;
2608 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002609 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002610
drh308c2a52010-05-14 11:30:18 +00002611 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002612 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002613 offset, length));
drhbfe66312006-10-03 17:40:40 +00002614 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2615 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002616 int rc;
2617 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002618 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2619 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002620#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2621 rc = SQLITE_BUSY;
2622#else
drh734c9862008-11-28 15:37:20 +00002623 rc = sqliteErrorFromPosixError(tErrno,
2624 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002625#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002626 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002627 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002628 }
2629 return rc;
drhbfe66312006-10-03 17:40:40 +00002630 } else {
aswift5b1a2562008-08-22 00:22:35 +00002631 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002632 }
2633}
2634
drh6b9d6dd2008-12-03 19:34:47 +00002635/*
2636** This routine checks if there is a RESERVED lock held on the specified
2637** file by this or any other process. If such a lock is held, set *pResOut
2638** to a non-zero value otherwise *pResOut is set to zero. The return value
2639** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2640*/
danielk1977e339d652008-06-28 11:23:00 +00002641static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002642 int rc = SQLITE_OK;
2643 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002644 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002645 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002646
aswift5b1a2562008-08-22 00:22:35 +00002647 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2648
2649 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002650 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002651 if( context->reserved ){
2652 *pResOut = 1;
2653 return SQLITE_OK;
2654 }
drh8af6c222010-05-14 12:43:01 +00002655 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002656
2657 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002658 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002659 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002660 }
2661
2662 /* Otherwise see if some other process holds it.
2663 */
aswift5b1a2562008-08-22 00:22:35 +00002664 if( !reserved ){
2665 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002666 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002667 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002668 /* if we succeeded in taking the reserved lock, unlock it to restore
2669 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002670 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002671 } else {
2672 /* if we failed to get the lock then someone else must have it */
2673 reserved = 1;
2674 }
2675 if( IS_LOCK_ERROR(lrc) ){
2676 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002677 }
2678 }
drhbfe66312006-10-03 17:40:40 +00002679
drh7ed97b92010-01-20 13:07:21 +00002680 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002681 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002682
2683 *pResOut = reserved;
2684 return rc;
drhbfe66312006-10-03 17:40:40 +00002685}
2686
drh6b9d6dd2008-12-03 19:34:47 +00002687/*
drh308c2a52010-05-14 11:30:18 +00002688** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002689** of the following:
2690**
2691** (1) SHARED_LOCK
2692** (2) RESERVED_LOCK
2693** (3) PENDING_LOCK
2694** (4) EXCLUSIVE_LOCK
2695**
2696** Sometimes when requesting one lock state, additional lock states
2697** are inserted in between. The locking might fail on one of the later
2698** transitions leaving the lock state different from what it started but
2699** still short of its goal. The following chart shows the allowed
2700** transitions and the inserted intermediate states:
2701**
2702** UNLOCKED -> SHARED
2703** SHARED -> RESERVED
2704** SHARED -> (PENDING) -> EXCLUSIVE
2705** RESERVED -> (PENDING) -> EXCLUSIVE
2706** PENDING -> EXCLUSIVE
2707**
2708** This routine will only increase a lock. Use the sqlite3OsUnlock()
2709** routine to lower a locking level.
2710*/
drh308c2a52010-05-14 11:30:18 +00002711static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002712 int rc = SQLITE_OK;
2713 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002714 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002715 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002716
2717 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002718 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2719 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002720 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002721
drhbfe66312006-10-03 17:40:40 +00002722 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002723 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002724 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002725 */
drh308c2a52010-05-14 11:30:18 +00002726 if( pFile->eFileLock>=eFileLock ){
2727 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2728 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002729 return SQLITE_OK;
2730 }
2731
2732 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002733 ** (1) We never move from unlocked to anything higher than shared lock.
2734 ** (2) SQLite never explicitly requests a pendig lock.
2735 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002736 */
drh308c2a52010-05-14 11:30:18 +00002737 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2738 assert( eFileLock!=PENDING_LOCK );
2739 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002740
drh8af6c222010-05-14 12:43:01 +00002741 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002742 */
drh6c7d5c52008-11-21 20:32:33 +00002743 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002744 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002745
2746 /* If some thread using this PID has a lock via a different unixFile*
2747 ** handle that precludes the requested lock, return BUSY.
2748 */
drh8af6c222010-05-14 12:43:01 +00002749 if( (pFile->eFileLock!=pInode->eFileLock &&
2750 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002751 ){
2752 rc = SQLITE_BUSY;
2753 goto afp_end_lock;
2754 }
2755
2756 /* If a SHARED lock is requested, and some thread using this PID already
2757 ** has a SHARED or RESERVED lock, then increment reference counts and
2758 ** return SQLITE_OK.
2759 */
drh308c2a52010-05-14 11:30:18 +00002760 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002761 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002762 assert( eFileLock==SHARED_LOCK );
2763 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002764 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002765 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002766 pInode->nShared++;
2767 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002768 goto afp_end_lock;
2769 }
drhbfe66312006-10-03 17:40:40 +00002770
2771 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002772 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2773 ** be released.
2774 */
drh308c2a52010-05-14 11:30:18 +00002775 if( eFileLock==SHARED_LOCK
2776 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002777 ){
2778 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002779 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002780 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002781 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002782 goto afp_end_lock;
2783 }
2784 }
2785
2786 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002787 ** operating system calls for the specified lock.
2788 */
drh308c2a52010-05-14 11:30:18 +00002789 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002790 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002791 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002792
drh8af6c222010-05-14 12:43:01 +00002793 assert( pInode->nShared==0 );
2794 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002795
2796 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002797 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002798 /* note that the quality of the randomness doesn't matter that much */
2799 lk = random();
drh8af6c222010-05-14 12:43:01 +00002800 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002801 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002802 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002803 if( IS_LOCK_ERROR(lrc1) ){
2804 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002805 }
aswift5b1a2562008-08-22 00:22:35 +00002806 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002807 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002808
aswift5b1a2562008-08-22 00:22:35 +00002809 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002810 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002811 rc = lrc1;
2812 goto afp_end_lock;
2813 } else if( IS_LOCK_ERROR(lrc2) ){
2814 rc = lrc2;
2815 goto afp_end_lock;
2816 } else if( lrc1 != SQLITE_OK ) {
2817 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002818 } else {
drh308c2a52010-05-14 11:30:18 +00002819 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002820 pInode->nLock++;
2821 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002822 }
drh8af6c222010-05-14 12:43:01 +00002823 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002824 /* We are trying for an exclusive lock but another thread in this
2825 ** same process is still holding a shared lock. */
2826 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002827 }else{
2828 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2829 ** assumed that there is a SHARED or greater lock on the file
2830 ** already.
2831 */
2832 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002833 assert( 0!=pFile->eFileLock );
2834 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002835 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002836 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002837 if( !failed ){
2838 context->reserved = 1;
2839 }
drhbfe66312006-10-03 17:40:40 +00002840 }
drh308c2a52010-05-14 11:30:18 +00002841 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002842 /* Acquire an EXCLUSIVE lock */
2843
2844 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002845 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002846 */
drh6b9d6dd2008-12-03 19:34:47 +00002847 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002848 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002849 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002850 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002851 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002852 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002853 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002854 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002855 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2856 ** a critical I/O error
2857 */
2858 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2859 SQLITE_IOERR_LOCK;
2860 goto afp_end_lock;
2861 }
2862 }else{
aswift5b1a2562008-08-22 00:22:35 +00002863 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002864 }
2865 }
aswift5b1a2562008-08-22 00:22:35 +00002866 if( failed ){
2867 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002868 }
2869 }
2870
2871 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002872 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002873 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002874 }else if( eFileLock==EXCLUSIVE_LOCK ){
2875 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002876 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002877 }
2878
2879afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002880 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002881 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2882 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002883 return rc;
2884}
2885
2886/*
drh308c2a52010-05-14 11:30:18 +00002887** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002888** must be either NO_LOCK or SHARED_LOCK.
2889**
2890** If the locking level of the file descriptor is already at or below
2891** the requested locking level, this routine is a no-op.
2892*/
drh308c2a52010-05-14 11:30:18 +00002893static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002894 int rc = SQLITE_OK;
2895 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002896 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002897 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2898 int skipShared = 0;
2899#ifdef SQLITE_TEST
2900 int h = pFile->h;
2901#endif
drhbfe66312006-10-03 17:40:40 +00002902
2903 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002904 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002905 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002906 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002907
drh308c2a52010-05-14 11:30:18 +00002908 assert( eFileLock<=SHARED_LOCK );
2909 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002910 return SQLITE_OK;
2911 }
drh6c7d5c52008-11-21 20:32:33 +00002912 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002913 pInode = pFile->pInode;
2914 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002915 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002916 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002917 SimulateIOErrorBenign(1);
2918 SimulateIOError( h=(-1) )
2919 SimulateIOErrorBenign(0);
2920
drhd3d8c042012-05-29 17:02:40 +00002921#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002922 /* When reducing a lock such that other processes can start
2923 ** reading the database file again, make sure that the
2924 ** transaction counter was updated if any part of the database
2925 ** file changed. If the transaction counter is not updated,
2926 ** other connections to the same file might not realize that
2927 ** the file has changed and hence might not know to flush their
2928 ** cache. The use of a stale cache can lead to database corruption.
2929 */
2930 assert( pFile->inNormalWrite==0
2931 || pFile->dbUpdate==0
2932 || pFile->transCntrChng==1 );
2933 pFile->inNormalWrite = 0;
2934#endif
aswiftaebf4132008-11-21 00:10:35 +00002935
drh308c2a52010-05-14 11:30:18 +00002936 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002937 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002938 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002939 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002940 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002941 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2942 } else {
2943 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002944 }
2945 }
drh308c2a52010-05-14 11:30:18 +00002946 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002947 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002948 }
drh308c2a52010-05-14 11:30:18 +00002949 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002950 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2951 if( !rc ){
2952 context->reserved = 0;
2953 }
aswiftaebf4132008-11-21 00:10:35 +00002954 }
drh8af6c222010-05-14 12:43:01 +00002955 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2956 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002957 }
aswiftaebf4132008-11-21 00:10:35 +00002958 }
drh308c2a52010-05-14 11:30:18 +00002959 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002960
drh7ed97b92010-01-20 13:07:21 +00002961 /* Decrement the shared lock counter. Release the lock using an
2962 ** OS call only when all threads in this same process have released
2963 ** the lock.
2964 */
drh8af6c222010-05-14 12:43:01 +00002965 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2966 pInode->nShared--;
2967 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002968 SimulateIOErrorBenign(1);
2969 SimulateIOError( h=(-1) )
2970 SimulateIOErrorBenign(0);
2971 if( !skipShared ){
2972 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2973 }
2974 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002975 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002976 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002977 }
2978 }
2979 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002980 pInode->nLock--;
2981 assert( pInode->nLock>=0 );
2982 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002983 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002984 }
2985 }
drhbfe66312006-10-03 17:40:40 +00002986 }
drh7ed97b92010-01-20 13:07:21 +00002987
drh6c7d5c52008-11-21 20:32:33 +00002988 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002989 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002990 return rc;
2991}
2992
2993/*
drh339eb0b2008-03-07 15:34:11 +00002994** Close a file & cleanup AFP specific locking context
2995*/
danielk1977e339d652008-06-28 11:23:00 +00002996static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002997 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00002998 unixFile *pFile = (unixFile*)id;
2999 assert( id!=0 );
3000 afpUnlock(id, NO_LOCK);
3001 unixEnterMutex();
3002 if( pFile->pInode && pFile->pInode->nLock ){
3003 /* If there are outstanding locks, do not actually close the file just
3004 ** yet because that would clear those locks. Instead, add the file
3005 ** descriptor to pInode->aPending. It will be automatically closed when
3006 ** the last lock is cleared.
3007 */
3008 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003009 }
drha8de1e12015-11-30 00:05:39 +00003010 releaseInodeInfo(pFile);
3011 sqlite3_free(pFile->lockingContext);
3012 rc = closeUnixFile(id);
3013 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003014 return rc;
drhbfe66312006-10-03 17:40:40 +00003015}
3016
drhd2cb50b2009-01-09 21:41:17 +00003017#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003018/*
3019** The code above is the AFP lock implementation. The code is specific
3020** to MacOSX and does not work on other unix platforms. No alternative
3021** is available. If you don't compile for a mac, then the "unix-afp"
3022** VFS is not available.
3023**
3024********************* End of the AFP lock implementation **********************
3025******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003026
drh7ed97b92010-01-20 13:07:21 +00003027/******************************************************************************
3028*************************** Begin NFS Locking ********************************/
3029
3030#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3031/*
drh308c2a52010-05-14 11:30:18 +00003032 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003033 ** must be either NO_LOCK or SHARED_LOCK.
3034 **
3035 ** If the locking level of the file descriptor is already at or below
3036 ** the requested locking level, this routine is a no-op.
3037 */
drh308c2a52010-05-14 11:30:18 +00003038static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003039 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003040}
3041
3042#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3043/*
3044** The code above is the NFS lock implementation. The code is specific
3045** to MacOSX and does not work on other unix platforms. No alternative
3046** is available.
3047**
3048********************* End of the NFS lock implementation **********************
3049******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003050
3051/******************************************************************************
3052**************** Non-locking sqlite3_file methods *****************************
3053**
3054** The next division contains implementations for all methods of the
3055** sqlite3_file object other than the locking methods. The locking
3056** methods were defined in divisions above (one locking method per
3057** division). Those methods that are common to all locking modes
3058** are gather together into this division.
3059*/
drhbfe66312006-10-03 17:40:40 +00003060
3061/*
drh734c9862008-11-28 15:37:20 +00003062** Seek to the offset passed as the second argument, then read cnt
3063** bytes into pBuf. Return the number of bytes actually read.
3064**
3065** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3066** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3067** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003068** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003069** See tickets #2741 and #2681.
3070**
3071** To avoid stomping the errno value on a failed read the lastErrno value
3072** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003073*/
drh734c9862008-11-28 15:37:20 +00003074static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3075 int got;
drh58024642011-11-07 18:16:00 +00003076 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003077#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003078 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003079#endif
drh734c9862008-11-28 15:37:20 +00003080 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003081 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003082 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003083 do{
drh734c9862008-11-28 15:37:20 +00003084#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003085 got = osPread(id->h, pBuf, cnt, offset);
3086 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003087#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003088 got = osPread64(id->h, pBuf, cnt, offset);
3089 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003090#else
drh58024642011-11-07 18:16:00 +00003091 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003092 SimulateIOError( newOffset = -1 );
3093 if( newOffset<0 ){
3094 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003095 return -1;
drh734c9862008-11-28 15:37:20 +00003096 }
drh58024642011-11-07 18:16:00 +00003097 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003098#endif
drh58024642011-11-07 18:16:00 +00003099 if( got==cnt ) break;
3100 if( got<0 ){
3101 if( errno==EINTR ){ got = 1; continue; }
3102 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003103 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003104 break;
3105 }else if( got>0 ){
3106 cnt -= got;
3107 offset += got;
3108 prior += got;
3109 pBuf = (void*)(got + (char*)pBuf);
3110 }
3111 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003112 TIMER_END;
drh58024642011-11-07 18:16:00 +00003113 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3114 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3115 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003116}
3117
3118/*
drh734c9862008-11-28 15:37:20 +00003119** Read data from a file into a buffer. Return SQLITE_OK if all
3120** bytes were read successfully and SQLITE_IOERR if anything goes
3121** wrong.
drh339eb0b2008-03-07 15:34:11 +00003122*/
drh734c9862008-11-28 15:37:20 +00003123static int unixRead(
3124 sqlite3_file *id,
3125 void *pBuf,
3126 int amt,
3127 sqlite3_int64 offset
3128){
dan08da86a2009-08-21 17:18:03 +00003129 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003130 int got;
3131 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003132 assert( offset>=0 );
3133 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003134
dan08da86a2009-08-21 17:18:03 +00003135 /* If this is a database file (not a journal, master-journal or temp
3136 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003137#if 0
dane946c392009-08-22 11:39:46 +00003138 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003139 || offset>=PENDING_BYTE+512
3140 || offset+amt<=PENDING_BYTE
3141 );
dan7c246102010-04-12 19:00:29 +00003142#endif
drh08c6d442009-02-09 17:34:07 +00003143
drh9b4c59f2013-04-15 17:03:42 +00003144#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003145 /* Deal with as much of this read request as possible by transfering
3146 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003147 if( offset<pFile->mmapSize ){
3148 if( offset+amt <= pFile->mmapSize ){
3149 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3150 return SQLITE_OK;
3151 }else{
3152 int nCopy = pFile->mmapSize - offset;
3153 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3154 pBuf = &((u8 *)pBuf)[nCopy];
3155 amt -= nCopy;
3156 offset += nCopy;
3157 }
3158 }
drh6e0b6d52013-04-09 16:19:20 +00003159#endif
danf23da962013-03-23 21:00:41 +00003160
dan08da86a2009-08-21 17:18:03 +00003161 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003162 if( got==amt ){
3163 return SQLITE_OK;
3164 }else if( got<0 ){
3165 /* lastErrno set by seekAndRead */
3166 return SQLITE_IOERR_READ;
3167 }else{
drh4bf66fd2015-02-19 02:43:02 +00003168 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003169 /* Unread parts of the buffer must be zero-filled */
3170 memset(&((char*)pBuf)[got], 0, amt-got);
3171 return SQLITE_IOERR_SHORT_READ;
3172 }
3173}
3174
3175/*
dan47a2b4a2013-04-26 16:09:29 +00003176** Attempt to seek the file-descriptor passed as the first argument to
3177** absolute offset iOff, then attempt to write nBuf bytes of data from
3178** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3179** return the actual number of bytes written (which may be less than
3180** nBuf).
3181*/
3182static int seekAndWriteFd(
3183 int fd, /* File descriptor to write to */
3184 i64 iOff, /* File offset to begin writing at */
3185 const void *pBuf, /* Copy data from this buffer to the file */
3186 int nBuf, /* Size of buffer pBuf in bytes */
3187 int *piErrno /* OUT: Error number if error occurs */
3188){
3189 int rc = 0; /* Value returned by system call */
3190
3191 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003192 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003193 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003194 nBuf &= 0x1ffff;
3195 TIMER_START;
3196
3197#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003198 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003199#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003200 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003201#else
3202 do{
3203 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003204 SimulateIOError( iSeek = -1 );
3205 if( iSeek<0 ){
3206 rc = -1;
3207 break;
dan47a2b4a2013-04-26 16:09:29 +00003208 }
3209 rc = osWrite(fd, pBuf, nBuf);
3210 }while( rc<0 && errno==EINTR );
3211#endif
3212
3213 TIMER_END;
3214 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3215
drhe1818ec2015-12-01 16:21:35 +00003216 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003217 return rc;
3218}
3219
3220
3221/*
drh734c9862008-11-28 15:37:20 +00003222** Seek to the offset in id->offset then read cnt bytes into pBuf.
3223** Return the number of bytes actually read. Update the offset.
3224**
3225** To avoid stomping the errno value on a failed write the lastErrno value
3226** is set before returning.
3227*/
3228static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003229 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003230}
3231
3232
3233/*
3234** Write data from a buffer into a file. Return SQLITE_OK on success
3235** or some other error code on failure.
3236*/
3237static int unixWrite(
3238 sqlite3_file *id,
3239 const void *pBuf,
3240 int amt,
3241 sqlite3_int64 offset
3242){
dan08da86a2009-08-21 17:18:03 +00003243 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003244 int wrote = 0;
3245 assert( id );
3246 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003247
dan08da86a2009-08-21 17:18:03 +00003248 /* If this is a database file (not a journal, master-journal or temp
3249 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003250#if 0
dane946c392009-08-22 11:39:46 +00003251 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003252 || offset>=PENDING_BYTE+512
3253 || offset+amt<=PENDING_BYTE
3254 );
dan7c246102010-04-12 19:00:29 +00003255#endif
drh08c6d442009-02-09 17:34:07 +00003256
drhd3d8c042012-05-29 17:02:40 +00003257#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003258 /* If we are doing a normal write to a database file (as opposed to
3259 ** doing a hot-journal rollback or a write to some file other than a
3260 ** normal database file) then record the fact that the database
3261 ** has changed. If the transaction counter is modified, record that
3262 ** fact too.
3263 */
dan08da86a2009-08-21 17:18:03 +00003264 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003265 pFile->dbUpdate = 1; /* The database has been modified */
3266 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003267 int rc;
drh8f941bc2009-01-14 23:03:40 +00003268 char oldCntr[4];
3269 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003270 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003271 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003272 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003273 pFile->transCntrChng = 1; /* The transaction counter has changed */
3274 }
3275 }
3276 }
3277#endif
3278
danfe33e392015-11-17 20:56:06 +00003279#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003280 /* Deal with as much of this write request as possible by transfering
3281 ** data from the memory mapping using memcpy(). */
3282 if( offset<pFile->mmapSize ){
3283 if( offset+amt <= pFile->mmapSize ){
3284 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3285 return SQLITE_OK;
3286 }else{
3287 int nCopy = pFile->mmapSize - offset;
3288 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3289 pBuf = &((u8 *)pBuf)[nCopy];
3290 amt -= nCopy;
3291 offset += nCopy;
3292 }
3293 }
drh6e0b6d52013-04-09 16:19:20 +00003294#endif
drh02bf8b42015-09-01 23:51:53 +00003295
3296 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003297 amt -= wrote;
3298 offset += wrote;
3299 pBuf = &((char*)pBuf)[wrote];
3300 }
3301 SimulateIOError(( wrote=(-1), amt=1 ));
3302 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003303
drh02bf8b42015-09-01 23:51:53 +00003304 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003305 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003306 /* lastErrno set by seekAndWrite */
3307 return SQLITE_IOERR_WRITE;
3308 }else{
drh4bf66fd2015-02-19 02:43:02 +00003309 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003310 return SQLITE_FULL;
3311 }
3312 }
dan6e09d692010-07-27 18:34:15 +00003313
drh734c9862008-11-28 15:37:20 +00003314 return SQLITE_OK;
3315}
3316
3317#ifdef SQLITE_TEST
3318/*
3319** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003320** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003321*/
3322int sqlite3_sync_count = 0;
3323int sqlite3_fullsync_count = 0;
3324#endif
3325
3326/*
drh89240432009-03-25 01:06:01 +00003327** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003328** Others do no. To be safe, we will stick with the (slightly slower)
3329** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003330** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003331*/
drhf7a4a1b2015-01-10 18:02:45 +00003332#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003333# define fdatasync fsync
3334#endif
3335
3336/*
3337** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3338** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3339** only available on Mac OS X. But that could change.
3340*/
3341#ifdef F_FULLFSYNC
3342# define HAVE_FULLFSYNC 1
3343#else
3344# define HAVE_FULLFSYNC 0
3345#endif
3346
3347
3348/*
3349** The fsync() system call does not work as advertised on many
3350** unix systems. The following procedure is an attempt to make
3351** it work better.
3352**
3353** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3354** for testing when we want to run through the test suite quickly.
3355** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3356** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3357** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003358**
3359** SQLite sets the dataOnly flag if the size of the file is unchanged.
3360** The idea behind dataOnly is that it should only write the file content
3361** to disk, not the inode. We only set dataOnly if the file size is
3362** unchanged since the file size is part of the inode. However,
3363** Ted Ts'o tells us that fdatasync() will also write the inode if the
3364** file size has changed. The only real difference between fdatasync()
3365** and fsync(), Ted tells us, is that fdatasync() will not flush the
3366** inode if the mtime or owner or other inode attributes have changed.
3367** We only care about the file size, not the other file attributes, so
3368** as far as SQLite is concerned, an fdatasync() is always adequate.
3369** So, we always use fdatasync() if it is available, regardless of
3370** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003371*/
3372static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003373 int rc;
drh734c9862008-11-28 15:37:20 +00003374
3375 /* The following "ifdef/elif/else/" block has the same structure as
3376 ** the one below. It is replicated here solely to avoid cluttering
3377 ** up the real code with the UNUSED_PARAMETER() macros.
3378 */
3379#ifdef SQLITE_NO_SYNC
3380 UNUSED_PARAMETER(fd);
3381 UNUSED_PARAMETER(fullSync);
3382 UNUSED_PARAMETER(dataOnly);
3383#elif HAVE_FULLFSYNC
3384 UNUSED_PARAMETER(dataOnly);
3385#else
3386 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003387 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003388#endif
3389
3390 /* Record the number of times that we do a normal fsync() and
3391 ** FULLSYNC. This is used during testing to verify that this procedure
3392 ** gets called with the correct arguments.
3393 */
3394#ifdef SQLITE_TEST
3395 if( fullSync ) sqlite3_fullsync_count++;
3396 sqlite3_sync_count++;
3397#endif
3398
3399 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003400 ** no-op. But go ahead and call fstat() to validate the file
3401 ** descriptor as we need a method to provoke a failure during
3402 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003403 */
3404#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003405 {
3406 struct stat buf;
3407 rc = osFstat(fd, &buf);
3408 }
drh734c9862008-11-28 15:37:20 +00003409#elif HAVE_FULLFSYNC
3410 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003411 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003412 }else{
3413 rc = 1;
3414 }
3415 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003416 ** It shouldn't be possible for fullfsync to fail on the local
3417 ** file system (on OSX), so failure indicates that FULLFSYNC
3418 ** isn't supported for this file system. So, attempt an fsync
3419 ** and (for now) ignore the overhead of a superfluous fcntl call.
3420 ** It'd be better to detect fullfsync support once and avoid
3421 ** the fcntl call every time sync is called.
3422 */
drh734c9862008-11-28 15:37:20 +00003423 if( rc ) rc = fsync(fd);
3424
drh7ed97b92010-01-20 13:07:21 +00003425#elif defined(__APPLE__)
3426 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3427 ** so currently we default to the macro that redefines fdatasync to fsync
3428 */
3429 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003430#else
drh0b647ff2009-03-21 14:41:04 +00003431 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003432#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003433 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003434 rc = fsync(fd);
3435 }
drh0b647ff2009-03-21 14:41:04 +00003436#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003437#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3438
3439 if( OS_VXWORKS && rc!= -1 ){
3440 rc = 0;
3441 }
chw97185482008-11-17 08:05:31 +00003442 return rc;
drhbfe66312006-10-03 17:40:40 +00003443}
3444
drh734c9862008-11-28 15:37:20 +00003445/*
drh0059eae2011-08-08 23:48:40 +00003446** Open a file descriptor to the directory containing file zFilename.
3447** If successful, *pFd is set to the opened file descriptor and
3448** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3449** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3450** value.
3451**
drh90315a22011-08-10 01:52:12 +00003452** The directory file descriptor is used for only one thing - to
3453** fsync() a directory to make sure file creation and deletion events
3454** are flushed to disk. Such fsyncs are not needed on newer
3455** journaling filesystems, but are required on older filesystems.
3456**
3457** This routine can be overridden using the xSetSysCall interface.
3458** The ability to override this routine was added in support of the
3459** chromium sandbox. Opening a directory is a security risk (we are
3460** told) so making it overrideable allows the chromium sandbox to
3461** replace this routine with a harmless no-op. To make this routine
3462** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3463** *pFd set to a negative number.
3464**
drh0059eae2011-08-08 23:48:40 +00003465** If SQLITE_OK is returned, the caller is responsible for closing
3466** the file descriptor *pFd using close().
3467*/
3468static int openDirectory(const char *zFilename, int *pFd){
3469 int ii;
3470 int fd = -1;
3471 char zDirname[MAX_PATHNAME+1];
3472
3473 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003474 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3475 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003476 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003477 }else{
3478 if( zDirname[0]!='/' ) zDirname[0] = '.';
3479 zDirname[1] = 0;
3480 }
3481 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3482 if( fd>=0 ){
3483 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003484 }
3485 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003486 if( fd>=0 ) return SQLITE_OK;
3487 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003488}
3489
3490/*
drh734c9862008-11-28 15:37:20 +00003491** Make sure all writes to a particular file are committed to disk.
3492**
3493** If dataOnly==0 then both the file itself and its metadata (file
3494** size, access time, etc) are synced. If dataOnly!=0 then only the
3495** file data is synced.
3496**
3497** Under Unix, also make sure that the directory entry for the file
3498** has been created by fsync-ing the directory that contains the file.
3499** If we do not do this and we encounter a power failure, the directory
3500** entry for the journal might not exist after we reboot. The next
3501** SQLite to access the file will not know that the journal exists (because
3502** the directory entry for the journal was never created) and the transaction
3503** will not roll back - possibly leading to database corruption.
3504*/
3505static int unixSync(sqlite3_file *id, int flags){
3506 int rc;
3507 unixFile *pFile = (unixFile*)id;
3508
3509 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3510 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3511
3512 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3513 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3514 || (flags&0x0F)==SQLITE_SYNC_FULL
3515 );
3516
3517 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3518 ** line is to test that doing so does not cause any problems.
3519 */
3520 SimulateDiskfullError( return SQLITE_FULL );
3521
3522 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003523 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003524 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3525 SimulateIOError( rc=1 );
3526 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003527 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003528 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003529 }
drh0059eae2011-08-08 23:48:40 +00003530
3531 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003532 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003533 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003534 */
3535 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3536 int dirfd;
3537 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003538 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003539 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003540 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003541 full_fsync(dirfd, 0, 0);
3542 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003543 }else{
3544 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003545 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003546 }
drh0059eae2011-08-08 23:48:40 +00003547 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003548 }
3549 return rc;
3550}
3551
3552/*
3553** Truncate an open file to a specified size
3554*/
3555static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003556 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003557 int rc;
dan6e09d692010-07-27 18:34:15 +00003558 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003559 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003560
3561 /* If the user has configured a chunk-size for this file, truncate the
3562 ** file so that it consists of an integer number of chunks (i.e. the
3563 ** actual file size after the operation may be larger than the requested
3564 ** size).
3565 */
drhb8af4b72012-04-05 20:04:39 +00003566 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003567 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3568 }
3569
dan2ee53412014-09-06 16:49:40 +00003570 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003571 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003572 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003573 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003574 }else{
drhd3d8c042012-05-29 17:02:40 +00003575#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003576 /* If we are doing a normal write to a database file (as opposed to
3577 ** doing a hot-journal rollback or a write to some file other than a
3578 ** normal database file) and we truncate the file to zero length,
3579 ** that effectively updates the change counter. This might happen
3580 ** when restoring a database using the backup API from a zero-length
3581 ** source.
3582 */
dan6e09d692010-07-27 18:34:15 +00003583 if( pFile->inNormalWrite && nByte==0 ){
3584 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003585 }
danf23da962013-03-23 21:00:41 +00003586#endif
danc0003312013-03-22 17:46:11 +00003587
mistachkine98844f2013-08-24 00:59:24 +00003588#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003589 /* If the file was just truncated to a size smaller than the currently
3590 ** mapped region, reduce the effective mapping size as well. SQLite will
3591 ** use read() and write() to access data beyond this point from now on.
3592 */
3593 if( nByte<pFile->mmapSize ){
3594 pFile->mmapSize = nByte;
3595 }
mistachkine98844f2013-08-24 00:59:24 +00003596#endif
drh3313b142009-11-06 04:13:18 +00003597
drh734c9862008-11-28 15:37:20 +00003598 return SQLITE_OK;
3599 }
3600}
3601
3602/*
3603** Determine the current size of a file in bytes
3604*/
3605static int unixFileSize(sqlite3_file *id, i64 *pSize){
3606 int rc;
3607 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003608 assert( id );
3609 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003610 SimulateIOError( rc=1 );
3611 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003612 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003613 return SQLITE_IOERR_FSTAT;
3614 }
3615 *pSize = buf.st_size;
3616
drh8af6c222010-05-14 12:43:01 +00003617 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003618 ** writes a single byte into that file in order to work around a bug
3619 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3620 ** layers, we need to report this file size as zero even though it is
3621 ** really 1. Ticket #3260.
3622 */
3623 if( *pSize==1 ) *pSize = 0;
3624
3625
3626 return SQLITE_OK;
3627}
3628
drhd2cb50b2009-01-09 21:41:17 +00003629#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003630/*
3631** Handler for proxy-locking file-control verbs. Defined below in the
3632** proxying locking division.
3633*/
3634static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003635#endif
drh715ff302008-12-03 22:32:44 +00003636
dan502019c2010-07-28 14:26:17 +00003637/*
3638** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003639** file-control operation. Enlarge the database to nBytes in size
3640** (rounded up to the next chunk-size). If the database is already
3641** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003642*/
3643static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003644 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003645 i64 nSize; /* Required file size */
3646 struct stat buf; /* Used to hold return values of fstat() */
3647
drh4bf66fd2015-02-19 02:43:02 +00003648 if( osFstat(pFile->h, &buf) ){
3649 return SQLITE_IOERR_FSTAT;
3650 }
dan502019c2010-07-28 14:26:17 +00003651
3652 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3653 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003654
dan502019c2010-07-28 14:26:17 +00003655#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003656 /* The code below is handling the return value of osFallocate()
3657 ** correctly. posix_fallocate() is defined to "returns zero on success,
3658 ** or an error number on failure". See the manpage for details. */
3659 int err;
drhff812312011-02-23 13:33:46 +00003660 do{
dan661d71a2011-03-30 19:08:03 +00003661 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3662 }while( err==EINTR );
3663 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003664#else
dan592bf7f2014-12-30 19:58:31 +00003665 /* If the OS does not have posix_fallocate(), fake it. Write a
3666 ** single byte to the last byte in each block that falls entirely
3667 ** within the extended region. Then, if required, a single byte
3668 ** at offset (nSize-1), to set the size of the file correctly.
3669 ** This is a similar technique to that used by glibc on systems
3670 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003671 */
3672 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003673 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003674 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003675
drh053378d2015-12-01 22:09:42 +00003676 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003677 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003678 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003679 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3680 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003681 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003682 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003683 }
dan502019c2010-07-28 14:26:17 +00003684#endif
3685 }
3686 }
3687
mistachkine98844f2013-08-24 00:59:24 +00003688#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003689 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003690 int rc;
3691 if( pFile->szChunk<=0 ){
3692 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003693 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003694 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3695 }
3696 }
3697
3698 rc = unixMapfile(pFile, nByte);
3699 return rc;
3700 }
mistachkine98844f2013-08-24 00:59:24 +00003701#endif
danf23da962013-03-23 21:00:41 +00003702
dan502019c2010-07-28 14:26:17 +00003703 return SQLITE_OK;
3704}
danielk1977ad94b582007-08-20 06:44:22 +00003705
danielk1977e3026632004-06-22 11:29:02 +00003706/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003707** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003708** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3709**
3710** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3711*/
3712static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3713 if( *pArg<0 ){
3714 *pArg = (pFile->ctrlFlags & mask)!=0;
3715 }else if( (*pArg)==0 ){
3716 pFile->ctrlFlags &= ~mask;
3717 }else{
3718 pFile->ctrlFlags |= mask;
3719 }
3720}
3721
drh696b33e2012-12-06 19:01:42 +00003722/* Forward declaration */
3723static int unixGetTempname(int nBuf, char *zBuf);
3724
drhf12b3f62011-12-21 14:42:29 +00003725/*
drh9e33c2c2007-08-31 18:34:59 +00003726** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003727*/
drhcc6bb3e2007-08-31 16:11:35 +00003728static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003729 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003730 switch( op ){
3731 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003732 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003733 return SQLITE_OK;
3734 }
drh4bf66fd2015-02-19 02:43:02 +00003735 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003736 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003737 return SQLITE_OK;
3738 }
dan6e09d692010-07-27 18:34:15 +00003739 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003740 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003741 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003742 }
drh9ff27ec2010-05-19 19:26:05 +00003743 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003744 int rc;
3745 SimulateIOErrorBenign(1);
3746 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3747 SimulateIOErrorBenign(0);
3748 return rc;
drhf0b190d2011-07-26 16:03:07 +00003749 }
3750 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003751 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3752 return SQLITE_OK;
3753 }
drhcb15f352011-12-23 01:04:17 +00003754 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3755 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003756 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003757 }
drhde60fc22011-12-14 17:53:36 +00003758 case SQLITE_FCNTL_VFSNAME: {
3759 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3760 return SQLITE_OK;
3761 }
drh696b33e2012-12-06 19:01:42 +00003762 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003763 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003764 if( zTFile ){
3765 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3766 *(char**)pArg = zTFile;
3767 }
3768 return SQLITE_OK;
3769 }
drhb959a012013-12-07 12:29:22 +00003770 case SQLITE_FCNTL_HAS_MOVED: {
3771 *(int*)pArg = fileHasMoved(pFile);
3772 return SQLITE_OK;
3773 }
mistachkine98844f2013-08-24 00:59:24 +00003774#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003775 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003776 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003777 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003778 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3779 newLimit = sqlite3GlobalConfig.mxMmap;
3780 }
3781 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003782 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003783 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003784 if( pFile->mmapSize>0 ){
3785 unixUnmapfile(pFile);
3786 rc = unixMapfile(pFile, -1);
3787 }
danbcb8a862013-04-08 15:30:41 +00003788 }
drh34e258c2013-05-23 01:40:53 +00003789 return rc;
danb2d3de32013-03-14 18:34:37 +00003790 }
mistachkine98844f2013-08-24 00:59:24 +00003791#endif
drhd3d8c042012-05-29 17:02:40 +00003792#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003793 /* The pager calls this method to signal that it has done
3794 ** a rollback and that the database is therefore unchanged and
3795 ** it hence it is OK for the transaction change counter to be
3796 ** unchanged.
3797 */
3798 case SQLITE_FCNTL_DB_UNCHANGED: {
3799 ((unixFile*)id)->dbUpdate = 0;
3800 return SQLITE_OK;
3801 }
3802#endif
drhd2cb50b2009-01-09 21:41:17 +00003803#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003804 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3805 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003806 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003807 }
drhd2cb50b2009-01-09 21:41:17 +00003808#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003809 }
drh0b52b7d2011-01-26 19:46:22 +00003810 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003811}
3812
3813/*
danielk1977a3d4c882007-03-23 10:08:38 +00003814** Return the sector size in bytes of the underlying block device for
3815** the specified file. This is almost always 512 bytes, but may be
3816** larger for some devices.
3817**
3818** SQLite code assumes this function cannot fail. It also assumes that
3819** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003820** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003821** same for both.
3822*/
drh537dddf2012-10-26 13:46:24 +00003823#ifndef __QNXNTO__
3824static int unixSectorSize(sqlite3_file *NotUsed){
3825 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003826 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003827}
drh537dddf2012-10-26 13:46:24 +00003828#endif
3829
3830/*
3831** The following version of unixSectorSize() is optimized for QNX.
3832*/
3833#ifdef __QNXNTO__
3834#include <sys/dcmd_blk.h>
3835#include <sys/statvfs.h>
3836static int unixSectorSize(sqlite3_file *id){
3837 unixFile *pFile = (unixFile*)id;
3838 if( pFile->sectorSize == 0 ){
3839 struct statvfs fsInfo;
3840
3841 /* Set defaults for non-supported filesystems */
3842 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3843 pFile->deviceCharacteristics = 0;
3844 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3845 return pFile->sectorSize;
3846 }
3847
3848 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3849 pFile->sectorSize = fsInfo.f_bsize;
3850 pFile->deviceCharacteristics =
3851 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3852 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3853 ** the write succeeds */
3854 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3855 ** so it is ordered */
3856 0;
3857 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3858 pFile->sectorSize = fsInfo.f_bsize;
3859 pFile->deviceCharacteristics =
3860 /* etfs cluster size writes are atomic */
3861 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3862 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3863 ** the write succeeds */
3864 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3865 ** so it is ordered */
3866 0;
3867 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3868 pFile->sectorSize = fsInfo.f_bsize;
3869 pFile->deviceCharacteristics =
3870 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3871 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3872 ** the write succeeds */
3873 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3874 ** so it is ordered */
3875 0;
3876 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3877 pFile->sectorSize = fsInfo.f_bsize;
3878 pFile->deviceCharacteristics =
3879 /* full bitset of atomics from max sector size and smaller */
3880 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3881 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3882 ** so it is ordered */
3883 0;
3884 }else if( strstr(fsInfo.f_basetype, "dos") ){
3885 pFile->sectorSize = fsInfo.f_bsize;
3886 pFile->deviceCharacteristics =
3887 /* full bitset of atomics from max sector size and smaller */
3888 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3889 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3890 ** so it is ordered */
3891 0;
3892 }else{
3893 pFile->deviceCharacteristics =
3894 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3895 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3896 ** the write succeeds */
3897 0;
3898 }
3899 }
3900 /* Last chance verification. If the sector size isn't a multiple of 512
3901 ** then it isn't valid.*/
3902 if( pFile->sectorSize % 512 != 0 ){
3903 pFile->deviceCharacteristics = 0;
3904 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3905 }
3906 return pFile->sectorSize;
3907}
3908#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003909
danielk197790949c22007-08-17 16:50:38 +00003910/*
drhf12b3f62011-12-21 14:42:29 +00003911** Return the device characteristics for the file.
3912**
drhcb15f352011-12-23 01:04:17 +00003913** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003914** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003915** file system does not always provide powersafe overwrites. (In other
3916** words, after a power-loss event, parts of the file that were never
3917** written might end up being altered.) However, non-PSOW behavior is very,
3918** very rare. And asserting PSOW makes a large reduction in the amount
3919** of required I/O for journaling, since a lot of padding is eliminated.
3920** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3921** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003922*/
drhf12b3f62011-12-21 14:42:29 +00003923static int unixDeviceCharacteristics(sqlite3_file *id){
3924 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003925 int rc = 0;
3926#ifdef __QNXNTO__
3927 if( p->sectorSize==0 ) unixSectorSize(id);
3928 rc = p->deviceCharacteristics;
3929#endif
drhcb15f352011-12-23 01:04:17 +00003930 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003931 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003932 }
drh537dddf2012-10-26 13:46:24 +00003933 return rc;
danielk197762079062007-08-15 17:08:46 +00003934}
3935
dan702eec12014-06-23 10:04:58 +00003936#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003937
dan702eec12014-06-23 10:04:58 +00003938/*
3939** Return the system page size.
3940**
3941** This function should not be called directly by other code in this file.
3942** Instead, it should be called via macro osGetpagesize().
3943*/
3944static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003945#if OS_VXWORKS
3946 return 1024;
3947#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003948 return getpagesize();
3949#else
3950 return (int)sysconf(_SC_PAGESIZE);
3951#endif
3952}
3953
3954#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3955
3956#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003957
3958/*
drhd91c68f2010-05-14 14:52:25 +00003959** Object used to represent an shared memory buffer.
3960**
3961** When multiple threads all reference the same wal-index, each thread
3962** has its own unixShm object, but they all point to a single instance
3963** of this unixShmNode object. In other words, each wal-index is opened
3964** only once per process.
3965**
3966** Each unixShmNode object is connected to a single unixInodeInfo object.
3967** We could coalesce this object into unixInodeInfo, but that would mean
3968** every open file that does not use shared memory (in other words, most
3969** open files) would have to carry around this extra information. So
3970** the unixInodeInfo object contains a pointer to this unixShmNode object
3971** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003972**
3973** unixMutexHeld() must be true when creating or destroying
3974** this object or while reading or writing the following fields:
3975**
3976** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003977**
3978** The following fields are read-only after the object is created:
3979**
3980** fid
3981** zFilename
3982**
drhd91c68f2010-05-14 14:52:25 +00003983** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003984** unixMutexHeld() is true when reading or writing any other field
3985** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003986*/
drhd91c68f2010-05-14 14:52:25 +00003987struct unixShmNode {
3988 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003989 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003990 char *zFilename; /* Name of the mmapped file */
3991 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003992 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003993 u16 nRegion; /* Size of array apRegion */
3994 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003995 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003996 int nRef; /* Number of unixShm objects pointing to this */
3997 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003998#ifdef SQLITE_DEBUG
3999 u8 exclMask; /* Mask of exclusive locks held */
4000 u8 sharedMask; /* Mask of shared locks held */
4001 u8 nextShmId; /* Next available unixShm.id value */
4002#endif
4003};
4004
4005/*
drhd9e5c4f2010-05-12 18:01:39 +00004006** Structure used internally by this VFS to record the state of an
4007** open shared memory connection.
4008**
drhd91c68f2010-05-14 14:52:25 +00004009** The following fields are initialized when this object is created and
4010** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004011**
drhd91c68f2010-05-14 14:52:25 +00004012** unixShm.pFile
4013** unixShm.id
4014**
4015** All other fields are read/write. The unixShm.pFile->mutex must be held
4016** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004017*/
4018struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004019 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4020 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004021 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004022 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004023 u16 sharedMask; /* Mask of shared locks held */
4024 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004025};
4026
4027/*
drhd9e5c4f2010-05-12 18:01:39 +00004028** Constants used for locking
4029*/
drhbd9676c2010-06-23 17:58:38 +00004030#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004031#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004032
drhd9e5c4f2010-05-12 18:01:39 +00004033/*
drh73b64e42010-05-30 19:55:15 +00004034** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004035**
4036** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4037** otherwise.
4038*/
4039static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004040 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004041 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004042 int ofst, /* First byte of the locking range */
4043 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004044){
drhbbf76ee2015-03-10 20:22:35 +00004045 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4046 struct flock f; /* The posix advisory locking structure */
4047 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004048
drhd91c68f2010-05-14 14:52:25 +00004049 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004050 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004051 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004052
drh73b64e42010-05-30 19:55:15 +00004053 /* Shared locks never span more than one byte */
4054 assert( n==1 || lockType!=F_RDLCK );
4055
4056 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004057 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004058
drh3cb93392011-03-12 18:10:44 +00004059 if( pShmNode->h>=0 ){
4060 /* Initialize the locking parameters */
4061 memset(&f, 0, sizeof(f));
4062 f.l_type = lockType;
4063 f.l_whence = SEEK_SET;
4064 f.l_start = ofst;
4065 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004066
drhdcfb9652015-12-02 00:05:26 +00004067 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004068 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4069 }
drhd9e5c4f2010-05-12 18:01:39 +00004070
4071 /* Update the global lock state and do debug tracing */
4072#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004073 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004074 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004075 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004076 if( rc==SQLITE_OK ){
4077 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004078 OSTRACE(("unlock %d ok", ofst));
4079 pShmNode->exclMask &= ~mask;
4080 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004081 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004082 OSTRACE(("read-lock %d ok", ofst));
4083 pShmNode->exclMask &= ~mask;
4084 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004085 }else{
4086 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004087 OSTRACE(("write-lock %d ok", ofst));
4088 pShmNode->exclMask |= mask;
4089 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004090 }
4091 }else{
4092 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004093 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004094 }else if( lockType==F_RDLCK ){
4095 OSTRACE(("read-lock failed"));
4096 }else{
4097 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004098 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004099 }
4100 }
drh20e1f082010-05-31 16:10:12 +00004101 OSTRACE((" - afterwards %03x,%03x\n",
4102 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004103 }
drhd9e5c4f2010-05-12 18:01:39 +00004104#endif
4105
4106 return rc;
4107}
4108
dan781e34c2014-03-20 08:59:47 +00004109/*
dan781e34c2014-03-20 08:59:47 +00004110** Return the minimum number of 32KB shm regions that should be mapped at
4111** a time, assuming that each mapping must be an integer multiple of the
4112** current system page-size.
4113**
4114** Usually, this is 1. The exception seems to be systems that are configured
4115** to use 64KB pages - in this case each mapping must cover at least two
4116** shm regions.
4117*/
4118static int unixShmRegionPerMap(void){
4119 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004120 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004121 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4122 if( pgsz<shmsz ) return 1;
4123 return pgsz/shmsz;
4124}
drhd9e5c4f2010-05-12 18:01:39 +00004125
4126/*
drhd91c68f2010-05-14 14:52:25 +00004127** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004128**
4129** This is not a VFS shared-memory method; it is a utility function called
4130** by VFS shared-memory methods.
4131*/
drhd91c68f2010-05-14 14:52:25 +00004132static void unixShmPurge(unixFile *pFd){
4133 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004134 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004135 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004136 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004137 int i;
drhd91c68f2010-05-14 14:52:25 +00004138 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004139 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004140 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004141 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004142 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004143 }else{
4144 sqlite3_free(p->apRegion[i]);
4145 }
dan13a3cb82010-06-11 19:04:21 +00004146 }
dan18801912010-06-14 14:07:50 +00004147 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004148 if( p->h>=0 ){
4149 robust_close(pFd, p->h, __LINE__);
4150 p->h = -1;
4151 }
drhd91c68f2010-05-14 14:52:25 +00004152 p->pInode->pShmNode = 0;
4153 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004154 }
4155}
4156
4157/*
danda9fe0c2010-07-13 18:44:03 +00004158** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004159** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004160**
drh7234c6d2010-06-19 15:10:09 +00004161** The file used to implement shared-memory is in the same directory
4162** as the open database file and has the same name as the open database
4163** file with the "-shm" suffix added. For example, if the database file
4164** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004165** for shared memory will be called "/home/user1/config.db-shm".
4166**
4167** Another approach to is to use files in /dev/shm or /dev/tmp or an
4168** some other tmpfs mount. But if a file in a different directory
4169** from the database file is used, then differing access permissions
4170** or a chroot() might cause two different processes on the same
4171** database to end up using different files for shared memory -
4172** meaning that their memory would not really be shared - resulting
4173** in database corruption. Nevertheless, this tmpfs file usage
4174** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4175** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4176** option results in an incompatible build of SQLite; builds of SQLite
4177** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4178** same database file at the same time, database corruption will likely
4179** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4180** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004181**
4182** When opening a new shared-memory file, if no other instances of that
4183** file are currently open, in this process or in other processes, then
4184** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004185**
4186** If the original database file (pDbFd) is using the "unix-excl" VFS
4187** that means that an exclusive lock is held on the database file and
4188** that no other processes are able to read or write the database. In
4189** that case, we do not really need shared memory. No shared memory
4190** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004191*/
danda9fe0c2010-07-13 18:44:03 +00004192static int unixOpenSharedMemory(unixFile *pDbFd){
4193 struct unixShm *p = 0; /* The connection to be opened */
4194 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4195 int rc; /* Result code */
4196 unixInodeInfo *pInode; /* The inode of fd */
4197 char *zShmFilename; /* Name of the file used for SHM */
4198 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004199
danda9fe0c2010-07-13 18:44:03 +00004200 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004201 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004202 if( p==0 ) return SQLITE_NOMEM;
4203 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004204 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004205
danda9fe0c2010-07-13 18:44:03 +00004206 /* Check to see if a unixShmNode object already exists. Reuse an existing
4207 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004208 */
4209 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004210 pInode = pDbFd->pInode;
4211 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004212 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004213 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004214#ifndef SQLITE_SHM_DIRECTORY
4215 const char *zBasePath = pDbFd->zPath;
4216#endif
danddb0ac42010-07-14 14:48:58 +00004217
4218 /* Call fstat() to figure out the permissions on the database file. If
4219 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004220 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004221 */
drhf3b1ed02015-12-02 13:11:03 +00004222 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004223 rc = SQLITE_IOERR_FSTAT;
4224 goto shm_open_err;
4225 }
4226
drha4ced192010-07-15 18:32:40 +00004227#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004228 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004229#else
drh4bf66fd2015-02-19 02:43:02 +00004230 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004231#endif
drhf3cdcdc2015-04-29 16:50:28 +00004232 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004233 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004234 rc = SQLITE_NOMEM;
4235 goto shm_open_err;
4236 }
drh9cb5a0d2012-01-05 21:19:54 +00004237 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004238 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004239#ifdef SQLITE_SHM_DIRECTORY
4240 sqlite3_snprintf(nShmFilename, zShmFilename,
4241 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4242 (u32)sStat.st_ino, (u32)sStat.st_dev);
4243#else
drh4bf66fd2015-02-19 02:43:02 +00004244 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004245 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004246#endif
drhd91c68f2010-05-14 14:52:25 +00004247 pShmNode->h = -1;
4248 pDbFd->pInode->pShmNode = pShmNode;
4249 pShmNode->pInode = pDbFd->pInode;
4250 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4251 if( pShmNode->mutex==0 ){
4252 rc = SQLITE_NOMEM;
4253 goto shm_open_err;
4254 }
drhd9e5c4f2010-05-12 18:01:39 +00004255
drh3cb93392011-03-12 18:10:44 +00004256 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004257 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004258 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004259 openFlags = O_RDONLY;
4260 pShmNode->isReadonly = 1;
4261 }
4262 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004263 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004264 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4265 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004266 }
drhac7c3ac2012-02-11 19:23:48 +00004267
4268 /* If this process is running as root, make sure that the SHM file
4269 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004270 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004271 */
drh6226ca22015-11-24 15:06:28 +00004272 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004273
4274 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004275 ** If not, truncate the file to zero length.
4276 */
4277 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004278 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004279 if( robust_ftruncate(pShmNode->h, 0) ){
4280 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004281 }
4282 }
drh66dfec8b2011-06-01 20:01:49 +00004283 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004284 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004285 }
4286 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004287 }
drhd9e5c4f2010-05-12 18:01:39 +00004288 }
4289
drhd91c68f2010-05-14 14:52:25 +00004290 /* Make the new connection a child of the unixShmNode */
4291 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004292#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004293 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004294#endif
drhd91c68f2010-05-14 14:52:25 +00004295 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004296 pDbFd->pShm = p;
4297 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004298
4299 /* The reference count on pShmNode has already been incremented under
4300 ** the cover of the unixEnterMutex() mutex and the pointer from the
4301 ** new (struct unixShm) object to the pShmNode has been set. All that is
4302 ** left to do is to link the new object into the linked list starting
4303 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4304 ** mutex.
4305 */
4306 sqlite3_mutex_enter(pShmNode->mutex);
4307 p->pNext = pShmNode->pFirst;
4308 pShmNode->pFirst = p;
4309 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004310 return SQLITE_OK;
4311
4312 /* Jump here on any error */
4313shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004314 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004315 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004316 unixLeaveMutex();
4317 return rc;
4318}
4319
4320/*
danda9fe0c2010-07-13 18:44:03 +00004321** This function is called to obtain a pointer to region iRegion of the
4322** shared-memory associated with the database file fd. Shared-memory regions
4323** are numbered starting from zero. Each shared-memory region is szRegion
4324** bytes in size.
4325**
4326** If an error occurs, an error code is returned and *pp is set to NULL.
4327**
4328** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4329** region has not been allocated (by any client, including one running in a
4330** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4331** bExtend is non-zero and the requested shared-memory region has not yet
4332** been allocated, it is allocated by this function.
4333**
4334** If the shared-memory region has already been allocated or is allocated by
4335** this call as described above, then it is mapped into this processes
4336** address space (if it is not already), *pp is set to point to the mapped
4337** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004338*/
danda9fe0c2010-07-13 18:44:03 +00004339static int unixShmMap(
4340 sqlite3_file *fd, /* Handle open on database file */
4341 int iRegion, /* Region to retrieve */
4342 int szRegion, /* Size of regions */
4343 int bExtend, /* True to extend file if necessary */
4344 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004345){
danda9fe0c2010-07-13 18:44:03 +00004346 unixFile *pDbFd = (unixFile*)fd;
4347 unixShm *p;
4348 unixShmNode *pShmNode;
4349 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004350 int nShmPerMap = unixShmRegionPerMap();
4351 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004352
danda9fe0c2010-07-13 18:44:03 +00004353 /* If the shared-memory file has not yet been opened, open it now. */
4354 if( pDbFd->pShm==0 ){
4355 rc = unixOpenSharedMemory(pDbFd);
4356 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004357 }
drhd9e5c4f2010-05-12 18:01:39 +00004358
danda9fe0c2010-07-13 18:44:03 +00004359 p = pDbFd->pShm;
4360 pShmNode = p->pShmNode;
4361 sqlite3_mutex_enter(pShmNode->mutex);
4362 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004363 assert( pShmNode->pInode==pDbFd->pInode );
4364 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4365 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004366
dan781e34c2014-03-20 08:59:47 +00004367 /* Minimum number of regions required to be mapped. */
4368 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4369
4370 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004371 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004372 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004373 struct stat sStat; /* Used by fstat() */
4374
4375 pShmNode->szRegion = szRegion;
4376
drh3cb93392011-03-12 18:10:44 +00004377 if( pShmNode->h>=0 ){
4378 /* The requested region is not mapped into this processes address space.
4379 ** Check to see if it has been allocated (i.e. if the wal-index file is
4380 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004381 */
drh3cb93392011-03-12 18:10:44 +00004382 if( osFstat(pShmNode->h, &sStat) ){
4383 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004384 goto shmpage_out;
4385 }
drh3cb93392011-03-12 18:10:44 +00004386
4387 if( sStat.st_size<nByte ){
4388 /* The requested memory region does not exist. If bExtend is set to
4389 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004390 */
dan47a2b4a2013-04-26 16:09:29 +00004391 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004392 goto shmpage_out;
4393 }
dan47a2b4a2013-04-26 16:09:29 +00004394
4395 /* Alternatively, if bExtend is true, extend the file. Do this by
4396 ** writing a single byte to the end of each (OS) page being
4397 ** allocated or extended. Technically, we need only write to the
4398 ** last page in order to extend the file. But writing to all new
4399 ** pages forces the OS to allocate them immediately, which reduces
4400 ** the chances of SIGBUS while accessing the mapped region later on.
4401 */
4402 else{
4403 static const int pgsz = 4096;
4404 int iPg;
4405
4406 /* Write to the last byte of each newly allocated or extended page */
4407 assert( (nByte % pgsz)==0 );
4408 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004409 int x = 0;
4410 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004411 const char *zFile = pShmNode->zFilename;
4412 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4413 goto shmpage_out;
4414 }
4415 }
drh3cb93392011-03-12 18:10:44 +00004416 }
4417 }
danda9fe0c2010-07-13 18:44:03 +00004418 }
4419
4420 /* Map the requested memory region into this processes address space. */
4421 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004422 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004423 );
4424 if( !apNew ){
4425 rc = SQLITE_IOERR_NOMEM;
4426 goto shmpage_out;
4427 }
4428 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004429 while( pShmNode->nRegion<nReqRegion ){
4430 int nMap = szRegion*nShmPerMap;
4431 int i;
drh3cb93392011-03-12 18:10:44 +00004432 void *pMem;
4433 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004434 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004435 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004436 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004437 );
4438 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004439 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004440 goto shmpage_out;
4441 }
4442 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004443 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004444 if( pMem==0 ){
4445 rc = SQLITE_NOMEM;
4446 goto shmpage_out;
4447 }
4448 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004449 }
dan781e34c2014-03-20 08:59:47 +00004450
4451 for(i=0; i<nShmPerMap; i++){
4452 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4453 }
4454 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004455 }
4456 }
4457
4458shmpage_out:
4459 if( pShmNode->nRegion>iRegion ){
4460 *pp = pShmNode->apRegion[iRegion];
4461 }else{
4462 *pp = 0;
4463 }
drh66dfec8b2011-06-01 20:01:49 +00004464 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004465 sqlite3_mutex_leave(pShmNode->mutex);
4466 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004467}
4468
4469/*
drhd9e5c4f2010-05-12 18:01:39 +00004470** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004471**
4472** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4473** different here than in posix. In xShmLock(), one can go from unlocked
4474** to shared and back or from unlocked to exclusive and back. But one may
4475** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004476*/
4477static int unixShmLock(
4478 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004479 int ofst, /* First lock to acquire or release */
4480 int n, /* Number of locks to acquire or release */
4481 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004482){
drh73b64e42010-05-30 19:55:15 +00004483 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4484 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4485 unixShm *pX; /* For looping over all siblings */
4486 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4487 int rc = SQLITE_OK; /* Result code */
4488 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004489
drhd91c68f2010-05-14 14:52:25 +00004490 assert( pShmNode==pDbFd->pInode->pShmNode );
4491 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004492 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004493 assert( n>=1 );
4494 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4495 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4496 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4497 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4498 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004499 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4500 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004501
drhc99597c2010-05-31 01:41:15 +00004502 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004503 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004504 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004505 if( flags & SQLITE_SHM_UNLOCK ){
4506 u16 allMask = 0; /* Mask of locks held by siblings */
4507
4508 /* See if any siblings hold this same lock */
4509 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4510 if( pX==p ) continue;
4511 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4512 allMask |= pX->sharedMask;
4513 }
4514
4515 /* Unlock the system-level locks */
4516 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004517 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004518 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004519 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004520 }
drh73b64e42010-05-30 19:55:15 +00004521
4522 /* Undo the local locks */
4523 if( rc==SQLITE_OK ){
4524 p->exclMask &= ~mask;
4525 p->sharedMask &= ~mask;
4526 }
4527 }else if( flags & SQLITE_SHM_SHARED ){
4528 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4529
4530 /* Find out which shared locks are already held by sibling connections.
4531 ** If any sibling already holds an exclusive lock, go ahead and return
4532 ** SQLITE_BUSY.
4533 */
4534 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004535 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004536 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004537 break;
4538 }
4539 allShared |= pX->sharedMask;
4540 }
4541
4542 /* Get shared locks at the system level, if necessary */
4543 if( rc==SQLITE_OK ){
4544 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004545 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004546 }else{
drh73b64e42010-05-30 19:55:15 +00004547 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004548 }
drhd9e5c4f2010-05-12 18:01:39 +00004549 }
drh73b64e42010-05-30 19:55:15 +00004550
4551 /* Get the local shared locks */
4552 if( rc==SQLITE_OK ){
4553 p->sharedMask |= mask;
4554 }
4555 }else{
4556 /* Make sure no sibling connections hold locks that will block this
4557 ** lock. If any do, return SQLITE_BUSY right away.
4558 */
4559 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004560 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4561 rc = SQLITE_BUSY;
4562 break;
4563 }
4564 }
4565
4566 /* Get the exclusive locks at the system level. Then if successful
4567 ** also mark the local connection as being locked.
4568 */
4569 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004570 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004571 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004572 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004573 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004574 }
drhd9e5c4f2010-05-12 18:01:39 +00004575 }
4576 }
drhd91c68f2010-05-14 14:52:25 +00004577 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004578 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004579 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004580 return rc;
4581}
4582
drh286a2882010-05-20 23:51:06 +00004583/*
4584** Implement a memory barrier or memory fence on shared memory.
4585**
4586** All loads and stores begun before the barrier must complete before
4587** any load or store begun after the barrier.
4588*/
4589static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004590 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004591){
drhff828942010-06-26 21:34:06 +00004592 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004593 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4594 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004595 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004596}
4597
dan18801912010-06-14 14:07:50 +00004598/*
danda9fe0c2010-07-13 18:44:03 +00004599** Close a connection to shared-memory. Delete the underlying
4600** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004601**
4602** If there is no shared memory associated with the connection then this
4603** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004604*/
danda9fe0c2010-07-13 18:44:03 +00004605static int unixShmUnmap(
4606 sqlite3_file *fd, /* The underlying database file */
4607 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004608){
danda9fe0c2010-07-13 18:44:03 +00004609 unixShm *p; /* The connection to be closed */
4610 unixShmNode *pShmNode; /* The underlying shared-memory file */
4611 unixShm **pp; /* For looping over sibling connections */
4612 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004613
danda9fe0c2010-07-13 18:44:03 +00004614 pDbFd = (unixFile*)fd;
4615 p = pDbFd->pShm;
4616 if( p==0 ) return SQLITE_OK;
4617 pShmNode = p->pShmNode;
4618
4619 assert( pShmNode==pDbFd->pInode->pShmNode );
4620 assert( pShmNode->pInode==pDbFd->pInode );
4621
4622 /* Remove connection p from the set of connections associated
4623 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004624 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004625 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4626 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004627
danda9fe0c2010-07-13 18:44:03 +00004628 /* Free the connection p */
4629 sqlite3_free(p);
4630 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004631 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004632
4633 /* If pShmNode->nRef has reached 0, then close the underlying
4634 ** shared-memory file, too */
4635 unixEnterMutex();
4636 assert( pShmNode->nRef>0 );
4637 pShmNode->nRef--;
4638 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004639 if( deleteFlag && pShmNode->h>=0 ){
4640 osUnlink(pShmNode->zFilename);
4641 }
danda9fe0c2010-07-13 18:44:03 +00004642 unixShmPurge(pDbFd);
4643 }
4644 unixLeaveMutex();
4645
4646 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004647}
drh286a2882010-05-20 23:51:06 +00004648
danda9fe0c2010-07-13 18:44:03 +00004649
drhd9e5c4f2010-05-12 18:01:39 +00004650#else
drh6b017cc2010-06-14 18:01:46 +00004651# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004652# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004653# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004654# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004655#endif /* #ifndef SQLITE_OMIT_WAL */
4656
mistachkine98844f2013-08-24 00:59:24 +00004657#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004658/*
danaef49d72013-03-25 16:28:54 +00004659** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004660*/
danf23da962013-03-23 21:00:41 +00004661static void unixUnmapfile(unixFile *pFd){
4662 assert( pFd->nFetchOut==0 );
4663 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004664 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004665 pFd->pMapRegion = 0;
4666 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004667 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004668 }
4669}
dan5d8a1372013-03-19 19:28:06 +00004670
danaef49d72013-03-25 16:28:54 +00004671/*
dane6ecd662013-04-01 17:56:59 +00004672** Attempt to set the size of the memory mapping maintained by file
4673** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4674**
4675** If successful, this function sets the following variables:
4676**
4677** unixFile.pMapRegion
4678** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004679** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004680**
4681** If unsuccessful, an error message is logged via sqlite3_log() and
4682** the three variables above are zeroed. In this case SQLite should
4683** continue accessing the database using the xRead() and xWrite()
4684** methods.
4685*/
4686static void unixRemapfile(
4687 unixFile *pFd, /* File descriptor object */
4688 i64 nNew /* Required mapping size */
4689){
dan4ff7bc42013-04-02 12:04:09 +00004690 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004691 int h = pFd->h; /* File descriptor open on db file */
4692 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004693 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004694 u8 *pNew = 0; /* Location of new mapping */
4695 int flags = PROT_READ; /* Flags to pass to mmap() */
4696
4697 assert( pFd->nFetchOut==0 );
4698 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004699 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004700 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004701 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004702 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004703
danfe33e392015-11-17 20:56:06 +00004704#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004705 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004706#endif
dane6ecd662013-04-01 17:56:59 +00004707
4708 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004709#if HAVE_MREMAP
4710 i64 nReuse = pFd->mmapSize;
4711#else
danbc760632014-03-20 09:42:09 +00004712 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004713 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004714#endif
dane6ecd662013-04-01 17:56:59 +00004715 u8 *pReq = &pOrig[nReuse];
4716
4717 /* Unmap any pages of the existing mapping that cannot be reused. */
4718 if( nReuse!=nOrig ){
4719 osMunmap(pReq, nOrig-nReuse);
4720 }
4721
4722#if HAVE_MREMAP
4723 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004724 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004725#else
4726 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4727 if( pNew!=MAP_FAILED ){
4728 if( pNew!=pReq ){
4729 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004730 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004731 }else{
4732 pNew = pOrig;
4733 }
4734 }
4735#endif
4736
dan48ccef82013-04-02 20:55:01 +00004737 /* The attempt to extend the existing mapping failed. Free it. */
4738 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004739 osMunmap(pOrig, nReuse);
4740 }
4741 }
4742
4743 /* If pNew is still NULL, try to create an entirely new mapping. */
4744 if( pNew==0 ){
4745 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004746 }
4747
dan4ff7bc42013-04-02 12:04:09 +00004748 if( pNew==MAP_FAILED ){
4749 pNew = 0;
4750 nNew = 0;
4751 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4752
4753 /* If the mmap() above failed, assume that all subsequent mmap() calls
4754 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4755 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004756 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004757 }
dane6ecd662013-04-01 17:56:59 +00004758 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004759 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004760}
4761
4762/*
danaef49d72013-03-25 16:28:54 +00004763** Memory map or remap the file opened by file-descriptor pFd (if the file
4764** is already mapped, the existing mapping is replaced by the new). Or, if
4765** there already exists a mapping for this file, and there are still
4766** outstanding xFetch() references to it, this function is a no-op.
4767**
4768** If parameter nByte is non-negative, then it is the requested size of
4769** the mapping to create. Otherwise, if nByte is less than zero, then the
4770** requested size is the size of the file on disk. The actual size of the
4771** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004772** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004773**
4774** SQLITE_OK is returned if no error occurs (even if the mapping is not
4775** recreated as a result of outstanding references) or an SQLite error
4776** code otherwise.
4777*/
drhf3b1ed02015-12-02 13:11:03 +00004778static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004779 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004780 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004781 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4782
4783 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004784 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004785 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004786 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004787 }
drh3044b512014-06-16 16:41:52 +00004788 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004789 }
drh9b4c59f2013-04-15 17:03:42 +00004790 if( nMap>pFd->mmapSizeMax ){
4791 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004792 }
4793
drh333e6ca2015-12-02 15:44:39 +00004794 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004795 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004796 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004797 }
4798
danf23da962013-03-23 21:00:41 +00004799 return SQLITE_OK;
4800}
mistachkine98844f2013-08-24 00:59:24 +00004801#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004802
danaef49d72013-03-25 16:28:54 +00004803/*
4804** If possible, return a pointer to a mapping of file fd starting at offset
4805** iOff. The mapping must be valid for at least nAmt bytes.
4806**
4807** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4808** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4809** Finally, if an error does occur, return an SQLite error code. The final
4810** value of *pp is undefined in this case.
4811**
4812** If this function does return a pointer, the caller must eventually
4813** release the reference by calling unixUnfetch().
4814*/
danf23da962013-03-23 21:00:41 +00004815static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004816#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004817 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004818#endif
danf23da962013-03-23 21:00:41 +00004819 *pp = 0;
4820
drh9b4c59f2013-04-15 17:03:42 +00004821#if SQLITE_MAX_MMAP_SIZE>0
4822 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004823 if( pFd->pMapRegion==0 ){
4824 int rc = unixMapfile(pFd, -1);
4825 if( rc!=SQLITE_OK ) return rc;
4826 }
4827 if( pFd->mmapSize >= iOff+nAmt ){
4828 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4829 pFd->nFetchOut++;
4830 }
4831 }
drh6e0b6d52013-04-09 16:19:20 +00004832#endif
danf23da962013-03-23 21:00:41 +00004833 return SQLITE_OK;
4834}
4835
danaef49d72013-03-25 16:28:54 +00004836/*
dandf737fe2013-03-25 17:00:24 +00004837** If the third argument is non-NULL, then this function releases a
4838** reference obtained by an earlier call to unixFetch(). The second
4839** argument passed to this function must be the same as the corresponding
4840** argument that was passed to the unixFetch() invocation.
4841**
4842** Or, if the third argument is NULL, then this function is being called
4843** to inform the VFS layer that, according to POSIX, any existing mapping
4844** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004845*/
dandf737fe2013-03-25 17:00:24 +00004846static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004847#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004848 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004849 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004850
danaef49d72013-03-25 16:28:54 +00004851 /* If p==0 (unmap the entire file) then there must be no outstanding
4852 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4853 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004854 assert( (p==0)==(pFd->nFetchOut==0) );
4855
dandf737fe2013-03-25 17:00:24 +00004856 /* If p!=0, it must match the iOff value. */
4857 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4858
danf23da962013-03-23 21:00:41 +00004859 if( p ){
4860 pFd->nFetchOut--;
4861 }else{
4862 unixUnmapfile(pFd);
4863 }
4864
4865 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004866#else
4867 UNUSED_PARAMETER(fd);
4868 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004869 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004870#endif
danf23da962013-03-23 21:00:41 +00004871 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004872}
4873
4874/*
drh734c9862008-11-28 15:37:20 +00004875** Here ends the implementation of all sqlite3_file methods.
4876**
4877********************** End sqlite3_file Methods *******************************
4878******************************************************************************/
4879
4880/*
drh6b9d6dd2008-12-03 19:34:47 +00004881** This division contains definitions of sqlite3_io_methods objects that
4882** implement various file locking strategies. It also contains definitions
4883** of "finder" functions. A finder-function is used to locate the appropriate
4884** sqlite3_io_methods object for a particular database file. The pAppData
4885** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4886** the correct finder-function for that VFS.
4887**
4888** Most finder functions return a pointer to a fixed sqlite3_io_methods
4889** object. The only interesting finder-function is autolockIoFinder, which
4890** looks at the filesystem type and tries to guess the best locking
4891** strategy from that.
4892**
peter.d.reid60ec9142014-09-06 16:39:46 +00004893** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004894**
4895** (1) The real finder-function named "FImpt()".
4896**
dane946c392009-08-22 11:39:46 +00004897** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004898**
4899**
4900** A pointer to the F pointer is used as the pAppData value for VFS
4901** objects. We have to do this instead of letting pAppData point
4902** directly at the finder-function since C90 rules prevent a void*
4903** from be cast into a function pointer.
4904**
drh6b9d6dd2008-12-03 19:34:47 +00004905**
drh7708e972008-11-29 00:56:52 +00004906** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004907**
drh7708e972008-11-29 00:56:52 +00004908** * A constant sqlite3_io_methods object call METHOD that has locking
4909** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4910**
4911** * An I/O method finder function called FINDER that returns a pointer
4912** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004913*/
drhe6d41732015-02-21 00:49:00 +00004914#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004915static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004916 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004917 CLOSE, /* xClose */ \
4918 unixRead, /* xRead */ \
4919 unixWrite, /* xWrite */ \
4920 unixTruncate, /* xTruncate */ \
4921 unixSync, /* xSync */ \
4922 unixFileSize, /* xFileSize */ \
4923 LOCK, /* xLock */ \
4924 UNLOCK, /* xUnlock */ \
4925 CKLOCK, /* xCheckReservedLock */ \
4926 unixFileControl, /* xFileControl */ \
4927 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004928 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004929 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004930 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004931 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004932 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004933 unixFetch, /* xFetch */ \
4934 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004935}; \
drh0c2694b2009-09-03 16:23:44 +00004936static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4937 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004938 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004939} \
drh0c2694b2009-09-03 16:23:44 +00004940static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004941 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004942
4943/*
4944** Here are all of the sqlite3_io_methods objects for each of the
4945** locking strategies. Functions that return pointers to these methods
4946** are also created.
4947*/
4948IOMETHODS(
4949 posixIoFinder, /* Finder function name */
4950 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004951 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004952 unixClose, /* xClose method */
4953 unixLock, /* xLock method */
4954 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004955 unixCheckReservedLock, /* xCheckReservedLock method */
4956 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004957)
drh7708e972008-11-29 00:56:52 +00004958IOMETHODS(
4959 nolockIoFinder, /* Finder function name */
4960 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004961 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004962 nolockClose, /* xClose method */
4963 nolockLock, /* xLock method */
4964 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004965 nolockCheckReservedLock, /* xCheckReservedLock method */
4966 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004967)
drh7708e972008-11-29 00:56:52 +00004968IOMETHODS(
4969 dotlockIoFinder, /* Finder function name */
4970 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004971 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004972 dotlockClose, /* xClose method */
4973 dotlockLock, /* xLock method */
4974 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004975 dotlockCheckReservedLock, /* xCheckReservedLock method */
4976 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004977)
drh7708e972008-11-29 00:56:52 +00004978
drhe89b2912015-03-03 20:42:01 +00004979#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004980IOMETHODS(
4981 flockIoFinder, /* Finder function name */
4982 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004983 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004984 flockClose, /* xClose method */
4985 flockLock, /* xLock method */
4986 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004987 flockCheckReservedLock, /* xCheckReservedLock method */
4988 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004989)
drh7708e972008-11-29 00:56:52 +00004990#endif
4991
drh6c7d5c52008-11-21 20:32:33 +00004992#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004993IOMETHODS(
4994 semIoFinder, /* Finder function name */
4995 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004996 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00004997 semXClose, /* xClose method */
4998 semXLock, /* xLock method */
4999 semXUnlock, /* xUnlock method */
5000 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005001 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005002)
aswiftaebf4132008-11-21 00:10:35 +00005003#endif
drh7708e972008-11-29 00:56:52 +00005004
drhd2cb50b2009-01-09 21:41:17 +00005005#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005006IOMETHODS(
5007 afpIoFinder, /* Finder function name */
5008 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005009 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005010 afpClose, /* xClose method */
5011 afpLock, /* xLock method */
5012 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005013 afpCheckReservedLock, /* xCheckReservedLock method */
5014 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005015)
drh715ff302008-12-03 22:32:44 +00005016#endif
5017
5018/*
5019** The proxy locking method is a "super-method" in the sense that it
5020** opens secondary file descriptors for the conch and lock files and
5021** it uses proxy, dot-file, AFP, and flock() locking methods on those
5022** secondary files. For this reason, the division that implements
5023** proxy locking is located much further down in the file. But we need
5024** to go ahead and define the sqlite3_io_methods and finder function
5025** for proxy locking here. So we forward declare the I/O methods.
5026*/
drhd2cb50b2009-01-09 21:41:17 +00005027#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005028static int proxyClose(sqlite3_file*);
5029static int proxyLock(sqlite3_file*, int);
5030static int proxyUnlock(sqlite3_file*, int);
5031static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005032IOMETHODS(
5033 proxyIoFinder, /* Finder function name */
5034 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005035 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005036 proxyClose, /* xClose method */
5037 proxyLock, /* xLock method */
5038 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005039 proxyCheckReservedLock, /* xCheckReservedLock method */
5040 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005041)
aswiftaebf4132008-11-21 00:10:35 +00005042#endif
drh7708e972008-11-29 00:56:52 +00005043
drh7ed97b92010-01-20 13:07:21 +00005044/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5045#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5046IOMETHODS(
5047 nfsIoFinder, /* Finder function name */
5048 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005049 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005050 unixClose, /* xClose method */
5051 unixLock, /* xLock method */
5052 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005053 unixCheckReservedLock, /* xCheckReservedLock method */
5054 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005055)
5056#endif
drh7708e972008-11-29 00:56:52 +00005057
drhd2cb50b2009-01-09 21:41:17 +00005058#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005059/*
drh6b9d6dd2008-12-03 19:34:47 +00005060** This "finder" function attempts to determine the best locking strategy
5061** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005062** object that implements that strategy.
5063**
5064** This is for MacOSX only.
5065*/
drh1875f7a2008-12-08 18:19:17 +00005066static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005067 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005068 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005069){
5070 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005071 const char *zFilesystem; /* Filesystem type name */
5072 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005073 } aMap[] = {
5074 { "hfs", &posixIoMethods },
5075 { "ufs", &posixIoMethods },
5076 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005077 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005078 { "webdav", &nolockIoMethods },
5079 { 0, 0 }
5080 };
5081 int i;
5082 struct statfs fsInfo;
5083 struct flock lockInfo;
5084
5085 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005086 /* If filePath==NULL that means we are dealing with a transient file
5087 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005088 return &nolockIoMethods;
5089 }
5090 if( statfs(filePath, &fsInfo) != -1 ){
5091 if( fsInfo.f_flags & MNT_RDONLY ){
5092 return &nolockIoMethods;
5093 }
5094 for(i=0; aMap[i].zFilesystem; i++){
5095 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5096 return aMap[i].pMethods;
5097 }
5098 }
5099 }
5100
5101 /* Default case. Handles, amongst others, "nfs".
5102 ** Test byte-range lock using fcntl(). If the call succeeds,
5103 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005104 */
drh7708e972008-11-29 00:56:52 +00005105 lockInfo.l_len = 1;
5106 lockInfo.l_start = 0;
5107 lockInfo.l_whence = SEEK_SET;
5108 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005109 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005110 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5111 return &nfsIoMethods;
5112 } else {
5113 return &posixIoMethods;
5114 }
drh7708e972008-11-29 00:56:52 +00005115 }else{
5116 return &dotlockIoMethods;
5117 }
5118}
drh0c2694b2009-09-03 16:23:44 +00005119static const sqlite3_io_methods
5120 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005121
drhd2cb50b2009-01-09 21:41:17 +00005122#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005123
drhe89b2912015-03-03 20:42:01 +00005124#if OS_VXWORKS
5125/*
5126** This "finder" function for VxWorks checks to see if posix advisory
5127** locking works. If it does, then that is what is used. If it does not
5128** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005129*/
drhe89b2912015-03-03 20:42:01 +00005130static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005131 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005132 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005133){
5134 struct flock lockInfo;
5135
5136 if( !filePath ){
5137 /* If filePath==NULL that means we are dealing with a transient file
5138 ** that does not need to be locked. */
5139 return &nolockIoMethods;
5140 }
5141
5142 /* Test if fcntl() is supported and use POSIX style locks.
5143 ** Otherwise fall back to the named semaphore method.
5144 */
5145 lockInfo.l_len = 1;
5146 lockInfo.l_start = 0;
5147 lockInfo.l_whence = SEEK_SET;
5148 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005149 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005150 return &posixIoMethods;
5151 }else{
5152 return &semIoMethods;
5153 }
5154}
drh0c2694b2009-09-03 16:23:44 +00005155static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005156 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005157
drhe89b2912015-03-03 20:42:01 +00005158#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005159
drh7708e972008-11-29 00:56:52 +00005160/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005161** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005162*/
drh0c2694b2009-09-03 16:23:44 +00005163typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005164
aswiftaebf4132008-11-21 00:10:35 +00005165
drh734c9862008-11-28 15:37:20 +00005166/****************************************************************************
5167**************************** sqlite3_vfs methods ****************************
5168**
5169** This division contains the implementation of methods on the
5170** sqlite3_vfs object.
5171*/
5172
danielk1977a3d4c882007-03-23 10:08:38 +00005173/*
danielk1977e339d652008-06-28 11:23:00 +00005174** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005175*/
5176static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005177 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005178 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005179 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005180 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005181 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005182){
drh7708e972008-11-29 00:56:52 +00005183 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005184 unixFile *pNew = (unixFile *)pId;
5185 int rc = SQLITE_OK;
5186
drh8af6c222010-05-14 12:43:01 +00005187 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005188
dan00157392010-10-05 11:33:15 +00005189 /* Usually the path zFilename should not be a relative pathname. The
5190 ** exception is when opening the proxy "conch" file in builds that
5191 ** include the special Apple locking styles.
5192 */
dan00157392010-10-05 11:33:15 +00005193#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005194 assert( zFilename==0 || zFilename[0]=='/'
5195 || pVfs->pAppData==(void*)&autolockIoFinder );
5196#else
5197 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005198#endif
dan00157392010-10-05 11:33:15 +00005199
drhb07028f2011-10-14 21:49:18 +00005200 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005201 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005202
drh308c2a52010-05-14 11:30:18 +00005203 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005204 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005205 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005206 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005207 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005208#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005209 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005210#endif
drhc02a43a2012-01-10 23:18:38 +00005211 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5212 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005213 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005214 }
drh503a6862013-03-01 01:07:17 +00005215 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005216 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005217 }
drh339eb0b2008-03-07 15:34:11 +00005218
drh6c7d5c52008-11-21 20:32:33 +00005219#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005220 pNew->pId = vxworksFindFileId(zFilename);
5221 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005222 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005223 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005224 }
5225#endif
5226
drhc02a43a2012-01-10 23:18:38 +00005227 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005228 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005229 }else{
drh0c2694b2009-09-03 16:23:44 +00005230 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005231#if SQLITE_ENABLE_LOCKING_STYLE
5232 /* Cache zFilename in the locking context (AFP and dotlock override) for
5233 ** proxyLock activation is possible (remote proxy is based on db name)
5234 ** zFilename remains valid until file is closed, to support */
5235 pNew->lockingContext = (void*)zFilename;
5236#endif
drhda0e7682008-07-30 15:27:54 +00005237 }
danielk1977e339d652008-06-28 11:23:00 +00005238
drh7ed97b92010-01-20 13:07:21 +00005239 if( pLockingStyle == &posixIoMethods
5240#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5241 || pLockingStyle == &nfsIoMethods
5242#endif
5243 ){
drh7708e972008-11-29 00:56:52 +00005244 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005245 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005246 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005247 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005248 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005249 ** in two scenarios:
5250 **
5251 ** (a) A call to fstat() failed.
5252 ** (b) A malloc failed.
5253 **
5254 ** Scenario (b) may only occur if the process is holding no other
5255 ** file descriptors open on the same file. If there were other file
5256 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005257 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005258 ** handle h - as it is guaranteed that no posix locks will be released
5259 ** by doing so.
5260 **
5261 ** If scenario (a) caused the error then things are not so safe. The
5262 ** implicit assumption here is that if fstat() fails, things are in
5263 ** such bad shape that dropping a lock or two doesn't matter much.
5264 */
drh0e9365c2011-03-02 02:08:13 +00005265 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005266 h = -1;
5267 }
drh7708e972008-11-29 00:56:52 +00005268 unixLeaveMutex();
5269 }
danielk1977e339d652008-06-28 11:23:00 +00005270
drhd2cb50b2009-01-09 21:41:17 +00005271#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005272 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005273 /* AFP locking uses the file path so it needs to be included in
5274 ** the afpLockingContext.
5275 */
5276 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005277 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005278 if( pCtx==0 ){
5279 rc = SQLITE_NOMEM;
5280 }else{
5281 /* NB: zFilename exists and remains valid until the file is closed
5282 ** according to requirement F11141. So we do not need to make a
5283 ** copy of the filename. */
5284 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005285 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005286 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005287 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005288 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005289 if( rc!=SQLITE_OK ){
5290 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005291 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005292 h = -1;
5293 }
drh7708e972008-11-29 00:56:52 +00005294 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005295 }
drh7708e972008-11-29 00:56:52 +00005296 }
5297#endif
danielk1977e339d652008-06-28 11:23:00 +00005298
drh7708e972008-11-29 00:56:52 +00005299 else if( pLockingStyle == &dotlockIoMethods ){
5300 /* Dotfile locking uses the file path so it needs to be included in
5301 ** the dotlockLockingContext
5302 */
5303 char *zLockFile;
5304 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005305 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005306 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005307 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005308 if( zLockFile==0 ){
5309 rc = SQLITE_NOMEM;
5310 }else{
5311 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005312 }
drh7708e972008-11-29 00:56:52 +00005313 pNew->lockingContext = zLockFile;
5314 }
danielk1977e339d652008-06-28 11:23:00 +00005315
drh6c7d5c52008-11-21 20:32:33 +00005316#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005317 else if( pLockingStyle == &semIoMethods ){
5318 /* Named semaphore locking uses the file path so it needs to be
5319 ** included in the semLockingContext
5320 */
5321 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005322 rc = findInodeInfo(pNew, &pNew->pInode);
5323 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5324 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005325 int n;
drh2238dcc2009-08-27 17:56:20 +00005326 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005327 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005328 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005329 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005330 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5331 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005332 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005333 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005334 }
chw97185482008-11-17 08:05:31 +00005335 }
drh7708e972008-11-29 00:56:52 +00005336 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005337 }
drh7708e972008-11-29 00:56:52 +00005338#endif
aswift5b1a2562008-08-22 00:22:35 +00005339
drh4bf66fd2015-02-19 02:43:02 +00005340 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005341#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005342 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005343 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005344 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005345 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005346 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005347 }
chw97185482008-11-17 08:05:31 +00005348#endif
danielk1977e339d652008-06-28 11:23:00 +00005349 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005350 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005351 }else{
drh7708e972008-11-29 00:56:52 +00005352 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005353 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005354 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005355 }
danielk1977e339d652008-06-28 11:23:00 +00005356 return rc;
drh054889e2005-11-30 03:20:31 +00005357}
drh9c06c952005-11-26 00:25:00 +00005358
danielk1977ad94b582007-08-20 06:44:22 +00005359/*
drh8b3cf822010-06-01 21:02:51 +00005360** Return the name of a directory in which to put temporary files.
5361** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005362*/
drh7234c6d2010-06-19 15:10:09 +00005363static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005364 static const char *azDirs[] = {
5365 0,
aswiftaebf4132008-11-21 00:10:35 +00005366 0,
danielk197717b90b52008-06-06 11:11:25 +00005367 "/var/tmp",
5368 "/usr/tmp",
5369 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005370 "."
danielk197717b90b52008-06-06 11:11:25 +00005371 };
drh8b3cf822010-06-01 21:02:51 +00005372 unsigned int i;
5373 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005374 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005375
drhb7e50ad2015-11-28 21:49:53 +00005376 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5377 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005378 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005379 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005380 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005381 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005382 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005383 break;
5384 }
5385 return zDir;
5386}
5387
5388/*
5389** Create a temporary file name in zBuf. zBuf must be allocated
5390** by the calling process and must be big enough to hold at least
5391** pVfs->mxPathname bytes.
5392*/
5393static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005394 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005395 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005396
5397 /* It's odd to simulate an io-error here, but really this is just
5398 ** using the io-error infrastructure to test that SQLite handles this
5399 ** function failing.
5400 */
5401 SimulateIOError( return SQLITE_IOERR );
5402
drh7234c6d2010-06-19 15:10:09 +00005403 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005404 do{
drh970942e2015-11-25 23:13:14 +00005405 u64 r;
5406 sqlite3_randomness(sizeof(r), &r);
5407 assert( nBuf>2 );
5408 zBuf[nBuf-2] = 0;
5409 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5410 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005411 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005412 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005413 return SQLITE_OK;
5414}
5415
drhd2cb50b2009-01-09 21:41:17 +00005416#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005417/*
5418** Routine to transform a unixFile into a proxy-locking unixFile.
5419** Implementation in the proxy-lock division, but used by unixOpen()
5420** if SQLITE_PREFER_PROXY_LOCKING is defined.
5421*/
5422static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005423#endif
drhc66d5b62008-12-03 22:48:32 +00005424
dan08da86a2009-08-21 17:18:03 +00005425/*
5426** Search for an unused file descriptor that was opened on the database
5427** file (not a journal or master-journal file) identified by pathname
5428** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5429** argument to this function.
5430**
5431** Such a file descriptor may exist if a database connection was closed
5432** but the associated file descriptor could not be closed because some
5433** other file descriptor open on the same file is holding a file-lock.
5434** Refer to comments in the unixClose() function and the lengthy comment
5435** describing "Posix Advisory Locking" at the start of this file for
5436** further details. Also, ticket #4018.
5437**
5438** If a suitable file descriptor is found, then it is returned. If no
5439** such file descriptor is located, -1 is returned.
5440*/
dane946c392009-08-22 11:39:46 +00005441static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5442 UnixUnusedFd *pUnused = 0;
5443
5444 /* Do not search for an unused file descriptor on vxworks. Not because
5445 ** vxworks would not benefit from the change (it might, we're not sure),
5446 ** but because no way to test it is currently available. It is better
5447 ** not to risk breaking vxworks support for the sake of such an obscure
5448 ** feature. */
5449#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005450 struct stat sStat; /* Results of stat() call */
5451
5452 /* A stat() call may fail for various reasons. If this happens, it is
5453 ** almost certain that an open() call on the same path will also fail.
5454 ** For this reason, if an error occurs in the stat() call here, it is
5455 ** ignored and -1 is returned. The caller will try to open a new file
5456 ** descriptor on the same path, fail, and return an error to SQLite.
5457 **
5458 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005459 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005460 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005461 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005462
5463 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005464 pInode = inodeList;
5465 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5466 || pInode->fileId.ino!=sStat.st_ino) ){
5467 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005468 }
drh8af6c222010-05-14 12:43:01 +00005469 if( pInode ){
dane946c392009-08-22 11:39:46 +00005470 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005471 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005472 pUnused = *pp;
5473 if( pUnused ){
5474 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005475 }
5476 }
5477 unixLeaveMutex();
5478 }
dane946c392009-08-22 11:39:46 +00005479#endif /* if !OS_VXWORKS */
5480 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005481}
danielk197717b90b52008-06-06 11:11:25 +00005482
5483/*
danddb0ac42010-07-14 14:48:58 +00005484** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005485** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005486** and a value suitable for passing as the third argument to open(2) is
5487** written to *pMode. If an IO error occurs, an SQLite error code is
5488** returned and the value of *pMode is not modified.
5489**
peter.d.reid60ec9142014-09-06 16:39:46 +00005490** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005491** an indication to robust_open() to create the file using
5492** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5493** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005494** this function queries the file-system for the permissions on the
5495** corresponding database file and sets *pMode to this value. Whenever
5496** possible, WAL and journal files are created using the same permissions
5497** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005498**
5499** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5500** original filename is unavailable. But 8_3_NAMES is only used for
5501** FAT filesystems and permissions do not matter there, so just use
5502** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005503*/
5504static int findCreateFileMode(
5505 const char *zPath, /* Path of file (possibly) being created */
5506 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005507 mode_t *pMode, /* OUT: Permissions to open file with */
5508 uid_t *pUid, /* OUT: uid to set on the file */
5509 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005510){
5511 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005512 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005513 *pUid = 0;
5514 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005515 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005516 char zDb[MAX_PATHNAME+1]; /* Database file path */
5517 int nDb; /* Number of valid bytes in zDb */
5518 struct stat sStat; /* Output of stat() on database file */
5519
dana0c989d2010-11-05 18:07:37 +00005520 /* zPath is a path to a WAL or journal file. The following block derives
5521 ** the path to the associated database file from zPath. This block handles
5522 ** the following naming conventions:
5523 **
5524 ** "<path to db>-journal"
5525 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005526 ** "<path to db>-journalNN"
5527 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005528 **
drhd337c5b2011-10-20 18:23:35 +00005529 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005530 ** used by the test_multiplex.c module.
5531 */
5532 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005533 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005534#ifndef SQLITE_ENABLE_8_3_NAMES
5535 /* In the normal case (8+3 filenames disabled) the journal filename
5536 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005537 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005538 assert( sqlite3Isalnum(zPath[nDb]) );
5539#else
5540 /* If 8+3 names are possible, then the journal file might not contain
5541 ** a '-' character. So check for that case and return early. */
5542 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5543#endif
drhc47167a2011-10-05 15:26:13 +00005544 nDb--;
5545 }
danddb0ac42010-07-14 14:48:58 +00005546 memcpy(zDb, zPath, nDb);
5547 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005548
drh58384f12011-07-28 00:14:45 +00005549 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005550 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005551 *pUid = sStat.st_uid;
5552 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005553 }else{
5554 rc = SQLITE_IOERR_FSTAT;
5555 }
5556 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5557 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005558 }
5559 return rc;
5560}
5561
5562/*
danielk1977ad94b582007-08-20 06:44:22 +00005563** Open the file zPath.
5564**
danielk1977b4b47412007-08-17 15:53:36 +00005565** Previously, the SQLite OS layer used three functions in place of this
5566** one:
5567**
5568** sqlite3OsOpenReadWrite();
5569** sqlite3OsOpenReadOnly();
5570** sqlite3OsOpenExclusive();
5571**
5572** These calls correspond to the following combinations of flags:
5573**
5574** ReadWrite() -> (READWRITE | CREATE)
5575** ReadOnly() -> (READONLY)
5576** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5577**
5578** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5579** true, the file was configured to be automatically deleted when the
5580** file handle closed. To achieve the same effect using this new
5581** interface, add the DELETEONCLOSE flag to those specified above for
5582** OpenExclusive().
5583*/
5584static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005585 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5586 const char *zPath, /* Pathname of file to be opened */
5587 sqlite3_file *pFile, /* The file descriptor to be filled in */
5588 int flags, /* Input flags to control the opening */
5589 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005590){
dan08da86a2009-08-21 17:18:03 +00005591 unixFile *p = (unixFile *)pFile;
5592 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005593 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005594 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005595 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005596 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005597 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005598
5599 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5600 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5601 int isCreate = (flags & SQLITE_OPEN_CREATE);
5602 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5603 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005604#if SQLITE_ENABLE_LOCKING_STYLE
5605 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5606#endif
drh3d4435b2011-08-26 20:55:50 +00005607#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5608 struct statfs fsInfo;
5609#endif
danielk1977b4b47412007-08-17 15:53:36 +00005610
danielk1977fee2d252007-08-18 10:59:19 +00005611 /* If creating a master or main-file journal, this function will open
5612 ** a file-descriptor on the directory too. The first time unixSync()
5613 ** is called the directory file descriptor will be fsync()ed and close()d.
5614 */
drh0059eae2011-08-08 23:48:40 +00005615 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005616 eType==SQLITE_OPEN_MASTER_JOURNAL
5617 || eType==SQLITE_OPEN_MAIN_JOURNAL
5618 || eType==SQLITE_OPEN_WAL
5619 ));
danielk1977fee2d252007-08-18 10:59:19 +00005620
danielk197717b90b52008-06-06 11:11:25 +00005621 /* If argument zPath is a NULL pointer, this function is required to open
5622 ** a temporary file. Use this buffer to store the file name in.
5623 */
drhc02a43a2012-01-10 23:18:38 +00005624 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005625 const char *zName = zPath;
5626
danielk1977fee2d252007-08-18 10:59:19 +00005627 /* Check the following statements are true:
5628 **
5629 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5630 ** (b) if CREATE is set, then READWRITE must also be set, and
5631 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005632 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005633 */
danielk1977b4b47412007-08-17 15:53:36 +00005634 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005635 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005636 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005637 assert(isDelete==0 || isCreate);
5638
danddb0ac42010-07-14 14:48:58 +00005639 /* The main DB, main journal, WAL file and master journal are never
5640 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005641 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5642 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5643 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005644 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005645
danielk1977fee2d252007-08-18 10:59:19 +00005646 /* Assert that the upper layer has set one of the "file-type" flags. */
5647 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5648 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5649 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005650 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005651 );
5652
drhb00d8622014-01-01 15:18:36 +00005653 /* Detect a pid change and reset the PRNG. There is a race condition
5654 ** here such that two or more threads all trying to open databases at
5655 ** the same instant might all reset the PRNG. But multiple resets
5656 ** are harmless.
5657 */
drh5ac93652015-03-21 20:59:43 +00005658 if( randomnessPid!=osGetpid(0) ){
5659 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005660 sqlite3_randomness(0,0);
5661 }
5662
dan08da86a2009-08-21 17:18:03 +00005663 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005664
dan08da86a2009-08-21 17:18:03 +00005665 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005666 UnixUnusedFd *pUnused;
5667 pUnused = findReusableFd(zName, flags);
5668 if( pUnused ){
5669 fd = pUnused->fd;
5670 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005671 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005672 if( !pUnused ){
5673 return SQLITE_NOMEM;
5674 }
5675 }
5676 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005677
5678 /* Database filenames are double-zero terminated if they are not
5679 ** URIs with parameters. Hence, they can always be passed into
5680 ** sqlite3_uri_parameter(). */
5681 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5682
dan08da86a2009-08-21 17:18:03 +00005683 }else if( !zName ){
5684 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005685 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005686 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005687 if( rc!=SQLITE_OK ){
5688 return rc;
5689 }
5690 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005691
5692 /* Generated temporary filenames are always double-zero terminated
5693 ** for use by sqlite3_uri_parameter(). */
5694 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005695 }
5696
dan08da86a2009-08-21 17:18:03 +00005697 /* Determine the value of the flags parameter passed to POSIX function
5698 ** open(). These must be calculated even if open() is not called, as
5699 ** they may be stored as part of the file handle and used by the
5700 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005701 if( isReadonly ) openFlags |= O_RDONLY;
5702 if( isReadWrite ) openFlags |= O_RDWR;
5703 if( isCreate ) openFlags |= O_CREAT;
5704 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5705 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005706
danielk1977b4b47412007-08-17 15:53:36 +00005707 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005708 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005709 uid_t uid; /* Userid for the file */
5710 gid_t gid; /* Groupid for the file */
5711 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005712 if( rc!=SQLITE_OK ){
5713 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005714 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005715 return rc;
5716 }
drhad4f1e52011-03-04 15:43:57 +00005717 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005718 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005719 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5720 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005721 /* Failed to open the file for read/write access. Try read-only. */
5722 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005723 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005724 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005725 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005726 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005727 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005728 }
5729 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005730 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005731 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005732 }
drhac7c3ac2012-02-11 19:23:48 +00005733
5734 /* If this process is running as root and if creating a new rollback
5735 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005736 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005737 */
5738 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005739 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005740 }
danielk1977b4b47412007-08-17 15:53:36 +00005741 }
dan08da86a2009-08-21 17:18:03 +00005742 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005743 if( pOutFlags ){
5744 *pOutFlags = flags;
5745 }
5746
dane946c392009-08-22 11:39:46 +00005747 if( p->pUnused ){
5748 p->pUnused->fd = fd;
5749 p->pUnused->flags = flags;
5750 }
5751
danielk1977b4b47412007-08-17 15:53:36 +00005752 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005753#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005754 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005755#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5756 zPath = sqlite3_mprintf("%s", zName);
5757 if( zPath==0 ){
5758 robust_close(p, fd, __LINE__);
5759 return SQLITE_NOMEM;
5760 }
chw97185482008-11-17 08:05:31 +00005761#else
drh036ac7f2011-08-08 23:18:05 +00005762 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005763#endif
danielk1977b4b47412007-08-17 15:53:36 +00005764 }
drh41022642008-11-21 00:24:42 +00005765#if SQLITE_ENABLE_LOCKING_STYLE
5766 else{
dan08da86a2009-08-21 17:18:03 +00005767 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005768 }
5769#endif
5770
drhda0e7682008-07-30 15:27:54 +00005771 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005772
drh7ed97b92010-01-20 13:07:21 +00005773
5774#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005775 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005776 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005777 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005778 return SQLITE_IOERR_ACCESS;
5779 }
5780 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5781 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5782 }
drh4bf66fd2015-02-19 02:43:02 +00005783 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5784 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5785 }
drh7ed97b92010-01-20 13:07:21 +00005786#endif
drhc02a43a2012-01-10 23:18:38 +00005787
5788 /* Set up appropriate ctrlFlags */
5789 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5790 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5791 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5792 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5793 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5794
drh7ed97b92010-01-20 13:07:21 +00005795#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005796#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005797 isAutoProxy = 1;
5798#endif
5799 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005800 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5801 int useProxy = 0;
5802
dan08da86a2009-08-21 17:18:03 +00005803 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5804 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005805 if( envforce!=NULL ){
5806 useProxy = atoi(envforce)>0;
5807 }else{
aswiftaebf4132008-11-21 00:10:35 +00005808 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5809 }
5810 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005811 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005812 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005813 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005814 if( rc!=SQLITE_OK ){
5815 /* Use unixClose to clean up the resources added in fillInUnixFile
5816 ** and clear all the structure's references. Specifically,
5817 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5818 */
5819 unixClose(pFile);
5820 return rc;
5821 }
aswiftaebf4132008-11-21 00:10:35 +00005822 }
dane946c392009-08-22 11:39:46 +00005823 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005824 }
5825 }
5826#endif
5827
drhc02a43a2012-01-10 23:18:38 +00005828 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5829
dane946c392009-08-22 11:39:46 +00005830open_finished:
5831 if( rc!=SQLITE_OK ){
5832 sqlite3_free(p->pUnused);
5833 }
5834 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005835}
5836
dane946c392009-08-22 11:39:46 +00005837
danielk1977b4b47412007-08-17 15:53:36 +00005838/*
danielk1977fee2d252007-08-18 10:59:19 +00005839** Delete the file at zPath. If the dirSync argument is true, fsync()
5840** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005841*/
drh6b9d6dd2008-12-03 19:34:47 +00005842static int unixDelete(
5843 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5844 const char *zPath, /* Name of file to be deleted */
5845 int dirSync /* If true, fsync() directory after deleting file */
5846){
danielk1977fee2d252007-08-18 10:59:19 +00005847 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005848 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005849 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005850 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005851 if( errno==ENOENT
5852#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005853 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005854#endif
5855 ){
dan9fc5b4a2012-11-09 20:17:26 +00005856 rc = SQLITE_IOERR_DELETE_NOENT;
5857 }else{
drhb4308162012-11-09 21:40:02 +00005858 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005859 }
drhb4308162012-11-09 21:40:02 +00005860 return rc;
drh5d4feff2010-07-14 01:45:22 +00005861 }
danielk1977d39fa702008-10-16 13:27:40 +00005862#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005863 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005864 int fd;
drh90315a22011-08-10 01:52:12 +00005865 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005866 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005867#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005868 if( fsync(fd)==-1 )
5869#else
5870 if( fsync(fd) )
5871#endif
5872 {
dane18d4952011-02-21 11:46:24 +00005873 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005874 }
drh0e9365c2011-03-02 02:08:13 +00005875 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005876 }else{
5877 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005878 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005879 }
5880 }
danielk1977d138dd82008-10-15 16:02:48 +00005881#endif
danielk1977fee2d252007-08-18 10:59:19 +00005882 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005883}
5884
danielk197790949c22007-08-17 16:50:38 +00005885/*
mistachkin48864df2013-03-21 21:20:32 +00005886** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005887** test performed depends on the value of flags:
5888**
5889** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5890** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5891** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5892**
5893** Otherwise return 0.
5894*/
danielk1977861f7452008-06-05 11:39:11 +00005895static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005896 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5897 const char *zPath, /* Path of the file to examine */
5898 int flags, /* What do we want to learn about the zPath file? */
5899 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005900){
danielk1977397d65f2008-11-19 11:35:39 +00005901 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005902 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005903 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005904
drhd260b5b2015-11-25 18:03:33 +00005905 /* The spec says there are three possible values for flags. But only
5906 ** two of them are actually used */
5907 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5908
5909 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005910 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005911 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5912 }else{
5913 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005914 }
danielk1977861f7452008-06-05 11:39:11 +00005915 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005916}
5917
danielk1977b4b47412007-08-17 15:53:36 +00005918
5919/*
5920** Turn a relative pathname into a full pathname. The relative path
5921** is stored as a nul-terminated string in the buffer pointed to by
5922** zPath.
5923**
5924** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5925** (in this case, MAX_PATHNAME bytes). The full-path is written to
5926** this buffer before returning.
5927*/
danielk1977adfb9b02007-09-17 07:02:56 +00005928static int unixFullPathname(
5929 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5930 const char *zPath, /* Possibly relative input path */
5931 int nOut, /* Size of output buffer in bytes */
5932 char *zOut /* Output buffer */
5933){
dan245fdc62015-10-31 17:58:33 +00005934 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005935
5936 /* It's odd to simulate an io-error here, but really this is just
5937 ** using the io-error infrastructure to test that SQLite handles this
5938 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005939 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005940 */
5941 SimulateIOError( return SQLITE_ERROR );
5942
drh153c62c2007-08-24 03:51:33 +00005943 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005944 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005945
dan245fdc62015-10-31 17:58:33 +00005946 /* Attempt to resolve the path as if it were a symbolic link. If it is
5947 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5948 ** the identified file is not a symbolic link or does not exist, then
5949 ** zPath is copied directly into zOut. Either way, nByte is left set to
5950 ** the size of the string copied into zOut[] in bytes. */
5951 nByte = osReadlink(zPath, zOut, nOut-1);
5952 if( nByte<0 ){
5953 if( errno!=EINVAL && errno!=ENOENT ){
5954 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5955 }
drhd260b5b2015-11-25 18:03:33 +00005956 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005957 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005958 }else{
dan245fdc62015-10-31 17:58:33 +00005959 zOut[nByte] = '\0';
5960 }
5961
5962 /* If buffer zOut[] now contains an absolute path there is nothing more
5963 ** to do. If it contains a relative path, do the following:
5964 **
5965 ** * move the relative path string so that it is at the end of th
5966 ** zOut[] buffer.
5967 ** * Call getcwd() to read the path of the current working directory
5968 ** into the start of the zOut[] buffer.
5969 ** * Append a '/' character to the cwd string and move the
5970 ** relative path back within the buffer so that it immediately
5971 ** follows the '/'.
5972 **
5973 ** This code is written so that if the combination of the CWD and relative
5974 ** path are larger than the allocated size of zOut[] the CWD is silently
5975 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5976 ** file for which this function returns a full path larger than (nOut-8)
5977 ** bytes in size. */
drh025d2f72015-11-30 22:22:23 +00005978 testcase( nByte==nOut-5 );
5979 testcase( nByte==nOut-4 );
5980 if( zOut[0]!='/' && nByte<nOut-4 ){
danielk1977b4b47412007-08-17 15:53:36 +00005981 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005982 int nRem = nOut-nByte-1;
5983 memmove(&zOut[nRem], zOut, nByte+1);
5984 zOut[nRem-1] = '\0';
5985 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005986 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005987 }
dan245fdc62015-10-31 17:58:33 +00005988 nCwd = sqlite3Strlen30(zOut);
5989 assert( nCwd<=nRem-1 );
5990 zOut[nCwd] = '/';
5991 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00005992 }
dan245fdc62015-10-31 17:58:33 +00005993
danielk1977b4b47412007-08-17 15:53:36 +00005994 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005995}
5996
drh0ccebe72005-06-07 22:22:50 +00005997
drh761df872006-12-21 01:29:22 +00005998#ifndef SQLITE_OMIT_LOAD_EXTENSION
5999/*
6000** Interfaces for opening a shared library, finding entry points
6001** within the shared library, and closing the shared library.
6002*/
6003#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006004static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6005 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006006 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6007}
danielk197795c8a542007-09-01 06:51:27 +00006008
6009/*
6010** SQLite calls this function immediately after a call to unixDlSym() or
6011** unixDlOpen() fails (returns a null pointer). If a more detailed error
6012** message is available, it is written to zBufOut. If no error message
6013** is available, zBufOut is left unmodified and SQLite uses a default
6014** error message.
6015*/
danielk1977397d65f2008-11-19 11:35:39 +00006016static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006017 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006018 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006019 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006020 zErr = dlerror();
6021 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006022 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006023 }
drh6c7d5c52008-11-21 20:32:33 +00006024 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006025}
drh1875f7a2008-12-08 18:19:17 +00006026static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6027 /*
6028 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6029 ** cast into a pointer to a function. And yet the library dlsym() routine
6030 ** returns a void* which is really a pointer to a function. So how do we
6031 ** use dlsym() with -pedantic-errors?
6032 **
6033 ** Variable x below is defined to be a pointer to a function taking
6034 ** parameters void* and const char* and returning a pointer to a function.
6035 ** We initialize x by assigning it a pointer to the dlsym() function.
6036 ** (That assignment requires a cast.) Then we call the function that
6037 ** x points to.
6038 **
6039 ** This work-around is unlikely to work correctly on any system where
6040 ** you really cannot cast a function pointer into void*. But then, on the
6041 ** other hand, dlsym() will not work on such a system either, so we have
6042 ** not really lost anything.
6043 */
6044 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006045 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006046 x = (void(*(*)(void*,const char*))(void))dlsym;
6047 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006048}
danielk1977397d65f2008-11-19 11:35:39 +00006049static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6050 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006051 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006052}
danielk1977b4b47412007-08-17 15:53:36 +00006053#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6054 #define unixDlOpen 0
6055 #define unixDlError 0
6056 #define unixDlSym 0
6057 #define unixDlClose 0
6058#endif
6059
6060/*
danielk197790949c22007-08-17 16:50:38 +00006061** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006062*/
danielk1977397d65f2008-11-19 11:35:39 +00006063static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6064 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006065 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006066
drhbbd42a62004-05-22 17:41:58 +00006067 /* We have to initialize zBuf to prevent valgrind from reporting
6068 ** errors. The reports issued by valgrind are incorrect - we would
6069 ** prefer that the randomness be increased by making use of the
6070 ** uninitialized space in zBuf - but valgrind errors tend to worry
6071 ** some users. Rather than argue, it seems easier just to initialize
6072 ** the whole array and silence valgrind, even if that means less randomness
6073 ** in the random seed.
6074 **
6075 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006076 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006077 ** tests repeatable.
6078 */
danielk1977b4b47412007-08-17 15:53:36 +00006079 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006080 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006081#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006082 {
drhb00d8622014-01-01 15:18:36 +00006083 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006084 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006085 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006086 time_t t;
6087 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006088 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006089 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6090 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6091 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006092 }else{
drhc18b4042012-02-10 03:10:27 +00006093 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006094 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006095 }
drhbbd42a62004-05-22 17:41:58 +00006096 }
6097#endif
drh72cbd072008-10-14 17:58:38 +00006098 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006099}
6100
danielk1977b4b47412007-08-17 15:53:36 +00006101
drhbbd42a62004-05-22 17:41:58 +00006102/*
6103** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006104** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006105** The return value is the number of microseconds of sleep actually
6106** requested from the underlying operating system, a number which
6107** might be greater than or equal to the argument, but not less
6108** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006109*/
danielk1977397d65f2008-11-19 11:35:39 +00006110static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006111#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006112 struct timespec sp;
6113
6114 sp.tv_sec = microseconds / 1000000;
6115 sp.tv_nsec = (microseconds % 1000000) * 1000;
6116 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006117 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006118 return microseconds;
6119#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006120 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006121 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006122 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006123#else
danielk1977b4b47412007-08-17 15:53:36 +00006124 int seconds = (microseconds+999999)/1000000;
6125 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006126 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006127 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006128#endif
drh88f474a2006-01-02 20:00:12 +00006129}
6130
6131/*
drh6b9d6dd2008-12-03 19:34:47 +00006132** The following variable, if set to a non-zero value, is interpreted as
6133** the number of seconds since 1970 and is used to set the result of
6134** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006135*/
6136#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006137int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006138#endif
6139
6140/*
drhb7e8ea22010-05-03 14:32:30 +00006141** Find the current time (in Universal Coordinated Time). Write into *piNow
6142** the current time and date as a Julian Day number times 86_400_000. In
6143** other words, write into *piNow the number of milliseconds since the Julian
6144** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6145** proleptic Gregorian calendar.
6146**
drh31702252011-10-12 23:13:43 +00006147** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6148** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006149*/
6150static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6151 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006152 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006153#if defined(NO_GETTOD)
6154 time_t t;
6155 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006156 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006157#elif OS_VXWORKS
6158 struct timespec sNow;
6159 clock_gettime(CLOCK_REALTIME, &sNow);
6160 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6161#else
6162 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006163 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6164 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006165#endif
6166
6167#ifdef SQLITE_TEST
6168 if( sqlite3_current_time ){
6169 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6170 }
6171#endif
6172 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006173 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006174}
6175
drh5337dac2015-11-25 15:15:03 +00006176#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006177/*
drhbbd42a62004-05-22 17:41:58 +00006178** Find the current time (in Universal Coordinated Time). Write the
6179** current time and date as a Julian Day number into *prNow and
6180** return 0. Return 1 if the time and date cannot be found.
6181*/
danielk1977397d65f2008-11-19 11:35:39 +00006182static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006183 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006184 int rc;
drhff828942010-06-26 21:34:06 +00006185 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006186 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006187 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006188 return rc;
drhbbd42a62004-05-22 17:41:58 +00006189}
drh5337dac2015-11-25 15:15:03 +00006190#else
6191# define unixCurrentTime 0
6192#endif
danielk1977b4b47412007-08-17 15:53:36 +00006193
drh5337dac2015-11-25 15:15:03 +00006194#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006195/*
6196** We added the xGetLastError() method with the intention of providing
6197** better low-level error messages when operating-system problems come up
6198** during SQLite operation. But so far, none of that has been implemented
6199** in the core. So this routine is never called. For now, it is merely
6200** a place-holder.
6201*/
danielk1977397d65f2008-11-19 11:35:39 +00006202static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6203 UNUSED_PARAMETER(NotUsed);
6204 UNUSED_PARAMETER(NotUsed2);
6205 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006206 return 0;
6207}
drh5337dac2015-11-25 15:15:03 +00006208#else
6209# define unixGetLastError 0
6210#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006211
drhf2424c52010-04-26 00:04:55 +00006212
6213/*
drh734c9862008-11-28 15:37:20 +00006214************************ End of sqlite3_vfs methods ***************************
6215******************************************************************************/
6216
drh715ff302008-12-03 22:32:44 +00006217/******************************************************************************
6218************************** Begin Proxy Locking ********************************
6219**
6220** Proxy locking is a "uber-locking-method" in this sense: It uses the
6221** other locking methods on secondary lock files. Proxy locking is a
6222** meta-layer over top of the primitive locking implemented above. For
6223** this reason, the division that implements of proxy locking is deferred
6224** until late in the file (here) after all of the other I/O methods have
6225** been defined - so that the primitive locking methods are available
6226** as services to help with the implementation of proxy locking.
6227**
6228****
6229**
6230** The default locking schemes in SQLite use byte-range locks on the
6231** database file to coordinate safe, concurrent access by multiple readers
6232** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6233** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6234** as POSIX read & write locks over fixed set of locations (via fsctl),
6235** on AFP and SMB only exclusive byte-range locks are available via fsctl
6236** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6237** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6238** address in the shared range is taken for a SHARED lock, the entire
6239** shared range is taken for an EXCLUSIVE lock):
6240**
drhf2f105d2012-08-20 15:53:54 +00006241** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006242** RESERVED_BYTE 0x40000001
6243** SHARED_RANGE 0x40000002 -> 0x40000200
6244**
6245** This works well on the local file system, but shows a nearly 100x
6246** slowdown in read performance on AFP because the AFP client disables
6247** the read cache when byte-range locks are present. Enabling the read
6248** cache exposes a cache coherency problem that is present on all OS X
6249** supported network file systems. NFS and AFP both observe the
6250** close-to-open semantics for ensuring cache coherency
6251** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6252** address the requirements for concurrent database access by multiple
6253** readers and writers
6254** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6255**
6256** To address the performance and cache coherency issues, proxy file locking
6257** changes the way database access is controlled by limiting access to a
6258** single host at a time and moving file locks off of the database file
6259** and onto a proxy file on the local file system.
6260**
6261**
6262** Using proxy locks
6263** -----------------
6264**
6265** C APIs
6266**
drh4bf66fd2015-02-19 02:43:02 +00006267** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006268** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006269** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6270** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006271**
6272**
6273** SQL pragmas
6274**
6275** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6276** PRAGMA [database.]lock_proxy_file
6277**
6278** Specifying ":auto:" means that if there is a conch file with a matching
6279** host ID in it, the proxy path in the conch file will be used, otherwise
6280** a proxy path based on the user's temp dir
6281** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6282** actual proxy file name is generated from the name and path of the
6283** database file. For example:
6284**
6285** For database path "/Users/me/foo.db"
6286** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6287**
6288** Once a lock proxy is configured for a database connection, it can not
6289** be removed, however it may be switched to a different proxy path via
6290** the above APIs (assuming the conch file is not being held by another
6291** connection or process).
6292**
6293**
6294** How proxy locking works
6295** -----------------------
6296**
6297** Proxy file locking relies primarily on two new supporting files:
6298**
6299** * conch file to limit access to the database file to a single host
6300** at a time
6301**
6302** * proxy file to act as a proxy for the advisory locks normally
6303** taken on the database
6304**
6305** The conch file - to use a proxy file, sqlite must first "hold the conch"
6306** by taking an sqlite-style shared lock on the conch file, reading the
6307** contents and comparing the host's unique host ID (see below) and lock
6308** proxy path against the values stored in the conch. The conch file is
6309** stored in the same directory as the database file and the file name
6310** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006311** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006312** host ID and/or proxy path, then the lock is escalated to an exclusive
6313** lock and the conch file contents is updated with the host ID and proxy
6314** path and the lock is downgraded to a shared lock again. If the conch
6315** is held by another process (with a shared lock), the exclusive lock
6316** will fail and SQLITE_BUSY is returned.
6317**
6318** The proxy file - a single-byte file used for all advisory file locks
6319** normally taken on the database file. This allows for safe sharing
6320** of the database file for multiple readers and writers on the same
6321** host (the conch ensures that they all use the same local lock file).
6322**
drh715ff302008-12-03 22:32:44 +00006323** Requesting the lock proxy does not immediately take the conch, it is
6324** only taken when the first request to lock database file is made.
6325** This matches the semantics of the traditional locking behavior, where
6326** opening a connection to a database file does not take a lock on it.
6327** The shared lock and an open file descriptor are maintained until
6328** the connection to the database is closed.
6329**
6330** The proxy file and the lock file are never deleted so they only need
6331** to be created the first time they are used.
6332**
6333** Configuration options
6334** ---------------------
6335**
6336** SQLITE_PREFER_PROXY_LOCKING
6337**
6338** Database files accessed on non-local file systems are
6339** automatically configured for proxy locking, lock files are
6340** named automatically using the same logic as
6341** PRAGMA lock_proxy_file=":auto:"
6342**
6343** SQLITE_PROXY_DEBUG
6344**
6345** Enables the logging of error messages during host id file
6346** retrieval and creation
6347**
drh715ff302008-12-03 22:32:44 +00006348** LOCKPROXYDIR
6349**
6350** Overrides the default directory used for lock proxy files that
6351** are named automatically via the ":auto:" setting
6352**
6353** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6354**
6355** Permissions to use when creating a directory for storing the
6356** lock proxy files, only used when LOCKPROXYDIR is not set.
6357**
6358**
6359** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6360** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6361** force proxy locking to be used for every database file opened, and 0
6362** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006363** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006364** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6365*/
6366
6367/*
6368** Proxy locking is only available on MacOSX
6369*/
drhd2cb50b2009-01-09 21:41:17 +00006370#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006371
drh715ff302008-12-03 22:32:44 +00006372/*
6373** The proxyLockingContext has the path and file structures for the remote
6374** and local proxy files in it
6375*/
6376typedef struct proxyLockingContext proxyLockingContext;
6377struct proxyLockingContext {
6378 unixFile *conchFile; /* Open conch file */
6379 char *conchFilePath; /* Name of the conch file */
6380 unixFile *lockProxy; /* Open proxy lock file */
6381 char *lockProxyPath; /* Name of the proxy lock file */
6382 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006383 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006384 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006385 void *oldLockingContext; /* Original lockingcontext to restore on close */
6386 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6387};
6388
drh7ed97b92010-01-20 13:07:21 +00006389/*
6390** The proxy lock file path for the database at dbPath is written into lPath,
6391** which must point to valid, writable memory large enough for a maxLen length
6392** file path.
drh715ff302008-12-03 22:32:44 +00006393*/
drh715ff302008-12-03 22:32:44 +00006394static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6395 int len;
6396 int dbLen;
6397 int i;
6398
6399#ifdef LOCKPROXYDIR
6400 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6401#else
6402# ifdef _CS_DARWIN_USER_TEMP_DIR
6403 {
drh7ed97b92010-01-20 13:07:21 +00006404 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006405 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006406 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006407 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006408 }
drh7ed97b92010-01-20 13:07:21 +00006409 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006410 }
6411# else
6412 len = strlcpy(lPath, "/tmp/", maxLen);
6413# endif
6414#endif
6415
6416 if( lPath[len-1]!='/' ){
6417 len = strlcat(lPath, "/", maxLen);
6418 }
6419
6420 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006421 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006422 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006423 char c = dbPath[i];
6424 lPath[i+len] = (c=='/')?'_':c;
6425 }
6426 lPath[i+len]='\0';
6427 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006428 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006429 return SQLITE_OK;
6430}
6431
drh7ed97b92010-01-20 13:07:21 +00006432/*
6433 ** Creates the lock file and any missing directories in lockPath
6434 */
6435static int proxyCreateLockPath(const char *lockPath){
6436 int i, len;
6437 char buf[MAXPATHLEN];
6438 int start = 0;
6439
6440 assert(lockPath!=NULL);
6441 /* try to create all the intermediate directories */
6442 len = (int)strlen(lockPath);
6443 buf[0] = lockPath[0];
6444 for( i=1; i<len; i++ ){
6445 if( lockPath[i] == '/' && (i - start > 0) ){
6446 /* only mkdir if leaf dir != "." or "/" or ".." */
6447 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6448 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6449 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006450 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006451 int err=errno;
6452 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006453 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006454 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006455 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006456 return err;
6457 }
6458 }
6459 }
6460 start=i+1;
6461 }
6462 buf[i] = lockPath[i];
6463 }
drh62aaa6c2015-11-21 17:27:42 +00006464 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006465 return 0;
6466}
6467
drh715ff302008-12-03 22:32:44 +00006468/*
6469** Create a new VFS file descriptor (stored in memory obtained from
6470** sqlite3_malloc) and open the file named "path" in the file descriptor.
6471**
6472** The caller is responsible not only for closing the file descriptor
6473** but also for freeing the memory associated with the file descriptor.
6474*/
drh7ed97b92010-01-20 13:07:21 +00006475static int proxyCreateUnixFile(
6476 const char *path, /* path for the new unixFile */
6477 unixFile **ppFile, /* unixFile created and returned by ref */
6478 int islockfile /* if non zero missing dirs will be created */
6479) {
6480 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006481 unixFile *pNew;
6482 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006483 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006484 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006485 int terrno = 0;
6486 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006487
drh7ed97b92010-01-20 13:07:21 +00006488 /* 1. first try to open/create the file
6489 ** 2. if that fails, and this is a lock file (not-conch), try creating
6490 ** the parent directories and then try again.
6491 ** 3. if that fails, try to open the file read-only
6492 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6493 */
6494 pUnused = findReusableFd(path, openFlags);
6495 if( pUnused ){
6496 fd = pUnused->fd;
6497 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006498 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006499 if( !pUnused ){
6500 return SQLITE_NOMEM;
6501 }
6502 }
6503 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006504 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006505 terrno = errno;
6506 if( fd<0 && errno==ENOENT && islockfile ){
6507 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006508 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006509 }
6510 }
6511 }
6512 if( fd<0 ){
6513 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006514 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006515 terrno = errno;
6516 }
6517 if( fd<0 ){
6518 if( islockfile ){
6519 return SQLITE_BUSY;
6520 }
6521 switch (terrno) {
6522 case EACCES:
6523 return SQLITE_PERM;
6524 case EIO:
6525 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6526 default:
drh9978c972010-02-23 17:36:32 +00006527 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006528 }
6529 }
6530
drhf3cdcdc2015-04-29 16:50:28 +00006531 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006532 if( pNew==NULL ){
6533 rc = SQLITE_NOMEM;
6534 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006535 }
6536 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006537 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006538 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006539 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006540 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006541 pUnused->fd = fd;
6542 pUnused->flags = openFlags;
6543 pNew->pUnused = pUnused;
6544
drhc02a43a2012-01-10 23:18:38 +00006545 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006546 if( rc==SQLITE_OK ){
6547 *ppFile = pNew;
6548 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006549 }
drh7ed97b92010-01-20 13:07:21 +00006550end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006551 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006552 sqlite3_free(pNew);
6553 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006554 return rc;
6555}
6556
drh7ed97b92010-01-20 13:07:21 +00006557#ifdef SQLITE_TEST
6558/* simulate multiple hosts by creating unique hostid file paths */
6559int sqlite3_hostid_num = 0;
6560#endif
6561
6562#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6563
drh6bca6512015-04-13 23:05:28 +00006564#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006565/* Not always defined in the headers as it ought to be */
6566extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006567#endif
drh0ab216a2010-07-02 17:10:40 +00006568
drh7ed97b92010-01-20 13:07:21 +00006569/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6570** bytes of writable memory.
6571*/
6572static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006573 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6574 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006575#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006576 {
drh4bf66fd2015-02-19 02:43:02 +00006577 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006578 if( gethostuuid(pHostID, &timeout) ){
6579 int err = errno;
6580 if( pError ){
6581 *pError = err;
6582 }
6583 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006584 }
drh7ed97b92010-01-20 13:07:21 +00006585 }
drh3d4435b2011-08-26 20:55:50 +00006586#else
6587 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006588#endif
drh7ed97b92010-01-20 13:07:21 +00006589#ifdef SQLITE_TEST
6590 /* simulate multiple hosts by creating unique hostid file paths */
6591 if( sqlite3_hostid_num != 0){
6592 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6593 }
6594#endif
6595
6596 return SQLITE_OK;
6597}
6598
6599/* The conch file contains the header, host id and lock file path
6600 */
6601#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6602#define PROXY_HEADERLEN 1 /* conch file header length */
6603#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6604#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6605
6606/*
6607** Takes an open conch file, copies the contents to a new path and then moves
6608** it back. The newly created file's file descriptor is assigned to the
6609** conch file structure and finally the original conch file descriptor is
6610** closed. Returns zero if successful.
6611*/
6612static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6613 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6614 unixFile *conchFile = pCtx->conchFile;
6615 char tPath[MAXPATHLEN];
6616 char buf[PROXY_MAXCONCHLEN];
6617 char *cPath = pCtx->conchFilePath;
6618 size_t readLen = 0;
6619 size_t pathLen = 0;
6620 char errmsg[64] = "";
6621 int fd = -1;
6622 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006623 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006624
6625 /* create a new path by replace the trailing '-conch' with '-break' */
6626 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6627 if( pathLen>MAXPATHLEN || pathLen<6 ||
6628 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006629 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006630 goto end_breaklock;
6631 }
6632 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006633 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006634 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006635 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006636 goto end_breaklock;
6637 }
6638 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006639 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006640 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006641 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006642 goto end_breaklock;
6643 }
drhe562be52011-03-02 18:01:10 +00006644 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006645 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006646 goto end_breaklock;
6647 }
6648 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006649 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006650 goto end_breaklock;
6651 }
6652 rc = 0;
6653 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006654 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006655 conchFile->h = fd;
6656 conchFile->openFlags = O_RDWR | O_CREAT;
6657
6658end_breaklock:
6659 if( rc ){
6660 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006661 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006662 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006663 }
6664 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6665 }
6666 return rc;
6667}
6668
6669/* Take the requested lock on the conch file and break a stale lock if the
6670** host id matches.
6671*/
6672static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6673 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6674 unixFile *conchFile = pCtx->conchFile;
6675 int rc = SQLITE_OK;
6676 int nTries = 0;
6677 struct timespec conchModTime;
6678
drh3d4435b2011-08-26 20:55:50 +00006679 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006680 do {
6681 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6682 nTries ++;
6683 if( rc==SQLITE_BUSY ){
6684 /* If the lock failed (busy):
6685 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6686 * 2nd try: fail if the mod time changed or host id is different, wait
6687 * 10 sec and try again
6688 * 3rd try: break the lock unless the mod time has changed.
6689 */
6690 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006691 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006692 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006693 return SQLITE_IOERR_LOCK;
6694 }
6695
6696 if( nTries==1 ){
6697 conchModTime = buf.st_mtimespec;
6698 usleep(500000); /* wait 0.5 sec and try the lock again*/
6699 continue;
6700 }
6701
6702 assert( nTries>1 );
6703 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6704 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6705 return SQLITE_BUSY;
6706 }
6707
6708 if( nTries==2 ){
6709 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006710 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006711 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006712 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006713 return SQLITE_IOERR_LOCK;
6714 }
6715 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6716 /* don't break the lock if the host id doesn't match */
6717 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6718 return SQLITE_BUSY;
6719 }
6720 }else{
6721 /* don't break the lock on short read or a version mismatch */
6722 return SQLITE_BUSY;
6723 }
6724 usleep(10000000); /* wait 10 sec and try the lock again */
6725 continue;
6726 }
6727
6728 assert( nTries==3 );
6729 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6730 rc = SQLITE_OK;
6731 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006732 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006733 }
6734 if( !rc ){
6735 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6736 }
6737 }
6738 }
6739 } while( rc==SQLITE_BUSY && nTries<3 );
6740
6741 return rc;
6742}
6743
6744/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006745** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6746** lockPath means that the lockPath in the conch file will be used if the
6747** host IDs match, or a new lock path will be generated automatically
6748** and written to the conch file.
6749*/
6750static int proxyTakeConch(unixFile *pFile){
6751 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6752
drh7ed97b92010-01-20 13:07:21 +00006753 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006754 return SQLITE_OK;
6755 }else{
6756 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006757 uuid_t myHostID;
6758 int pError = 0;
6759 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006760 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006761 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006762 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006763 int createConch = 0;
6764 int hostIdMatch = 0;
6765 int readLen = 0;
6766 int tryOldLockPath = 0;
6767 int forceNewLockPath = 0;
6768
drh308c2a52010-05-14 11:30:18 +00006769 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006770 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006771 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006772
drh7ed97b92010-01-20 13:07:21 +00006773 rc = proxyGetHostID(myHostID, &pError);
6774 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006775 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006776 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006777 }
drh7ed97b92010-01-20 13:07:21 +00006778 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006779 if( rc!=SQLITE_OK ){
6780 goto end_takeconch;
6781 }
drh7ed97b92010-01-20 13:07:21 +00006782 /* read the existing conch file */
6783 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6784 if( readLen<0 ){
6785 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006786 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006787 rc = SQLITE_IOERR_READ;
6788 goto end_takeconch;
6789 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6790 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6791 /* a short read or version format mismatch means we need to create a new
6792 ** conch file.
6793 */
6794 createConch = 1;
6795 }
6796 /* if the host id matches and the lock path already exists in the conch
6797 ** we'll try to use the path there, if we can't open that path, we'll
6798 ** retry with a new auto-generated path
6799 */
6800 do { /* in case we need to try again for an :auto: named lock file */
6801
6802 if( !createConch && !forceNewLockPath ){
6803 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6804 PROXY_HOSTIDLEN);
6805 /* if the conch has data compare the contents */
6806 if( !pCtx->lockProxyPath ){
6807 /* for auto-named local lock file, just check the host ID and we'll
6808 ** use the local lock file path that's already in there
6809 */
6810 if( hostIdMatch ){
6811 size_t pathLen = (readLen - PROXY_PATHINDEX);
6812
6813 if( pathLen>=MAXPATHLEN ){
6814 pathLen=MAXPATHLEN-1;
6815 }
6816 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6817 lockPath[pathLen] = 0;
6818 tempLockPath = lockPath;
6819 tryOldLockPath = 1;
6820 /* create a copy of the lock path if the conch is taken */
6821 goto end_takeconch;
6822 }
6823 }else if( hostIdMatch
6824 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6825 readLen-PROXY_PATHINDEX)
6826 ){
6827 /* conch host and lock path match */
6828 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006829 }
drh7ed97b92010-01-20 13:07:21 +00006830 }
6831
6832 /* if the conch isn't writable and doesn't match, we can't take it */
6833 if( (conchFile->openFlags&O_RDWR) == 0 ){
6834 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006835 goto end_takeconch;
6836 }
drh7ed97b92010-01-20 13:07:21 +00006837
6838 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006839 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006840 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6841 tempLockPath = lockPath;
6842 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006843 }
drh7ed97b92010-01-20 13:07:21 +00006844
6845 /* update conch with host and path (this will fail if other process
6846 ** has a shared lock already), if the host id matches, use the big
6847 ** stick.
drh715ff302008-12-03 22:32:44 +00006848 */
drh7ed97b92010-01-20 13:07:21 +00006849 futimes(conchFile->h, NULL);
6850 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006851 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006852 /* We are trying for an exclusive lock but another thread in this
6853 ** same process is still holding a shared lock. */
6854 rc = SQLITE_BUSY;
6855 } else {
6856 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006857 }
drh715ff302008-12-03 22:32:44 +00006858 }else{
drh4bf66fd2015-02-19 02:43:02 +00006859 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006860 }
drh7ed97b92010-01-20 13:07:21 +00006861 if( rc==SQLITE_OK ){
6862 char writeBuffer[PROXY_MAXCONCHLEN];
6863 int writeSize = 0;
6864
6865 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6866 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6867 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006868 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6869 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006870 }else{
6871 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6872 }
6873 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006874 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006875 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6876 fsync(conchFile->h);
6877 /* If we created a new conch file (not just updated the contents of a
6878 ** valid conch file), try to match the permissions of the database
6879 */
6880 if( rc==SQLITE_OK && createConch ){
6881 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006882 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006883 if( err==0 ){
6884 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6885 S_IROTH|S_IWOTH);
6886 /* try to match the database file R/W permissions, ignore failure */
6887#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006888 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006889#else
drhff812312011-02-23 13:33:46 +00006890 do{
drhe562be52011-03-02 18:01:10 +00006891 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006892 }while( rc==(-1) && errno==EINTR );
6893 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006894 int code = errno;
6895 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6896 cmode, code, strerror(code));
6897 } else {
6898 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6899 }
6900 }else{
6901 int code = errno;
6902 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6903 err, code, strerror(code));
6904#endif
6905 }
drh715ff302008-12-03 22:32:44 +00006906 }
6907 }
drh7ed97b92010-01-20 13:07:21 +00006908 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6909
6910 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006911 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006912 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006913 int fd;
drh7ed97b92010-01-20 13:07:21 +00006914 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006915 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006916 }
6917 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006918 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006919 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006920 if( fd>=0 ){
6921 pFile->h = fd;
6922 }else{
drh9978c972010-02-23 17:36:32 +00006923 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006924 during locking */
6925 }
6926 }
6927 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6928 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6929 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6930 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6931 /* we couldn't create the proxy lock file with the old lock file path
6932 ** so try again via auto-naming
6933 */
6934 forceNewLockPath = 1;
6935 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006936 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006937 }
6938 }
6939 if( rc==SQLITE_OK ){
6940 /* Need to make a copy of path if we extracted the value
6941 ** from the conch file or the path was allocated on the stack
6942 */
6943 if( tempLockPath ){
6944 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6945 if( !pCtx->lockProxyPath ){
6946 rc = SQLITE_NOMEM;
6947 }
6948 }
6949 }
6950 if( rc==SQLITE_OK ){
6951 pCtx->conchHeld = 1;
6952
6953 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6954 afpLockingContext *afpCtx;
6955 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6956 afpCtx->dbPath = pCtx->lockProxyPath;
6957 }
6958 } else {
6959 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6960 }
drh308c2a52010-05-14 11:30:18 +00006961 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6962 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006963 return rc;
drh308c2a52010-05-14 11:30:18 +00006964 } while (1); /* in case we need to retry the :auto: lock file -
6965 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006966 }
6967}
6968
6969/*
6970** If pFile holds a lock on a conch file, then release that lock.
6971*/
6972static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006973 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006974 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6975 unixFile *conchFile; /* Name of the conch file */
6976
6977 pCtx = (proxyLockingContext *)pFile->lockingContext;
6978 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006979 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006980 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006981 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006982 if( pCtx->conchHeld>0 ){
6983 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6984 }
drh715ff302008-12-03 22:32:44 +00006985 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006986 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6987 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006988 return rc;
6989}
6990
6991/*
6992** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00006993** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00006994** Make *pConchPath point to the new name. Return SQLITE_OK on success
6995** or SQLITE_NOMEM if unable to obtain memory.
6996**
6997** The caller is responsible for ensuring that the allocated memory
6998** space is eventually freed.
6999**
7000** *pConchPath is set to NULL if a memory allocation error occurs.
7001*/
7002static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7003 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007004 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007005 char *conchPath; /* buffer in which to construct conch name */
7006
7007 /* Allocate space for the conch filename and initialize the name to
7008 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007009 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007010 if( conchPath==0 ){
7011 return SQLITE_NOMEM;
7012 }
7013 memcpy(conchPath, dbPath, len+1);
7014
7015 /* now insert a "." before the last / character */
7016 for( i=(len-1); i>=0; i-- ){
7017 if( conchPath[i]=='/' ){
7018 i++;
7019 break;
7020 }
7021 }
7022 conchPath[i]='.';
7023 while ( i<len ){
7024 conchPath[i+1]=dbPath[i];
7025 i++;
7026 }
7027
7028 /* append the "-conch" suffix to the file */
7029 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007030 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007031
7032 return SQLITE_OK;
7033}
7034
7035
7036/* Takes a fully configured proxy locking-style unix file and switches
7037** the local lock file path
7038*/
7039static int switchLockProxyPath(unixFile *pFile, const char *path) {
7040 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7041 char *oldPath = pCtx->lockProxyPath;
7042 int rc = SQLITE_OK;
7043
drh308c2a52010-05-14 11:30:18 +00007044 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007045 return SQLITE_BUSY;
7046 }
7047
7048 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7049 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7050 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7051 return SQLITE_OK;
7052 }else{
7053 unixFile *lockProxy = pCtx->lockProxy;
7054 pCtx->lockProxy=NULL;
7055 pCtx->conchHeld = 0;
7056 if( lockProxy!=NULL ){
7057 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7058 if( rc ) return rc;
7059 sqlite3_free(lockProxy);
7060 }
7061 sqlite3_free(oldPath);
7062 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7063 }
7064
7065 return rc;
7066}
7067
7068/*
7069** pFile is a file that has been opened by a prior xOpen call. dbPath
7070** is a string buffer at least MAXPATHLEN+1 characters in size.
7071**
7072** This routine find the filename associated with pFile and writes it
7073** int dbPath.
7074*/
7075static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007076#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007077 if( pFile->pMethod == &afpIoMethods ){
7078 /* afp style keeps a reference to the db path in the filePath field
7079 ** of the struct */
drhea678832008-12-10 19:26:22 +00007080 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007081 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7082 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007083 } else
drh715ff302008-12-03 22:32:44 +00007084#endif
7085 if( pFile->pMethod == &dotlockIoMethods ){
7086 /* dot lock style uses the locking context to store the dot lock
7087 ** file path */
7088 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7089 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7090 }else{
7091 /* all other styles use the locking context to store the db file path */
7092 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007093 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007094 }
7095 return SQLITE_OK;
7096}
7097
7098/*
7099** Takes an already filled in unix file and alters it so all file locking
7100** will be performed on the local proxy lock file. The following fields
7101** are preserved in the locking context so that they can be restored and
7102** the unix structure properly cleaned up at close time:
7103** ->lockingContext
7104** ->pMethod
7105*/
7106static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7107 proxyLockingContext *pCtx;
7108 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7109 char *lockPath=NULL;
7110 int rc = SQLITE_OK;
7111
drh308c2a52010-05-14 11:30:18 +00007112 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007113 return SQLITE_BUSY;
7114 }
7115 proxyGetDbPathForUnixFile(pFile, dbPath);
7116 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7117 lockPath=NULL;
7118 }else{
7119 lockPath=(char *)path;
7120 }
7121
drh308c2a52010-05-14 11:30:18 +00007122 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007123 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007124
drhf3cdcdc2015-04-29 16:50:28 +00007125 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007126 if( pCtx==0 ){
7127 return SQLITE_NOMEM;
7128 }
7129 memset(pCtx, 0, sizeof(*pCtx));
7130
7131 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7132 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007133 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7134 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7135 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7136 ** (c) the file system is read-only, then enable no-locking access.
7137 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7138 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7139 */
7140 struct statfs fsInfo;
7141 struct stat conchInfo;
7142 int goLockless = 0;
7143
drh99ab3b12011-03-02 15:09:07 +00007144 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007145 int err = errno;
7146 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7147 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7148 }
7149 }
7150 if( goLockless ){
7151 pCtx->conchHeld = -1; /* read only FS/ lockless */
7152 rc = SQLITE_OK;
7153 }
7154 }
drh715ff302008-12-03 22:32:44 +00007155 }
7156 if( rc==SQLITE_OK && lockPath ){
7157 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7158 }
7159
7160 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007161 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7162 if( pCtx->dbPath==NULL ){
7163 rc = SQLITE_NOMEM;
7164 }
7165 }
7166 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007167 /* all memory is allocated, proxys are created and assigned,
7168 ** switch the locking context and pMethod then return.
7169 */
drh715ff302008-12-03 22:32:44 +00007170 pCtx->oldLockingContext = pFile->lockingContext;
7171 pFile->lockingContext = pCtx;
7172 pCtx->pOldMethod = pFile->pMethod;
7173 pFile->pMethod = &proxyIoMethods;
7174 }else{
7175 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007176 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007177 sqlite3_free(pCtx->conchFile);
7178 }
drhd56b1212010-08-11 06:14:15 +00007179 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007180 sqlite3_free(pCtx->conchFilePath);
7181 sqlite3_free(pCtx);
7182 }
drh308c2a52010-05-14 11:30:18 +00007183 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7184 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007185 return rc;
7186}
7187
7188
7189/*
7190** This routine handles sqlite3_file_control() calls that are specific
7191** to proxy locking.
7192*/
7193static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7194 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007195 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007196 unixFile *pFile = (unixFile*)id;
7197 if( pFile->pMethod == &proxyIoMethods ){
7198 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7199 proxyTakeConch(pFile);
7200 if( pCtx->lockProxyPath ){
7201 *(const char **)pArg = pCtx->lockProxyPath;
7202 }else{
7203 *(const char **)pArg = ":auto: (not held)";
7204 }
7205 } else {
7206 *(const char **)pArg = NULL;
7207 }
7208 return SQLITE_OK;
7209 }
drh4bf66fd2015-02-19 02:43:02 +00007210 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007211 unixFile *pFile = (unixFile*)id;
7212 int rc = SQLITE_OK;
7213 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7214 if( pArg==NULL || (const char *)pArg==0 ){
7215 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007216 /* turn off proxy locking - not supported. If support is added for
7217 ** switching proxy locking mode off then it will need to fail if
7218 ** the journal mode is WAL mode.
7219 */
drh715ff302008-12-03 22:32:44 +00007220 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7221 }else{
7222 /* turn off proxy locking - already off - NOOP */
7223 rc = SQLITE_OK;
7224 }
7225 }else{
7226 const char *proxyPath = (const char *)pArg;
7227 if( isProxyStyle ){
7228 proxyLockingContext *pCtx =
7229 (proxyLockingContext*)pFile->lockingContext;
7230 if( !strcmp(pArg, ":auto:")
7231 || (pCtx->lockProxyPath &&
7232 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7233 ){
7234 rc = SQLITE_OK;
7235 }else{
7236 rc = switchLockProxyPath(pFile, proxyPath);
7237 }
7238 }else{
7239 /* turn on proxy file locking */
7240 rc = proxyTransformUnixFile(pFile, proxyPath);
7241 }
7242 }
7243 return rc;
7244 }
7245 default: {
7246 assert( 0 ); /* The call assures that only valid opcodes are sent */
7247 }
7248 }
7249 /*NOTREACHED*/
7250 return SQLITE_ERROR;
7251}
7252
7253/*
7254** Within this division (the proxying locking implementation) the procedures
7255** above this point are all utilities. The lock-related methods of the
7256** proxy-locking sqlite3_io_method object follow.
7257*/
7258
7259
7260/*
7261** This routine checks if there is a RESERVED lock held on the specified
7262** file by this or any other process. If such a lock is held, set *pResOut
7263** to a non-zero value otherwise *pResOut is set to zero. The return value
7264** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7265*/
7266static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7267 unixFile *pFile = (unixFile*)id;
7268 int rc = proxyTakeConch(pFile);
7269 if( rc==SQLITE_OK ){
7270 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007271 if( pCtx->conchHeld>0 ){
7272 unixFile *proxy = pCtx->lockProxy;
7273 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7274 }else{ /* conchHeld < 0 is lockless */
7275 pResOut=0;
7276 }
drh715ff302008-12-03 22:32:44 +00007277 }
7278 return rc;
7279}
7280
7281/*
drh308c2a52010-05-14 11:30:18 +00007282** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007283** of the following:
7284**
7285** (1) SHARED_LOCK
7286** (2) RESERVED_LOCK
7287** (3) PENDING_LOCK
7288** (4) EXCLUSIVE_LOCK
7289**
7290** Sometimes when requesting one lock state, additional lock states
7291** are inserted in between. The locking might fail on one of the later
7292** transitions leaving the lock state different from what it started but
7293** still short of its goal. The following chart shows the allowed
7294** transitions and the inserted intermediate states:
7295**
7296** UNLOCKED -> SHARED
7297** SHARED -> RESERVED
7298** SHARED -> (PENDING) -> EXCLUSIVE
7299** RESERVED -> (PENDING) -> EXCLUSIVE
7300** PENDING -> EXCLUSIVE
7301**
7302** This routine will only increase a lock. Use the sqlite3OsUnlock()
7303** routine to lower a locking level.
7304*/
drh308c2a52010-05-14 11:30:18 +00007305static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007306 unixFile *pFile = (unixFile*)id;
7307 int rc = proxyTakeConch(pFile);
7308 if( rc==SQLITE_OK ){
7309 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007310 if( pCtx->conchHeld>0 ){
7311 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007312 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7313 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007314 }else{
7315 /* conchHeld < 0 is lockless */
7316 }
drh715ff302008-12-03 22:32:44 +00007317 }
7318 return rc;
7319}
7320
7321
7322/*
drh308c2a52010-05-14 11:30:18 +00007323** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007324** must be either NO_LOCK or SHARED_LOCK.
7325**
7326** If the locking level of the file descriptor is already at or below
7327** the requested locking level, this routine is a no-op.
7328*/
drh308c2a52010-05-14 11:30:18 +00007329static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007330 unixFile *pFile = (unixFile*)id;
7331 int rc = proxyTakeConch(pFile);
7332 if( rc==SQLITE_OK ){
7333 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007334 if( pCtx->conchHeld>0 ){
7335 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007336 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7337 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007338 }else{
7339 /* conchHeld < 0 is lockless */
7340 }
drh715ff302008-12-03 22:32:44 +00007341 }
7342 return rc;
7343}
7344
7345/*
7346** Close a file that uses proxy locks.
7347*/
7348static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007349 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007350 unixFile *pFile = (unixFile*)id;
7351 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7352 unixFile *lockProxy = pCtx->lockProxy;
7353 unixFile *conchFile = pCtx->conchFile;
7354 int rc = SQLITE_OK;
7355
7356 if( lockProxy ){
7357 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7358 if( rc ) return rc;
7359 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7360 if( rc ) return rc;
7361 sqlite3_free(lockProxy);
7362 pCtx->lockProxy = 0;
7363 }
7364 if( conchFile ){
7365 if( pCtx->conchHeld ){
7366 rc = proxyReleaseConch(pFile);
7367 if( rc ) return rc;
7368 }
7369 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7370 if( rc ) return rc;
7371 sqlite3_free(conchFile);
7372 }
drhd56b1212010-08-11 06:14:15 +00007373 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007374 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007375 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007376 /* restore the original locking context and pMethod then close it */
7377 pFile->lockingContext = pCtx->oldLockingContext;
7378 pFile->pMethod = pCtx->pOldMethod;
7379 sqlite3_free(pCtx);
7380 return pFile->pMethod->xClose(id);
7381 }
7382 return SQLITE_OK;
7383}
7384
7385
7386
drhd2cb50b2009-01-09 21:41:17 +00007387#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007388/*
7389** The proxy locking style is intended for use with AFP filesystems.
7390** And since AFP is only supported on MacOSX, the proxy locking is also
7391** restricted to MacOSX.
7392**
7393**
7394******************* End of the proxy lock implementation **********************
7395******************************************************************************/
7396
drh734c9862008-11-28 15:37:20 +00007397/*
danielk1977e339d652008-06-28 11:23:00 +00007398** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007399**
7400** This routine registers all VFS implementations for unix-like operating
7401** systems. This routine, and the sqlite3_os_end() routine that follows,
7402** should be the only routines in this file that are visible from other
7403** files.
drh6b9d6dd2008-12-03 19:34:47 +00007404**
7405** This routine is called once during SQLite initialization and by a
7406** single thread. The memory allocation and mutex subsystems have not
7407** necessarily been initialized when this routine is called, and so they
7408** should not be used.
drh153c62c2007-08-24 03:51:33 +00007409*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007410int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007411 /*
7412 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007413 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7414 ** to the "finder" function. (pAppData is a pointer to a pointer because
7415 ** silly C90 rules prohibit a void* from being cast to a function pointer
7416 ** and so we have to go through the intermediate pointer to avoid problems
7417 ** when compiling with -pedantic-errors on GCC.)
7418 **
7419 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007420 ** finder-function. The finder-function returns a pointer to the
7421 ** sqlite_io_methods object that implements the desired locking
7422 ** behaviors. See the division above that contains the IOMETHODS
7423 ** macro for addition information on finder-functions.
7424 **
7425 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7426 ** object. But the "autolockIoFinder" available on MacOSX does a little
7427 ** more than that; it looks at the filesystem type that hosts the
7428 ** database file and tries to choose an locking method appropriate for
7429 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007430 */
drh7708e972008-11-29 00:56:52 +00007431 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007432 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007433 sizeof(unixFile), /* szOsFile */ \
7434 MAX_PATHNAME, /* mxPathname */ \
7435 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007436 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007437 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007438 unixOpen, /* xOpen */ \
7439 unixDelete, /* xDelete */ \
7440 unixAccess, /* xAccess */ \
7441 unixFullPathname, /* xFullPathname */ \
7442 unixDlOpen, /* xDlOpen */ \
7443 unixDlError, /* xDlError */ \
7444 unixDlSym, /* xDlSym */ \
7445 unixDlClose, /* xDlClose */ \
7446 unixRandomness, /* xRandomness */ \
7447 unixSleep, /* xSleep */ \
7448 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007449 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007450 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007451 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007452 unixGetSystemCall, /* xGetSystemCall */ \
7453 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007454 }
7455
drh6b9d6dd2008-12-03 19:34:47 +00007456 /*
7457 ** All default VFSes for unix are contained in the following array.
7458 **
7459 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7460 ** by the SQLite core when the VFS is registered. So the following
7461 ** array cannot be const.
7462 */
danielk1977e339d652008-06-28 11:23:00 +00007463 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007464#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007465 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007466#elif OS_VXWORKS
7467 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007468#else
7469 UNIXVFS("unix", posixIoFinder ),
7470#endif
7471 UNIXVFS("unix-none", nolockIoFinder ),
7472 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007473 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007474#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007475 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007476#endif
drhe89b2912015-03-03 20:42:01 +00007477#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007478 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007479#endif
drhe89b2912015-03-03 20:42:01 +00007480#if SQLITE_ENABLE_LOCKING_STYLE
7481 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007482#endif
drhd2cb50b2009-01-09 21:41:17 +00007483#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007484 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007485 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007486 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007487#endif
drh153c62c2007-08-24 03:51:33 +00007488 };
drh6b9d6dd2008-12-03 19:34:47 +00007489 unsigned int i; /* Loop counter */
7490
drh2aa5a002011-04-13 13:42:25 +00007491 /* Double-check that the aSyscall[] array has been constructed
7492 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007493 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007494
drh6b9d6dd2008-12-03 19:34:47 +00007495 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007496 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007497 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007498 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007499 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007500}
danielk1977e339d652008-06-28 11:23:00 +00007501
7502/*
drh6b9d6dd2008-12-03 19:34:47 +00007503** Shutdown the operating system interface.
7504**
7505** Some operating systems might need to do some cleanup in this routine,
7506** to release dynamically allocated objects. But not on unix.
7507** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007508*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007509int sqlite3_os_end(void){
7510 return SQLITE_OK;
7511}
drhdce8bdb2007-08-16 13:01:44 +00007512
danielk197729bafea2008-06-26 10:41:19 +00007513#endif /* SQLITE_OS_UNIX */