blob: a40a866780f9f3b1569964c2b3192186e9c800e2 [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
drha8299922016-01-08 22:31:00 +0000449 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000450#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
drh24dbeae2016-01-08 22:18:00 +0000460#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000461 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000462#else
463 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
464#endif
drh6226ca22015-11-24 15:06:28 +0000465#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000466
dan245fdc62015-10-31 17:58:33 +0000467 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drh6226ca22015-11-24 15:06:28 +0000468#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000469
dan702eec12014-06-23 10:04:58 +0000470
drhe562be52011-03-02 18:01:10 +0000471}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000472
drh6226ca22015-11-24 15:06:28 +0000473
474/*
475** On some systems, calls to fchown() will trigger a message in a security
476** log if they come from non-root processes. So avoid calling fchown() if
477** we are not running as root.
478*/
479static int robustFchown(int fd, uid_t uid, gid_t gid){
480#if OS_VXWORKS
481 return 0;
482#else
483 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
484#endif
485}
486
drh99ab3b12011-03-02 15:09:07 +0000487/*
488** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000489** "unix" VFSes. Return SQLITE_OK opon successfully updating the
490** system call pointer, or SQLITE_NOTFOUND if there is no configurable
491** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000492*/
493static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000494 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
495 const char *zName, /* Name of system call to override */
496 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000497){
drh58ad5802011-03-23 22:02:23 +0000498 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000499 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000500
501 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000502 if( zName==0 ){
503 /* If no zName is given, restore all system calls to their default
504 ** settings and return NULL
505 */
dan51438a72011-04-02 17:00:47 +0000506 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000507 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
508 if( aSyscall[i].pDefault ){
509 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000510 }
511 }
512 }else{
513 /* If zName is specified, operate on only the one system call
514 ** specified.
515 */
516 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
517 if( strcmp(zName, aSyscall[i].zName)==0 ){
518 if( aSyscall[i].pDefault==0 ){
519 aSyscall[i].pDefault = aSyscall[i].pCurrent;
520 }
drh1df30962011-03-02 19:06:42 +0000521 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000522 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
523 aSyscall[i].pCurrent = pNewFunc;
524 break;
525 }
526 }
527 }
528 return rc;
529}
530
drh1df30962011-03-02 19:06:42 +0000531/*
532** Return the value of a system call. Return NULL if zName is not a
533** recognized system call name. NULL is also returned if the system call
534** is currently undefined.
535*/
drh58ad5802011-03-23 22:02:23 +0000536static sqlite3_syscall_ptr unixGetSystemCall(
537 sqlite3_vfs *pNotUsed,
538 const char *zName
539){
540 unsigned int i;
541
542 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000543 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
544 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
545 }
546 return 0;
547}
548
549/*
550** Return the name of the first system call after zName. If zName==NULL
551** then return the name of the first system call. Return NULL if zName
552** is the last system call or if zName is not the name of a valid
553** system call.
554*/
555static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000556 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000557
558 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000559 if( zName ){
560 for(i=0; i<ArraySize(aSyscall)-1; i++){
561 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000562 }
563 }
dan0fd7d862011-03-29 10:04:23 +0000564 for(i++; i<ArraySize(aSyscall); i++){
565 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000566 }
567 return 0;
568}
569
drhad4f1e52011-03-04 15:43:57 +0000570/*
drh77a3fdc2013-08-30 14:24:12 +0000571** Do not accept any file descriptor less than this value, in order to avoid
572** opening database file using file descriptors that are commonly used for
573** standard input, output, and error.
574*/
575#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
576# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
577#endif
578
579/*
drh8c815d12012-02-13 20:16:37 +0000580** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000581** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000582**
583** If the file creation mode "m" is 0 then set it to the default for
584** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
585** 0644) as modified by the system umask. If m is not 0, then
586** make the file creation mode be exactly m ignoring the umask.
587**
588** The m parameter will be non-zero only when creating -wal, -journal,
589** and -shm files. We want those files to have *exactly* the same
590** permissions as their original database, unadulterated by the umask.
591** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
592** transaction crashes and leaves behind hot journals, then any
593** process that is able to write to the database will also be able to
594** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000595*/
drh8c815d12012-02-13 20:16:37 +0000596static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000597 int fd;
drhe1186ab2013-01-04 20:45:13 +0000598 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000599 while(1){
drh5adc60b2012-04-14 13:25:11 +0000600#if defined(O_CLOEXEC)
601 fd = osOpen(z,f|O_CLOEXEC,m2);
602#else
603 fd = osOpen(z,f,m2);
604#endif
drh5128d002013-08-30 06:20:23 +0000605 if( fd<0 ){
606 if( errno==EINTR ) continue;
607 break;
608 }
drh77a3fdc2013-08-30 14:24:12 +0000609 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000610 osClose(fd);
611 sqlite3_log(SQLITE_WARNING,
612 "attempt to open \"%s\" as file descriptor %d", z, fd);
613 fd = -1;
614 if( osOpen("/dev/null", f, m)<0 ) break;
615 }
drhe1186ab2013-01-04 20:45:13 +0000616 if( fd>=0 ){
617 if( m!=0 ){
618 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000619 if( osFstat(fd, &statbuf)==0
620 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000621 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000622 ){
drhe1186ab2013-01-04 20:45:13 +0000623 osFchmod(fd, m);
624 }
625 }
drh5adc60b2012-04-14 13:25:11 +0000626#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000627 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000628#endif
drhe1186ab2013-01-04 20:45:13 +0000629 }
drh5adc60b2012-04-14 13:25:11 +0000630 return fd;
drhad4f1e52011-03-04 15:43:57 +0000631}
danielk197713adf8a2004-06-03 16:08:41 +0000632
drh107886a2008-11-21 22:21:50 +0000633/*
dan9359c7b2009-08-21 08:29:10 +0000634** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000635** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000636** vxworksFileId objects used by this file, all of which may be
637** shared by multiple threads.
638**
639** Function unixMutexHeld() is used to assert() that the global mutex
640** is held when required. This function is only used as part of assert()
641** statements. e.g.
642**
643** unixEnterMutex()
644** assert( unixMutexHeld() );
645** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000646*/
647static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000648 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000649}
650static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000651 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000652}
dan9359c7b2009-08-21 08:29:10 +0000653#ifdef SQLITE_DEBUG
654static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000655 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000656}
657#endif
drh107886a2008-11-21 22:21:50 +0000658
drh734c9862008-11-28 15:37:20 +0000659
mistachkinfb383e92015-04-16 03:24:38 +0000660#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000661/*
662** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000663** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000664** integer lock-type.
665*/
drh308c2a52010-05-14 11:30:18 +0000666static const char *azFileLock(int eFileLock){
667 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000668 case NO_LOCK: return "NONE";
669 case SHARED_LOCK: return "SHARED";
670 case RESERVED_LOCK: return "RESERVED";
671 case PENDING_LOCK: return "PENDING";
672 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000673 }
674 return "ERROR";
675}
676#endif
677
678#ifdef SQLITE_LOCK_TRACE
679/*
680** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000681**
drh734c9862008-11-28 15:37:20 +0000682** This routine is used for troubleshooting locks on multithreaded
683** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
684** command-line option on the compiler. This code is normally
685** turned off.
686*/
687static int lockTrace(int fd, int op, struct flock *p){
688 char *zOpName, *zType;
689 int s;
690 int savedErrno;
691 if( op==F_GETLK ){
692 zOpName = "GETLK";
693 }else if( op==F_SETLK ){
694 zOpName = "SETLK";
695 }else{
drh99ab3b12011-03-02 15:09:07 +0000696 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000697 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
698 return s;
699 }
700 if( p->l_type==F_RDLCK ){
701 zType = "RDLCK";
702 }else if( p->l_type==F_WRLCK ){
703 zType = "WRLCK";
704 }else if( p->l_type==F_UNLCK ){
705 zType = "UNLCK";
706 }else{
707 assert( 0 );
708 }
709 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000710 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000711 savedErrno = errno;
712 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
713 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
714 (int)p->l_pid, s);
715 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
716 struct flock l2;
717 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000718 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000719 if( l2.l_type==F_RDLCK ){
720 zType = "RDLCK";
721 }else if( l2.l_type==F_WRLCK ){
722 zType = "WRLCK";
723 }else if( l2.l_type==F_UNLCK ){
724 zType = "UNLCK";
725 }else{
726 assert( 0 );
727 }
728 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
729 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
730 }
731 errno = savedErrno;
732 return s;
733}
drh99ab3b12011-03-02 15:09:07 +0000734#undef osFcntl
735#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000736#endif /* SQLITE_LOCK_TRACE */
737
drhff812312011-02-23 13:33:46 +0000738/*
739** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000740**
drhe6d41732015-02-21 00:49:00 +0000741** All calls to ftruncate() within this file should be made through
742** this wrapper. On the Android platform, bypassing the logic below
743** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000744*/
drhff812312011-02-23 13:33:46 +0000745static int robust_ftruncate(int h, sqlite3_int64 sz){
746 int rc;
dan2ee53412014-09-06 16:49:40 +0000747#ifdef __ANDROID__
748 /* On Android, ftruncate() always uses 32-bit offsets, even if
749 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000750 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000751 ** such attempts. */
752 if( sz>(sqlite3_int64)0x7FFFFFFF ){
753 rc = SQLITE_OK;
754 }else
755#endif
drh99ab3b12011-03-02 15:09:07 +0000756 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000757 return rc;
758}
drh734c9862008-11-28 15:37:20 +0000759
760/*
761** This routine translates a standard POSIX errno code into something
762** useful to the clients of the sqlite3 functions. Specifically, it is
763** intended to translate a variety of "try again" errors into SQLITE_BUSY
764** and a variety of "please close the file descriptor NOW" errors into
765** SQLITE_IOERR
766**
767** Errors during initialization of locks, or file system support for locks,
768** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
769*/
770static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000771 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
772 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
773 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
774 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000775 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000776 case EACCES:
drh734c9862008-11-28 15:37:20 +0000777 case EAGAIN:
778 case ETIMEDOUT:
779 case EBUSY:
780 case EINTR:
781 case ENOLCK:
782 /* random NFS retry error, unless during file system support
783 * introspection, in which it actually means what it says */
784 return SQLITE_BUSY;
785
drh734c9862008-11-28 15:37:20 +0000786 case EPERM:
787 return SQLITE_PERM;
788
drh734c9862008-11-28 15:37:20 +0000789 default:
790 return sqliteIOErr;
791 }
792}
793
794
drh734c9862008-11-28 15:37:20 +0000795/******************************************************************************
796****************** Begin Unique File ID Utility Used By VxWorks ***************
797**
798** On most versions of unix, we can get a unique ID for a file by concatenating
799** the device number and the inode number. But this does not work on VxWorks.
800** On VxWorks, a unique file id must be based on the canonical filename.
801**
802** A pointer to an instance of the following structure can be used as a
803** unique file ID in VxWorks. Each instance of this structure contains
804** a copy of the canonical filename. There is also a reference count.
805** The structure is reclaimed when the number of pointers to it drops to
806** zero.
807**
808** There are never very many files open at one time and lookups are not
809** a performance-critical path, so it is sufficient to put these
810** structures on a linked list.
811*/
812struct vxworksFileId {
813 struct vxworksFileId *pNext; /* Next in a list of them all */
814 int nRef; /* Number of references to this one */
815 int nName; /* Length of the zCanonicalName[] string */
816 char *zCanonicalName; /* Canonical filename */
817};
818
819#if OS_VXWORKS
820/*
drh9b35ea62008-11-29 02:20:26 +0000821** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000822** variable:
823*/
824static struct vxworksFileId *vxworksFileList = 0;
825
826/*
827** Simplify a filename into its canonical form
828** by making the following changes:
829**
830** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000831** * convert /./ into just /
832** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000833**
834** Changes are made in-place. Return the new name length.
835**
836** The original filename is in z[0..n-1]. Return the number of
837** characters in the simplified name.
838*/
839static int vxworksSimplifyName(char *z, int n){
840 int i, j;
841 while( n>1 && z[n-1]=='/' ){ n--; }
842 for(i=j=0; i<n; i++){
843 if( z[i]=='/' ){
844 if( z[i+1]=='/' ) continue;
845 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
846 i += 1;
847 continue;
848 }
849 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
850 while( j>0 && z[j-1]!='/' ){ j--; }
851 if( j>0 ){ j--; }
852 i += 2;
853 continue;
854 }
855 }
856 z[j++] = z[i];
857 }
858 z[j] = 0;
859 return j;
860}
861
862/*
863** Find a unique file ID for the given absolute pathname. Return
864** a pointer to the vxworksFileId object. This pointer is the unique
865** file ID.
866**
867** The nRef field of the vxworksFileId object is incremented before
868** the object is returned. A new vxworksFileId object is created
869** and added to the global list if necessary.
870**
871** If a memory allocation error occurs, return NULL.
872*/
873static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
874 struct vxworksFileId *pNew; /* search key and new file ID */
875 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
876 int n; /* Length of zAbsoluteName string */
877
878 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000879 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000880 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000881 if( pNew==0 ) return 0;
882 pNew->zCanonicalName = (char*)&pNew[1];
883 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
884 n = vxworksSimplifyName(pNew->zCanonicalName, n);
885
886 /* Search for an existing entry that matching the canonical name.
887 ** If found, increment the reference count and return a pointer to
888 ** the existing file ID.
889 */
890 unixEnterMutex();
891 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
892 if( pCandidate->nName==n
893 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
894 ){
895 sqlite3_free(pNew);
896 pCandidate->nRef++;
897 unixLeaveMutex();
898 return pCandidate;
899 }
900 }
901
902 /* No match was found. We will make a new file ID */
903 pNew->nRef = 1;
904 pNew->nName = n;
905 pNew->pNext = vxworksFileList;
906 vxworksFileList = pNew;
907 unixLeaveMutex();
908 return pNew;
909}
910
911/*
912** Decrement the reference count on a vxworksFileId object. Free
913** the object when the reference count reaches zero.
914*/
915static void vxworksReleaseFileId(struct vxworksFileId *pId){
916 unixEnterMutex();
917 assert( pId->nRef>0 );
918 pId->nRef--;
919 if( pId->nRef==0 ){
920 struct vxworksFileId **pp;
921 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
922 assert( *pp==pId );
923 *pp = pId->pNext;
924 sqlite3_free(pId);
925 }
926 unixLeaveMutex();
927}
928#endif /* OS_VXWORKS */
929/*************** End of Unique File ID Utility Used By VxWorks ****************
930******************************************************************************/
931
932
933/******************************************************************************
934*************************** Posix Advisory Locking ****************************
935**
drh9b35ea62008-11-29 02:20:26 +0000936** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000937** section 6.5.2.2 lines 483 through 490 specify that when a process
938** sets or clears a lock, that operation overrides any prior locks set
939** by the same process. It does not explicitly say so, but this implies
940** that it overrides locks set by the same process using a different
941** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000942**
943** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000944** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
945**
946** Suppose ./file1 and ./file2 are really the same file (because
947** one is a hard or symbolic link to the other) then if you set
948** an exclusive lock on fd1, then try to get an exclusive lock
949** on fd2, it works. I would have expected the second lock to
950** fail since there was already a lock on the file due to fd1.
951** But not so. Since both locks came from the same process, the
952** second overrides the first, even though they were on different
953** file descriptors opened on different file names.
954**
drh734c9862008-11-28 15:37:20 +0000955** This means that we cannot use POSIX locks to synchronize file access
956** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000957** to synchronize access for threads in separate processes, but not
958** threads within the same process.
959**
960** To work around the problem, SQLite has to manage file locks internally
961** on its own. Whenever a new database is opened, we have to find the
962** specific inode of the database file (the inode is determined by the
963** st_dev and st_ino fields of the stat structure that fstat() fills in)
964** and check for locks already existing on that inode. When locks are
965** created or removed, we have to look at our own internal record of the
966** locks to see if another thread has previously set a lock on that same
967** inode.
968**
drh9b35ea62008-11-29 02:20:26 +0000969** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
970** For VxWorks, we have to use the alternative unique ID system based on
971** canonical filename and implemented in the previous division.)
972**
danielk1977ad94b582007-08-20 06:44:22 +0000973** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000974** descriptor. It is now a structure that holds the integer file
975** descriptor and a pointer to a structure that describes the internal
976** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000977** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000978** point to the same locking structure. The locking structure keeps
979** a reference count (so we will know when to delete it) and a "cnt"
980** field that tells us its internal lock status. cnt==0 means the
981** file is unlocked. cnt==-1 means the file has an exclusive lock.
982** cnt>0 means there are cnt shared locks on the file.
983**
984** Any attempt to lock or unlock a file first checks the locking
985** structure. The fcntl() system call is only invoked to set a
986** POSIX lock if the internal lock structure transitions between
987** a locked and an unlocked state.
988**
drh734c9862008-11-28 15:37:20 +0000989** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000990**
991** If you close a file descriptor that points to a file that has locks,
992** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000993** released. To work around this problem, each unixInodeInfo object
994** maintains a count of the number of pending locks on tha inode.
995** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000996** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000997** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000998** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000999** be closed and that list is walked (and cleared) when the last lock
1000** clears.
1001**
drh9b35ea62008-11-29 02:20:26 +00001002** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001003**
drh9b35ea62008-11-29 02:20:26 +00001004** Many older versions of linux use the LinuxThreads library which is
1005** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001006** A cannot be modified or overridden by a different thread B.
1007** Only thread A can modify the lock. Locking behavior is correct
1008** if the appliation uses the newer Native Posix Thread Library (NPTL)
1009** on linux - with NPTL a lock created by thread A can override locks
1010** in thread B. But there is no way to know at compile-time which
1011** threading library is being used. So there is no way to know at
1012** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001013** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001014** current process.
drh5fdae772004-06-29 03:29:00 +00001015**
drh8af6c222010-05-14 12:43:01 +00001016** SQLite used to support LinuxThreads. But support for LinuxThreads
1017** was dropped beginning with version 3.7.0. SQLite will still work with
1018** LinuxThreads provided that (1) there is no more than one connection
1019** per database file in the same process and (2) database connections
1020** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001021*/
1022
1023/*
1024** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001025** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001026*/
1027struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001028 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001029#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001030 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001031#else
drh107886a2008-11-21 22:21:50 +00001032 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001033#endif
1034};
1035
1036/*
drhbbd42a62004-05-22 17:41:58 +00001037** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001038** inode. Or, on LinuxThreads, there is one of these structures for
1039** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001040**
danielk1977ad94b582007-08-20 06:44:22 +00001041** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001042** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001043** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001044*/
drh8af6c222010-05-14 12:43:01 +00001045struct unixInodeInfo {
1046 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001047 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001048 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1049 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001050 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001051 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1052 int nLock; /* Number of outstanding file locks */
1053 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1054 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1055 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001056#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001057 unsigned long long sharedByte; /* for AFP simulated shared lock */
1058#endif
drh6c7d5c52008-11-21 20:32:33 +00001059#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001060 sem_t *pSem; /* Named POSIX semaphore */
1061 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001062#endif
drhbbd42a62004-05-22 17:41:58 +00001063};
1064
drhda0e7682008-07-30 15:27:54 +00001065/*
drh8af6c222010-05-14 12:43:01 +00001066** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001067*/
drhd91c68f2010-05-14 14:52:25 +00001068static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001069
drh5fdae772004-06-29 03:29:00 +00001070/*
dane18d4952011-02-21 11:46:24 +00001071**
drhaaeaa182015-11-24 15:12:47 +00001072** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001073** unixLogError().
1074**
1075** It is invoked after an error occurs in an OS function and errno has been
1076** set. It logs a message using sqlite3_log() containing the current value of
1077** errno and, if possible, the human-readable equivalent from strerror() or
1078** strerror_r().
1079**
1080** The first argument passed to the macro should be the error code that
1081** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1082** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001083** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001084** if any.
1085*/
drh0e9365c2011-03-02 02:08:13 +00001086#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1087static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001088 int errcode, /* SQLite error code */
1089 const char *zFunc, /* Name of OS function that failed */
1090 const char *zPath, /* File path associated with error */
1091 int iLine /* Source line number where error occurred */
1092){
1093 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001094 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001095
1096 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1097 ** the strerror() function to obtain the human-readable error message
1098 ** equivalent to errno. Otherwise, use strerror_r().
1099 */
1100#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1101 char aErr[80];
1102 memset(aErr, 0, sizeof(aErr));
1103 zErr = aErr;
1104
1105 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001106 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001107 ** returns a pointer to a buffer containing the error message. That pointer
1108 ** may point to aErr[], or it may point to some static storage somewhere.
1109 ** Otherwise, assume that the system provides the POSIX version of
1110 ** strerror_r(), which always writes an error message into aErr[].
1111 **
1112 ** If the code incorrectly assumes that it is the POSIX version that is
1113 ** available, the error message will often be an empty string. Not a
1114 ** huge problem. Incorrectly concluding that the GNU version is available
1115 ** could lead to a segfault though.
1116 */
1117#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1118 zErr =
1119# endif
drh0e9365c2011-03-02 02:08:13 +00001120 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001121
1122#elif SQLITE_THREADSAFE
1123 /* This is a threadsafe build, but strerror_r() is not available. */
1124 zErr = "";
1125#else
1126 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001127 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001128#endif
1129
drh0e9365c2011-03-02 02:08:13 +00001130 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001131 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001132 "os_unix.c:%d: (%d) %s(%s) - %s",
1133 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001134 );
1135
1136 return errcode;
1137}
1138
drh0e9365c2011-03-02 02:08:13 +00001139/*
1140** Close a file descriptor.
1141**
1142** We assume that close() almost always works, since it is only in a
1143** very sick application or on a very sick platform that it might fail.
1144** If it does fail, simply leak the file descriptor, but do log the
1145** error.
1146**
1147** Note that it is not safe to retry close() after EINTR since the
1148** file descriptor might have already been reused by another thread.
1149** So we don't even try to recover from an EINTR. Just log the error
1150** and move on.
1151*/
1152static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001153 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001154 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1155 pFile ? pFile->zPath : 0, lineno);
1156 }
1157}
dane18d4952011-02-21 11:46:24 +00001158
1159/*
drhe6d41732015-02-21 00:49:00 +00001160** Set the pFile->lastErrno. Do this in a subroutine as that provides
1161** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001162*/
1163static void storeLastErrno(unixFile *pFile, int error){
1164 pFile->lastErrno = error;
1165}
1166
1167/*
danb0ac3e32010-06-16 10:55:42 +00001168** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001169*/
drh0e9365c2011-03-02 02:08:13 +00001170static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001171 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001172 UnixUnusedFd *p;
1173 UnixUnusedFd *pNext;
1174 for(p=pInode->pUnused; p; p=pNext){
1175 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001176 robust_close(pFile, p->fd, __LINE__);
1177 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001178 }
drh0e9365c2011-03-02 02:08:13 +00001179 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001180}
1181
1182/*
drh8af6c222010-05-14 12:43:01 +00001183** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001184**
1185** The mutex entered using the unixEnterMutex() function must be held
1186** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001187*/
danb0ac3e32010-06-16 10:55:42 +00001188static void releaseInodeInfo(unixFile *pFile){
1189 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001190 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001191 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001192 pInode->nRef--;
1193 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001194 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001195 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001196 if( pInode->pPrev ){
1197 assert( pInode->pPrev->pNext==pInode );
1198 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001199 }else{
drh8af6c222010-05-14 12:43:01 +00001200 assert( inodeList==pInode );
1201 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001202 }
drh8af6c222010-05-14 12:43:01 +00001203 if( pInode->pNext ){
1204 assert( pInode->pNext->pPrev==pInode );
1205 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001206 }
drh8af6c222010-05-14 12:43:01 +00001207 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001208 }
drhbbd42a62004-05-22 17:41:58 +00001209 }
1210}
1211
1212/*
drh8af6c222010-05-14 12:43:01 +00001213** Given a file descriptor, locate the unixInodeInfo object that
1214** describes that file descriptor. Create a new one if necessary. The
1215** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001216**
dan9359c7b2009-08-21 08:29:10 +00001217** The mutex entered using the unixEnterMutex() function must be held
1218** when this function is called.
1219**
drh6c7d5c52008-11-21 20:32:33 +00001220** Return an appropriate error code.
1221*/
drh8af6c222010-05-14 12:43:01 +00001222static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001223 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001224 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001225){
1226 int rc; /* System call return code */
1227 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001228 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1229 struct stat statbuf; /* Low-level file information */
1230 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001231
dan9359c7b2009-08-21 08:29:10 +00001232 assert( unixMutexHeld() );
1233
drh6c7d5c52008-11-21 20:32:33 +00001234 /* Get low-level information about the file that we can used to
1235 ** create a unique name for the file.
1236 */
1237 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001238 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001239 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001240 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001241#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001242 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1243#endif
1244 return SQLITE_IOERR;
1245 }
1246
drheb0d74f2009-02-03 15:27:02 +00001247#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001248 /* On OS X on an msdos filesystem, the inode number is reported
1249 ** incorrectly for zero-size files. See ticket #3260. To work
1250 ** around this problem (we consider it a bug in OS X, not SQLite)
1251 ** we always increase the file size to 1 by writing a single byte
1252 ** prior to accessing the inode number. The one byte written is
1253 ** an ASCII 'S' character which also happens to be the first byte
1254 ** in the header of every SQLite database. In this way, if there
1255 ** is a race condition such that another thread has already populated
1256 ** the first page of the database, no damage is done.
1257 */
drh7ed97b92010-01-20 13:07:21 +00001258 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001259 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001260 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001261 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001262 return SQLITE_IOERR;
1263 }
drh99ab3b12011-03-02 15:09:07 +00001264 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001265 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001266 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001267 return SQLITE_IOERR;
1268 }
1269 }
drheb0d74f2009-02-03 15:27:02 +00001270#endif
drh6c7d5c52008-11-21 20:32:33 +00001271
drh8af6c222010-05-14 12:43:01 +00001272 memset(&fileId, 0, sizeof(fileId));
1273 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001274#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001275 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001276#else
drh8af6c222010-05-14 12:43:01 +00001277 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001278#endif
drh8af6c222010-05-14 12:43:01 +00001279 pInode = inodeList;
1280 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1281 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001282 }
drh8af6c222010-05-14 12:43:01 +00001283 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001284 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001285 if( pInode==0 ){
1286 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001287 }
drh8af6c222010-05-14 12:43:01 +00001288 memset(pInode, 0, sizeof(*pInode));
1289 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1290 pInode->nRef = 1;
1291 pInode->pNext = inodeList;
1292 pInode->pPrev = 0;
1293 if( inodeList ) inodeList->pPrev = pInode;
1294 inodeList = pInode;
1295 }else{
1296 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001297 }
drh8af6c222010-05-14 12:43:01 +00001298 *ppInode = pInode;
1299 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001300}
drh6c7d5c52008-11-21 20:32:33 +00001301
drhb959a012013-12-07 12:29:22 +00001302/*
1303** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1304*/
1305static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001306#if OS_VXWORKS
1307 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1308#else
drhb959a012013-12-07 12:29:22 +00001309 struct stat buf;
1310 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001311 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001312#endif
drhb959a012013-12-07 12:29:22 +00001313}
1314
aswift5b1a2562008-08-22 00:22:35 +00001315
1316/*
drhfbc7e882013-04-11 01:16:15 +00001317** Check a unixFile that is a database. Verify the following:
1318**
1319** (1) There is exactly one hard link on the file
1320** (2) The file is not a symbolic link
1321** (3) The file has not been renamed or unlinked
1322**
1323** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1324*/
1325static void verifyDbFile(unixFile *pFile){
1326 struct stat buf;
1327 int rc;
drhfbc7e882013-04-11 01:16:15 +00001328 rc = osFstat(pFile->h, &buf);
1329 if( rc!=0 ){
1330 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001331 return;
1332 }
drh3044b512014-06-16 16:41:52 +00001333 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001334 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001335 return;
1336 }
1337 if( buf.st_nlink>1 ){
1338 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001339 return;
1340 }
drhb959a012013-12-07 12:29:22 +00001341 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001342 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001343 return;
1344 }
1345}
1346
1347
1348/*
danielk197713adf8a2004-06-03 16:08:41 +00001349** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001350** file by this or any other process. If such a lock is held, set *pResOut
1351** to a non-zero value otherwise *pResOut is set to zero. The return value
1352** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001353*/
danielk1977861f7452008-06-05 11:39:11 +00001354static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001355 int rc = SQLITE_OK;
1356 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001357 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001358
danielk1977861f7452008-06-05 11:39:11 +00001359 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1360
drh054889e2005-11-30 03:20:31 +00001361 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001362 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001363 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001364
1365 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001366 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001367 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001368 }
1369
drh2ac3ee92004-06-07 16:27:46 +00001370 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001371 */
danielk197709480a92009-02-09 05:32:32 +00001372#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001373 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001374 struct flock lock;
1375 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001376 lock.l_start = RESERVED_BYTE;
1377 lock.l_len = 1;
1378 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001379 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1380 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001381 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001382 } else if( lock.l_type!=F_UNLCK ){
1383 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001384 }
1385 }
danielk197709480a92009-02-09 05:32:32 +00001386#endif
danielk197713adf8a2004-06-03 16:08:41 +00001387
drh6c7d5c52008-11-21 20:32:33 +00001388 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001389 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001390
aswift5b1a2562008-08-22 00:22:35 +00001391 *pResOut = reserved;
1392 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001393}
1394
1395/*
drha7e61d82011-03-12 17:02:57 +00001396** Attempt to set a system-lock on the file pFile. The lock is
1397** described by pLock.
1398**
drh77197112011-03-15 19:08:48 +00001399** If the pFile was opened read/write from unix-excl, then the only lock
1400** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001401** the first time any lock is attempted. All subsequent system locking
1402** operations become no-ops. Locking operations still happen internally,
1403** in order to coordinate access between separate database connections
1404** within this process, but all of that is handled in memory and the
1405** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001406**
1407** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1408** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1409** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001410**
1411** Zero is returned if the call completes successfully, or -1 if a call
1412** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001413*/
1414static int unixFileLock(unixFile *pFile, struct flock *pLock){
1415 int rc;
drh3cb93392011-03-12 18:10:44 +00001416 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001417 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001418 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001419 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001420 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001421 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001422 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001423 lock.l_whence = SEEK_SET;
1424 lock.l_start = SHARED_FIRST;
1425 lock.l_len = SHARED_SIZE;
1426 lock.l_type = F_WRLCK;
1427 rc = osFcntl(pFile->h, F_SETLK, &lock);
1428 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001429 pInode->bProcessLock = 1;
1430 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001431 }else{
1432 rc = 0;
1433 }
1434 }else{
1435 rc = osFcntl(pFile->h, F_SETLK, pLock);
1436 }
1437 return rc;
1438}
1439
1440/*
drh308c2a52010-05-14 11:30:18 +00001441** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001442** of the following:
1443**
drh2ac3ee92004-06-07 16:27:46 +00001444** (1) SHARED_LOCK
1445** (2) RESERVED_LOCK
1446** (3) PENDING_LOCK
1447** (4) EXCLUSIVE_LOCK
1448**
drhb3e04342004-06-08 00:47:47 +00001449** Sometimes when requesting one lock state, additional lock states
1450** are inserted in between. The locking might fail on one of the later
1451** transitions leaving the lock state different from what it started but
1452** still short of its goal. The following chart shows the allowed
1453** transitions and the inserted intermediate states:
1454**
1455** UNLOCKED -> SHARED
1456** SHARED -> RESERVED
1457** SHARED -> (PENDING) -> EXCLUSIVE
1458** RESERVED -> (PENDING) -> EXCLUSIVE
1459** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001460**
drha6abd042004-06-09 17:37:22 +00001461** This routine will only increase a lock. Use the sqlite3OsUnlock()
1462** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001463*/
drh308c2a52010-05-14 11:30:18 +00001464static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001465 /* The following describes the implementation of the various locks and
1466 ** lock transitions in terms of the POSIX advisory shared and exclusive
1467 ** lock primitives (called read-locks and write-locks below, to avoid
1468 ** confusion with SQLite lock names). The algorithms are complicated
1469 ** slightly in order to be compatible with windows systems simultaneously
1470 ** accessing the same database file, in case that is ever required.
1471 **
1472 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1473 ** byte', each single bytes at well known offsets, and the 'shared byte
1474 ** range', a range of 510 bytes at a well known offset.
1475 **
1476 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1477 ** byte'. If this is successful, a random byte from the 'shared byte
1478 ** range' is read-locked and the lock on the 'pending byte' released.
1479 **
danielk197790ba3bd2004-06-25 08:32:25 +00001480 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1481 ** A RESERVED lock is implemented by grabbing a write-lock on the
1482 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001483 **
1484 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001485 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1486 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1487 ** obtained, but existing SHARED locks are allowed to persist. A process
1488 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1489 ** This property is used by the algorithm for rolling back a journal file
1490 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001491 **
danielk197790ba3bd2004-06-25 08:32:25 +00001492 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1493 ** implemented by obtaining a write-lock on the entire 'shared byte
1494 ** range'. Since all other locks require a read-lock on one of the bytes
1495 ** within this range, this ensures that no other locks are held on the
1496 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001497 **
1498 ** The reason a single byte cannot be used instead of the 'shared byte
1499 ** range' is that some versions of windows do not support read-locks. By
1500 ** locking a random byte from a range, concurrent SHARED locks may exist
1501 ** even if the locking primitive used is always a write-lock.
1502 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001503 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001504 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001505 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001506 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001507 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001508
drh054889e2005-11-30 03:20:31 +00001509 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001510 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1511 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001512 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001513 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001514
1515 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001516 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001517 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001518 */
drh308c2a52010-05-14 11:30:18 +00001519 if( pFile->eFileLock>=eFileLock ){
1520 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1521 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001522 return SQLITE_OK;
1523 }
1524
drh0c2694b2009-09-03 16:23:44 +00001525 /* Make sure the locking sequence is correct.
1526 ** (1) We never move from unlocked to anything higher than shared lock.
1527 ** (2) SQLite never explicitly requests a pendig lock.
1528 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001529 */
drh308c2a52010-05-14 11:30:18 +00001530 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1531 assert( eFileLock!=PENDING_LOCK );
1532 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001533
drh8af6c222010-05-14 12:43:01 +00001534 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001535 */
drh6c7d5c52008-11-21 20:32:33 +00001536 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001537 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001538
danielk1977ad94b582007-08-20 06:44:22 +00001539 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001540 ** handle that precludes the requested lock, return BUSY.
1541 */
drh8af6c222010-05-14 12:43:01 +00001542 if( (pFile->eFileLock!=pInode->eFileLock &&
1543 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001544 ){
1545 rc = SQLITE_BUSY;
1546 goto end_lock;
1547 }
1548
1549 /* If a SHARED lock is requested, and some thread using this PID already
1550 ** has a SHARED or RESERVED lock, then increment reference counts and
1551 ** return SQLITE_OK.
1552 */
drh308c2a52010-05-14 11:30:18 +00001553 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001554 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001555 assert( eFileLock==SHARED_LOCK );
1556 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001557 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001558 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001559 pInode->nShared++;
1560 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001561 goto end_lock;
1562 }
1563
danielk19779a1d0ab2004-06-01 14:09:28 +00001564
drh3cde3bb2004-06-12 02:17:14 +00001565 /* A PENDING lock is needed before acquiring a SHARED lock and before
1566 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1567 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001568 */
drh0c2694b2009-09-03 16:23:44 +00001569 lock.l_len = 1L;
1570 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001571 if( eFileLock==SHARED_LOCK
1572 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001573 ){
drh308c2a52010-05-14 11:30:18 +00001574 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001575 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001576 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001577 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001578 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001579 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001580 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001581 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001582 goto end_lock;
1583 }
drh3cde3bb2004-06-12 02:17:14 +00001584 }
1585
1586
1587 /* If control gets to this point, then actually go ahead and make
1588 ** operating system calls for the specified lock.
1589 */
drh308c2a52010-05-14 11:30:18 +00001590 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001591 assert( pInode->nShared==0 );
1592 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001593 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001594
drh2ac3ee92004-06-07 16:27:46 +00001595 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001596 lock.l_start = SHARED_FIRST;
1597 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001598 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001599 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001600 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001601 }
dan661d71a2011-03-30 19:08:03 +00001602
drh2ac3ee92004-06-07 16:27:46 +00001603 /* Drop the temporary PENDING lock */
1604 lock.l_start = PENDING_BYTE;
1605 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001606 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001607 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1608 /* This could happen with a network mount */
1609 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001610 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001611 }
dan661d71a2011-03-30 19:08:03 +00001612
1613 if( rc ){
1614 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001615 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001616 }
dan661d71a2011-03-30 19:08:03 +00001617 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001618 }else{
drh308c2a52010-05-14 11:30:18 +00001619 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001620 pInode->nLock++;
1621 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001622 }
drh8af6c222010-05-14 12:43:01 +00001623 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001624 /* We are trying for an exclusive lock but another thread in this
1625 ** same process is still holding a shared lock. */
1626 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001627 }else{
drh3cde3bb2004-06-12 02:17:14 +00001628 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001629 ** assumed that there is a SHARED or greater lock on the file
1630 ** already.
1631 */
drh308c2a52010-05-14 11:30:18 +00001632 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001633 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001634
1635 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1636 if( eFileLock==RESERVED_LOCK ){
1637 lock.l_start = RESERVED_BYTE;
1638 lock.l_len = 1L;
1639 }else{
1640 lock.l_start = SHARED_FIRST;
1641 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001642 }
dan661d71a2011-03-30 19:08:03 +00001643
1644 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001645 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001646 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001647 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001648 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001649 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001650 }
drhbbd42a62004-05-22 17:41:58 +00001651 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001652
drh8f941bc2009-01-14 23:03:40 +00001653
drhd3d8c042012-05-29 17:02:40 +00001654#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001655 /* Set up the transaction-counter change checking flags when
1656 ** transitioning from a SHARED to a RESERVED lock. The change
1657 ** from SHARED to RESERVED marks the beginning of a normal
1658 ** write operation (not a hot journal rollback).
1659 */
1660 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001661 && pFile->eFileLock<=SHARED_LOCK
1662 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001663 ){
1664 pFile->transCntrChng = 0;
1665 pFile->dbUpdate = 0;
1666 pFile->inNormalWrite = 1;
1667 }
1668#endif
1669
1670
danielk1977ecb2a962004-06-02 06:30:16 +00001671 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001672 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001673 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001674 }else if( eFileLock==EXCLUSIVE_LOCK ){
1675 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001676 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001677 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001678
1679end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001680 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001681 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1682 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001683 return rc;
1684}
1685
1686/*
dan08da86a2009-08-21 17:18:03 +00001687** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001688** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001689*/
1690static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001691 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001692 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001693 p->pNext = pInode->pUnused;
1694 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001695 pFile->h = -1;
1696 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001697}
1698
1699/*
drh308c2a52010-05-14 11:30:18 +00001700** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001701** must be either NO_LOCK or SHARED_LOCK.
1702**
1703** If the locking level of the file descriptor is already at or below
1704** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001705**
1706** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1707** the byte range is divided into 2 parts and the first part is unlocked then
1708** set to a read lock, then the other part is simply unlocked. This works
1709** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1710** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001711*/
drha7e61d82011-03-12 17:02:57 +00001712static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001713 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001714 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001715 struct flock lock;
1716 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001717
drh054889e2005-11-30 03:20:31 +00001718 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001719 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001720 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001721 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001722
drh308c2a52010-05-14 11:30:18 +00001723 assert( eFileLock<=SHARED_LOCK );
1724 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001725 return SQLITE_OK;
1726 }
drh6c7d5c52008-11-21 20:32:33 +00001727 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001728 pInode = pFile->pInode;
1729 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001730 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001731 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001732
drhd3d8c042012-05-29 17:02:40 +00001733#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001734 /* When reducing a lock such that other processes can start
1735 ** reading the database file again, make sure that the
1736 ** transaction counter was updated if any part of the database
1737 ** file changed. If the transaction counter is not updated,
1738 ** other connections to the same file might not realize that
1739 ** the file has changed and hence might not know to flush their
1740 ** cache. The use of a stale cache can lead to database corruption.
1741 */
drh8f941bc2009-01-14 23:03:40 +00001742 pFile->inNormalWrite = 0;
1743#endif
1744
drh7ed97b92010-01-20 13:07:21 +00001745 /* downgrading to a shared lock on NFS involves clearing the write lock
1746 ** before establishing the readlock - to avoid a race condition we downgrade
1747 ** the lock in 2 blocks, so that part of the range will be covered by a
1748 ** write lock until the rest is covered by a read lock:
1749 ** 1: [WWWWW]
1750 ** 2: [....W]
1751 ** 3: [RRRRW]
1752 ** 4: [RRRR.]
1753 */
drh308c2a52010-05-14 11:30:18 +00001754 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001755#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001756 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001757 assert( handleNFSUnlock==0 );
1758#endif
1759#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001760 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001761 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001762 off_t divSize = SHARED_SIZE - 1;
1763
1764 lock.l_type = F_UNLCK;
1765 lock.l_whence = SEEK_SET;
1766 lock.l_start = SHARED_FIRST;
1767 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001768 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001769 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001770 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001771 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001772 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001773 }
drh7ed97b92010-01-20 13:07:21 +00001774 lock.l_type = F_RDLCK;
1775 lock.l_whence = SEEK_SET;
1776 lock.l_start = SHARED_FIRST;
1777 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001778 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001779 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001780 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1781 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001782 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001783 }
1784 goto end_unlock;
1785 }
1786 lock.l_type = F_UNLCK;
1787 lock.l_whence = SEEK_SET;
1788 lock.l_start = SHARED_FIRST+divSize;
1789 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001790 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001791 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001792 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001793 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001794 goto end_unlock;
1795 }
drh30f776f2011-02-25 03:25:07 +00001796 }else
1797#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1798 {
drh7ed97b92010-01-20 13:07:21 +00001799 lock.l_type = F_RDLCK;
1800 lock.l_whence = SEEK_SET;
1801 lock.l_start = SHARED_FIRST;
1802 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001803 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001804 /* In theory, the call to unixFileLock() cannot fail because another
1805 ** process is holding an incompatible lock. If it does, this
1806 ** indicates that the other process is not following the locking
1807 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1808 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1809 ** an assert to fail). */
1810 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001811 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001812 goto end_unlock;
1813 }
drh9c105bb2004-10-02 20:38:28 +00001814 }
1815 }
drhbbd42a62004-05-22 17:41:58 +00001816 lock.l_type = F_UNLCK;
1817 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001818 lock.l_start = PENDING_BYTE;
1819 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001820 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001821 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001822 }else{
danea83bc62011-04-01 11:56:32 +00001823 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001824 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001825 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001826 }
drhbbd42a62004-05-22 17:41:58 +00001827 }
drh308c2a52010-05-14 11:30:18 +00001828 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001829 /* Decrement the shared lock counter. Release the lock using an
1830 ** OS call only when all threads in this same process have released
1831 ** the lock.
1832 */
drh8af6c222010-05-14 12:43:01 +00001833 pInode->nShared--;
1834 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001835 lock.l_type = F_UNLCK;
1836 lock.l_whence = SEEK_SET;
1837 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001838 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001839 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001840 }else{
danea83bc62011-04-01 11:56:32 +00001841 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001842 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001843 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001844 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001845 }
drha6abd042004-06-09 17:37:22 +00001846 }
1847
drhbbd42a62004-05-22 17:41:58 +00001848 /* Decrement the count of locks against this same file. When the
1849 ** count reaches zero, close any other file descriptors whose close
1850 ** was deferred because of outstanding locks.
1851 */
drh8af6c222010-05-14 12:43:01 +00001852 pInode->nLock--;
1853 assert( pInode->nLock>=0 );
1854 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001855 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001856 }
1857 }
drhf2f105d2012-08-20 15:53:54 +00001858
aswift5b1a2562008-08-22 00:22:35 +00001859end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001860 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001861 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001862 return rc;
drhbbd42a62004-05-22 17:41:58 +00001863}
1864
1865/*
drh308c2a52010-05-14 11:30:18 +00001866** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001867** must be either NO_LOCK or SHARED_LOCK.
1868**
1869** If the locking level of the file descriptor is already at or below
1870** the requested locking level, this routine is a no-op.
1871*/
drh308c2a52010-05-14 11:30:18 +00001872static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001873#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001874 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001875#endif
drha7e61d82011-03-12 17:02:57 +00001876 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001877}
1878
mistachkine98844f2013-08-24 00:59:24 +00001879#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001880static int unixMapfile(unixFile *pFd, i64 nByte);
1881static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001882#endif
danf23da962013-03-23 21:00:41 +00001883
drh7ed97b92010-01-20 13:07:21 +00001884/*
danielk1977e339d652008-06-28 11:23:00 +00001885** This function performs the parts of the "close file" operation
1886** common to all locking schemes. It closes the directory and file
1887** handles, if they are valid, and sets all fields of the unixFile
1888** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001889**
1890** It is *not* necessary to hold the mutex when this routine is called,
1891** even on VxWorks. A mutex will be acquired on VxWorks by the
1892** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001893*/
1894static int closeUnixFile(sqlite3_file *id){
1895 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001896#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001897 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001898#endif
dan661d71a2011-03-30 19:08:03 +00001899 if( pFile->h>=0 ){
1900 robust_close(pFile, pFile->h, __LINE__);
1901 pFile->h = -1;
1902 }
1903#if OS_VXWORKS
1904 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001905 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001906 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001907 }
1908 vxworksReleaseFileId(pFile->pId);
1909 pFile->pId = 0;
1910 }
1911#endif
drh0bdbc902014-06-16 18:35:06 +00001912#ifdef SQLITE_UNLINK_AFTER_CLOSE
1913 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1914 osUnlink(pFile->zPath);
1915 sqlite3_free(*(char**)&pFile->zPath);
1916 pFile->zPath = 0;
1917 }
1918#endif
dan661d71a2011-03-30 19:08:03 +00001919 OSTRACE(("CLOSE %-3d\n", pFile->h));
1920 OpenCounter(-1);
1921 sqlite3_free(pFile->pUnused);
1922 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001923 return SQLITE_OK;
1924}
1925
1926/*
danielk1977e3026632004-06-22 11:29:02 +00001927** Close a file.
1928*/
danielk197762079062007-08-15 17:08:46 +00001929static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001930 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001931 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001932 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001933 unixUnlock(id, NO_LOCK);
1934 unixEnterMutex();
1935
1936 /* unixFile.pInode is always valid here. Otherwise, a different close
1937 ** routine (e.g. nolockClose()) would be called instead.
1938 */
1939 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1940 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1941 /* If there are outstanding locks, do not actually close the file just
1942 ** yet because that would clear those locks. Instead, add the file
1943 ** descriptor to pInode->pUnused list. It will be automatically closed
1944 ** when the last lock is cleared.
1945 */
1946 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001947 }
dan661d71a2011-03-30 19:08:03 +00001948 releaseInodeInfo(pFile);
1949 rc = closeUnixFile(id);
1950 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001951 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001952}
1953
drh734c9862008-11-28 15:37:20 +00001954/************** End of the posix advisory lock implementation *****************
1955******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001956
drh734c9862008-11-28 15:37:20 +00001957/******************************************************************************
1958****************************** No-op Locking **********************************
1959**
1960** Of the various locking implementations available, this is by far the
1961** simplest: locking is ignored. No attempt is made to lock the database
1962** file for reading or writing.
1963**
1964** This locking mode is appropriate for use on read-only databases
1965** (ex: databases that are burned into CD-ROM, for example.) It can
1966** also be used if the application employs some external mechanism to
1967** prevent simultaneous access of the same database by two or more
1968** database connections. But there is a serious risk of database
1969** corruption if this locking mode is used in situations where multiple
1970** database connections are accessing the same database file at the same
1971** time and one or more of those connections are writing.
1972*/
drhbfe66312006-10-03 17:40:40 +00001973
drh734c9862008-11-28 15:37:20 +00001974static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1975 UNUSED_PARAMETER(NotUsed);
1976 *pResOut = 0;
1977 return SQLITE_OK;
1978}
drh734c9862008-11-28 15:37:20 +00001979static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1980 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1981 return SQLITE_OK;
1982}
drh734c9862008-11-28 15:37:20 +00001983static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1984 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1985 return SQLITE_OK;
1986}
1987
1988/*
drh9b35ea62008-11-29 02:20:26 +00001989** Close the file.
drh734c9862008-11-28 15:37:20 +00001990*/
1991static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001992 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001993}
1994
1995/******************* End of the no-op lock implementation *********************
1996******************************************************************************/
1997
1998/******************************************************************************
1999************************* Begin dot-file Locking ******************************
2000**
mistachkin48864df2013-03-21 21:20:32 +00002001** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002002** files (really a directory) to control access to the database. This works
2003** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002004**
2005** (1) There is zero concurrency. A single reader blocks all other
2006** connections from reading or writing the database.
2007**
2008** (2) An application crash or power loss can leave stale lock files
2009** sitting around that need to be cleared manually.
2010**
2011** Nevertheless, a dotlock is an appropriate locking mode for use if no
2012** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002013**
drh9ef6bc42011-11-04 02:24:02 +00002014** Dotfile locking works by creating a subdirectory in the same directory as
2015** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002016** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002017** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002018*/
2019
2020/*
2021** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002022** lock directory.
drh734c9862008-11-28 15:37:20 +00002023*/
2024#define DOTLOCK_SUFFIX ".lock"
2025
drh7708e972008-11-29 00:56:52 +00002026/*
2027** This routine checks if there is a RESERVED lock held on the specified
2028** file by this or any other process. If such a lock is held, set *pResOut
2029** to a non-zero value otherwise *pResOut is set to zero. The return value
2030** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2031**
2032** In dotfile locking, either a lock exists or it does not. So in this
2033** variation of CheckReservedLock(), *pResOut is set to true if any lock
2034** is held on the file and false if the file is unlocked.
2035*/
drh734c9862008-11-28 15:37:20 +00002036static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2037 int rc = SQLITE_OK;
2038 int reserved = 0;
2039 unixFile *pFile = (unixFile*)id;
2040
2041 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2042
2043 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002044 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002045 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002046 *pResOut = reserved;
2047 return rc;
2048}
2049
drh7708e972008-11-29 00:56:52 +00002050/*
drh308c2a52010-05-14 11:30:18 +00002051** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002052** of the following:
2053**
2054** (1) SHARED_LOCK
2055** (2) RESERVED_LOCK
2056** (3) PENDING_LOCK
2057** (4) EXCLUSIVE_LOCK
2058**
2059** Sometimes when requesting one lock state, additional lock states
2060** are inserted in between. The locking might fail on one of the later
2061** transitions leaving the lock state different from what it started but
2062** still short of its goal. The following chart shows the allowed
2063** transitions and the inserted intermediate states:
2064**
2065** UNLOCKED -> SHARED
2066** SHARED -> RESERVED
2067** SHARED -> (PENDING) -> EXCLUSIVE
2068** RESERVED -> (PENDING) -> EXCLUSIVE
2069** PENDING -> EXCLUSIVE
2070**
2071** This routine will only increase a lock. Use the sqlite3OsUnlock()
2072** routine to lower a locking level.
2073**
2074** With dotfile locking, we really only support state (4): EXCLUSIVE.
2075** But we track the other locking levels internally.
2076*/
drh308c2a52010-05-14 11:30:18 +00002077static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002078 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002079 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002080 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002081
drh7708e972008-11-29 00:56:52 +00002082
2083 /* If we have any lock, then the lock file already exists. All we have
2084 ** to do is adjust our internal record of the lock level.
2085 */
drh308c2a52010-05-14 11:30:18 +00002086 if( pFile->eFileLock > NO_LOCK ){
2087 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002088 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002089#ifdef HAVE_UTIME
2090 utime(zLockFile, NULL);
2091#else
drh734c9862008-11-28 15:37:20 +00002092 utimes(zLockFile, NULL);
2093#endif
drh7708e972008-11-29 00:56:52 +00002094 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002095 }
2096
2097 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002098 rc = osMkdir(zLockFile, 0777);
2099 if( rc<0 ){
2100 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002101 int tErrno = errno;
2102 if( EEXIST == tErrno ){
2103 rc = SQLITE_BUSY;
2104 } else {
2105 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002106 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002107 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002108 }
2109 }
drh7708e972008-11-29 00:56:52 +00002110 return rc;
drh734c9862008-11-28 15:37:20 +00002111 }
drh734c9862008-11-28 15:37:20 +00002112
2113 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002114 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002115 return rc;
2116}
2117
drh7708e972008-11-29 00:56:52 +00002118/*
drh308c2a52010-05-14 11:30:18 +00002119** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002120** must be either NO_LOCK or SHARED_LOCK.
2121**
2122** If the locking level of the file descriptor is already at or below
2123** the requested locking level, this routine is a no-op.
2124**
2125** When the locking level reaches NO_LOCK, delete the lock file.
2126*/
drh308c2a52010-05-14 11:30:18 +00002127static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002128 unixFile *pFile = (unixFile*)id;
2129 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002130 int rc;
drh734c9862008-11-28 15:37:20 +00002131
2132 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002133 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002134 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002135 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002136
2137 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002138 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002139 return SQLITE_OK;
2140 }
drh7708e972008-11-29 00:56:52 +00002141
2142 /* To downgrade to shared, simply update our internal notion of the
2143 ** lock state. No need to mess with the file on disk.
2144 */
drh308c2a52010-05-14 11:30:18 +00002145 if( eFileLock==SHARED_LOCK ){
2146 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002147 return SQLITE_OK;
2148 }
2149
drh7708e972008-11-29 00:56:52 +00002150 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002151 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002152 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002153 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002154 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002155 if( tErrno==ENOENT ){
2156 rc = SQLITE_OK;
2157 }else{
danea83bc62011-04-01 11:56:32 +00002158 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002159 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002160 }
2161 return rc;
2162 }
drh308c2a52010-05-14 11:30:18 +00002163 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002164 return SQLITE_OK;
2165}
2166
2167/*
drh9b35ea62008-11-29 02:20:26 +00002168** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002169*/
2170static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002171 unixFile *pFile = (unixFile*)id;
2172 assert( id!=0 );
2173 dotlockUnlock(id, NO_LOCK);
2174 sqlite3_free(pFile->lockingContext);
2175 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002176}
2177/****************** End of the dot-file lock implementation *******************
2178******************************************************************************/
2179
2180/******************************************************************************
2181************************** Begin flock Locking ********************************
2182**
2183** Use the flock() system call to do file locking.
2184**
drh6b9d6dd2008-12-03 19:34:47 +00002185** flock() locking is like dot-file locking in that the various
2186** fine-grain locking levels supported by SQLite are collapsed into
2187** a single exclusive lock. In other words, SHARED, RESERVED, and
2188** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2189** still works when you do this, but concurrency is reduced since
2190** only a single process can be reading the database at a time.
2191**
drhe89b2912015-03-03 20:42:01 +00002192** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002193*/
drhe89b2912015-03-03 20:42:01 +00002194#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002195
drh6b9d6dd2008-12-03 19:34:47 +00002196/*
drhff812312011-02-23 13:33:46 +00002197** Retry flock() calls that fail with EINTR
2198*/
2199#ifdef EINTR
2200static int robust_flock(int fd, int op){
2201 int rc;
2202 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2203 return rc;
2204}
2205#else
drh5c819272011-02-23 14:00:12 +00002206# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002207#endif
2208
2209
2210/*
drh6b9d6dd2008-12-03 19:34:47 +00002211** This routine checks if there is a RESERVED lock held on the specified
2212** file by this or any other process. If such a lock is held, set *pResOut
2213** to a non-zero value otherwise *pResOut is set to zero. The return value
2214** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2215*/
drh734c9862008-11-28 15:37:20 +00002216static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2217 int rc = SQLITE_OK;
2218 int reserved = 0;
2219 unixFile *pFile = (unixFile*)id;
2220
2221 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2222
2223 assert( pFile );
2224
2225 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002226 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002227 reserved = 1;
2228 }
2229
2230 /* Otherwise see if some other process holds it. */
2231 if( !reserved ){
2232 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002233 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002234 if( !lrc ){
2235 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002236 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002237 if ( lrc ) {
2238 int tErrno = errno;
2239 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002240 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002241 storeLastErrno(pFile, tErrno);
2242 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002243 }
2244 } else {
2245 int tErrno = errno;
2246 reserved = 1;
2247 /* someone else might have it reserved */
2248 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2249 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002250 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002251 rc = lrc;
2252 }
2253 }
2254 }
drh308c2a52010-05-14 11:30:18 +00002255 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002256
2257#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2258 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2259 rc = SQLITE_OK;
2260 reserved=1;
2261 }
2262#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2263 *pResOut = reserved;
2264 return rc;
2265}
2266
drh6b9d6dd2008-12-03 19:34:47 +00002267/*
drh308c2a52010-05-14 11:30:18 +00002268** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002269** of the following:
2270**
2271** (1) SHARED_LOCK
2272** (2) RESERVED_LOCK
2273** (3) PENDING_LOCK
2274** (4) EXCLUSIVE_LOCK
2275**
2276** Sometimes when requesting one lock state, additional lock states
2277** are inserted in between. The locking might fail on one of the later
2278** transitions leaving the lock state different from what it started but
2279** still short of its goal. The following chart shows the allowed
2280** transitions and the inserted intermediate states:
2281**
2282** UNLOCKED -> SHARED
2283** SHARED -> RESERVED
2284** SHARED -> (PENDING) -> EXCLUSIVE
2285** RESERVED -> (PENDING) -> EXCLUSIVE
2286** PENDING -> EXCLUSIVE
2287**
2288** flock() only really support EXCLUSIVE locks. We track intermediate
2289** lock states in the sqlite3_file structure, but all locks SHARED or
2290** above are really EXCLUSIVE locks and exclude all other processes from
2291** access the file.
2292**
2293** This routine will only increase a lock. Use the sqlite3OsUnlock()
2294** routine to lower a locking level.
2295*/
drh308c2a52010-05-14 11:30:18 +00002296static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002297 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002298 unixFile *pFile = (unixFile*)id;
2299
2300 assert( pFile );
2301
2302 /* if we already have a lock, it is exclusive.
2303 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002304 if (pFile->eFileLock > NO_LOCK) {
2305 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002306 return SQLITE_OK;
2307 }
2308
2309 /* grab an exclusive lock */
2310
drhff812312011-02-23 13:33:46 +00002311 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002312 int tErrno = errno;
2313 /* didn't get, must be busy */
2314 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2315 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002316 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002317 }
2318 } else {
2319 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002320 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002321 }
drh308c2a52010-05-14 11:30:18 +00002322 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2323 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002324#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2325 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2326 rc = SQLITE_BUSY;
2327 }
2328#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2329 return rc;
2330}
2331
drh6b9d6dd2008-12-03 19:34:47 +00002332
2333/*
drh308c2a52010-05-14 11:30:18 +00002334** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002335** must be either NO_LOCK or SHARED_LOCK.
2336**
2337** If the locking level of the file descriptor is already at or below
2338** the requested locking level, this routine is a no-op.
2339*/
drh308c2a52010-05-14 11:30:18 +00002340static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002341 unixFile *pFile = (unixFile*)id;
2342
2343 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002344 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002345 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002346 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002347
2348 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002349 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002350 return SQLITE_OK;
2351 }
2352
2353 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002354 if (eFileLock==SHARED_LOCK) {
2355 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002356 return SQLITE_OK;
2357 }
2358
2359 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002360 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002361#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002362 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002363#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002364 return SQLITE_IOERR_UNLOCK;
2365 }else{
drh308c2a52010-05-14 11:30:18 +00002366 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002367 return SQLITE_OK;
2368 }
2369}
2370
2371/*
2372** Close a file.
2373*/
2374static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002375 assert( id!=0 );
2376 flockUnlock(id, NO_LOCK);
2377 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002378}
2379
2380#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2381
2382/******************* End of the flock lock implementation *********************
2383******************************************************************************/
2384
2385/******************************************************************************
2386************************ Begin Named Semaphore Locking ************************
2387**
2388** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002389**
2390** Semaphore locking is like dot-lock and flock in that it really only
2391** supports EXCLUSIVE locking. Only a single process can read or write
2392** the database file at a time. This reduces potential concurrency, but
2393** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002394*/
2395#if OS_VXWORKS
2396
drh6b9d6dd2008-12-03 19:34:47 +00002397/*
2398** This routine checks if there is a RESERVED lock held on the specified
2399** file by this or any other process. If such a lock is held, set *pResOut
2400** to a non-zero value otherwise *pResOut is set to zero. The return value
2401** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2402*/
drh8cd5b252015-03-02 22:06:43 +00002403static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002404 int rc = SQLITE_OK;
2405 int reserved = 0;
2406 unixFile *pFile = (unixFile*)id;
2407
2408 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2409
2410 assert( pFile );
2411
2412 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002413 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002414 reserved = 1;
2415 }
2416
2417 /* Otherwise see if some other process holds it. */
2418 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002419 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002420
2421 if( sem_trywait(pSem)==-1 ){
2422 int tErrno = errno;
2423 if( EAGAIN != tErrno ){
2424 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002425 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002426 } else {
2427 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002428 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002429 }
2430 }else{
2431 /* we could have it if we want it */
2432 sem_post(pSem);
2433 }
2434 }
drh308c2a52010-05-14 11:30:18 +00002435 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002436
2437 *pResOut = reserved;
2438 return rc;
2439}
2440
drh6b9d6dd2008-12-03 19:34:47 +00002441/*
drh308c2a52010-05-14 11:30:18 +00002442** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002443** of the following:
2444**
2445** (1) SHARED_LOCK
2446** (2) RESERVED_LOCK
2447** (3) PENDING_LOCK
2448** (4) EXCLUSIVE_LOCK
2449**
2450** Sometimes when requesting one lock state, additional lock states
2451** are inserted in between. The locking might fail on one of the later
2452** transitions leaving the lock state different from what it started but
2453** still short of its goal. The following chart shows the allowed
2454** transitions and the inserted intermediate states:
2455**
2456** UNLOCKED -> SHARED
2457** SHARED -> RESERVED
2458** SHARED -> (PENDING) -> EXCLUSIVE
2459** RESERVED -> (PENDING) -> EXCLUSIVE
2460** PENDING -> EXCLUSIVE
2461**
2462** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2463** lock states in the sqlite3_file structure, but all locks SHARED or
2464** above are really EXCLUSIVE locks and exclude all other processes from
2465** access the file.
2466**
2467** This routine will only increase a lock. Use the sqlite3OsUnlock()
2468** routine to lower a locking level.
2469*/
drh8cd5b252015-03-02 22:06:43 +00002470static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002471 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002472 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002473 int rc = SQLITE_OK;
2474
2475 /* if we already have a lock, it is exclusive.
2476 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002477 if (pFile->eFileLock > NO_LOCK) {
2478 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002479 rc = SQLITE_OK;
2480 goto sem_end_lock;
2481 }
2482
2483 /* lock semaphore now but bail out when already locked. */
2484 if( sem_trywait(pSem)==-1 ){
2485 rc = SQLITE_BUSY;
2486 goto sem_end_lock;
2487 }
2488
2489 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002490 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002491
2492 sem_end_lock:
2493 return rc;
2494}
2495
drh6b9d6dd2008-12-03 19:34:47 +00002496/*
drh308c2a52010-05-14 11:30:18 +00002497** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002498** must be either NO_LOCK or SHARED_LOCK.
2499**
2500** If the locking level of the file descriptor is already at or below
2501** the requested locking level, this routine is a no-op.
2502*/
drh8cd5b252015-03-02 22:06:43 +00002503static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002504 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002505 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002506
2507 assert( pFile );
2508 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002509 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002510 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002511 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002512
2513 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002514 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002515 return SQLITE_OK;
2516 }
2517
2518 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002519 if (eFileLock==SHARED_LOCK) {
2520 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002521 return SQLITE_OK;
2522 }
2523
2524 /* no, really unlock. */
2525 if ( sem_post(pSem)==-1 ) {
2526 int rc, tErrno = errno;
2527 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2528 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002529 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002530 }
2531 return rc;
2532 }
drh308c2a52010-05-14 11:30:18 +00002533 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002534 return SQLITE_OK;
2535}
2536
2537/*
2538 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002539 */
drh8cd5b252015-03-02 22:06:43 +00002540static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002541 if( id ){
2542 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002543 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002544 assert( pFile );
2545 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002546 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002547 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002548 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002549 }
2550 return SQLITE_OK;
2551}
2552
2553#endif /* OS_VXWORKS */
2554/*
2555** Named semaphore locking is only available on VxWorks.
2556**
2557*************** End of the named semaphore lock implementation ****************
2558******************************************************************************/
2559
2560
2561/******************************************************************************
2562*************************** Begin AFP Locking *********************************
2563**
2564** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2565** on Apple Macintosh computers - both OS9 and OSX.
2566**
2567** Third-party implementations of AFP are available. But this code here
2568** only works on OSX.
2569*/
2570
drhd2cb50b2009-01-09 21:41:17 +00002571#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002572/*
2573** The afpLockingContext structure contains all afp lock specific state
2574*/
drhbfe66312006-10-03 17:40:40 +00002575typedef struct afpLockingContext afpLockingContext;
2576struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002577 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002578 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002579};
2580
2581struct ByteRangeLockPB2
2582{
2583 unsigned long long offset; /* offset to first byte to lock */
2584 unsigned long long length; /* nbr of bytes to lock */
2585 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2586 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2587 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2588 int fd; /* file desc to assoc this lock with */
2589};
2590
drhfd131da2007-08-07 17:13:03 +00002591#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002592
drh6b9d6dd2008-12-03 19:34:47 +00002593/*
2594** This is a utility for setting or clearing a bit-range lock on an
2595** AFP filesystem.
2596**
2597** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2598*/
2599static int afpSetLock(
2600 const char *path, /* Name of the file to be locked or unlocked */
2601 unixFile *pFile, /* Open file descriptor on path */
2602 unsigned long long offset, /* First byte to be locked */
2603 unsigned long long length, /* Number of bytes to lock */
2604 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002605){
drh6b9d6dd2008-12-03 19:34:47 +00002606 struct ByteRangeLockPB2 pb;
2607 int err;
drhbfe66312006-10-03 17:40:40 +00002608
2609 pb.unLockFlag = setLockFlag ? 0 : 1;
2610 pb.startEndFlag = 0;
2611 pb.offset = offset;
2612 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002613 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002614
drh308c2a52010-05-14 11:30:18 +00002615 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002616 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002617 offset, length));
drhbfe66312006-10-03 17:40:40 +00002618 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2619 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002620 int rc;
2621 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002622 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2623 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002624#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2625 rc = SQLITE_BUSY;
2626#else
drh734c9862008-11-28 15:37:20 +00002627 rc = sqliteErrorFromPosixError(tErrno,
2628 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002629#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002630 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002631 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002632 }
2633 return rc;
drhbfe66312006-10-03 17:40:40 +00002634 } else {
aswift5b1a2562008-08-22 00:22:35 +00002635 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002636 }
2637}
2638
drh6b9d6dd2008-12-03 19:34:47 +00002639/*
2640** This routine checks if there is a RESERVED lock held on the specified
2641** file by this or any other process. If such a lock is held, set *pResOut
2642** to a non-zero value otherwise *pResOut is set to zero. The return value
2643** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2644*/
danielk1977e339d652008-06-28 11:23:00 +00002645static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002646 int rc = SQLITE_OK;
2647 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002648 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002649 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002650
aswift5b1a2562008-08-22 00:22:35 +00002651 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2652
2653 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002654 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002655 if( context->reserved ){
2656 *pResOut = 1;
2657 return SQLITE_OK;
2658 }
drh8af6c222010-05-14 12:43:01 +00002659 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002660
2661 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002662 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002663 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002664 }
2665
2666 /* Otherwise see if some other process holds it.
2667 */
aswift5b1a2562008-08-22 00:22:35 +00002668 if( !reserved ){
2669 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002670 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002671 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002672 /* if we succeeded in taking the reserved lock, unlock it to restore
2673 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002674 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002675 } else {
2676 /* if we failed to get the lock then someone else must have it */
2677 reserved = 1;
2678 }
2679 if( IS_LOCK_ERROR(lrc) ){
2680 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002681 }
2682 }
drhbfe66312006-10-03 17:40:40 +00002683
drh7ed97b92010-01-20 13:07:21 +00002684 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002685 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002686
2687 *pResOut = reserved;
2688 return rc;
drhbfe66312006-10-03 17:40:40 +00002689}
2690
drh6b9d6dd2008-12-03 19:34:47 +00002691/*
drh308c2a52010-05-14 11:30:18 +00002692** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002693** of the following:
2694**
2695** (1) SHARED_LOCK
2696** (2) RESERVED_LOCK
2697** (3) PENDING_LOCK
2698** (4) EXCLUSIVE_LOCK
2699**
2700** Sometimes when requesting one lock state, additional lock states
2701** are inserted in between. The locking might fail on one of the later
2702** transitions leaving the lock state different from what it started but
2703** still short of its goal. The following chart shows the allowed
2704** transitions and the inserted intermediate states:
2705**
2706** UNLOCKED -> SHARED
2707** SHARED -> RESERVED
2708** SHARED -> (PENDING) -> EXCLUSIVE
2709** RESERVED -> (PENDING) -> EXCLUSIVE
2710** PENDING -> EXCLUSIVE
2711**
2712** This routine will only increase a lock. Use the sqlite3OsUnlock()
2713** routine to lower a locking level.
2714*/
drh308c2a52010-05-14 11:30:18 +00002715static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002716 int rc = SQLITE_OK;
2717 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002718 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002719 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002720
2721 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002722 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2723 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002724 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002725
drhbfe66312006-10-03 17:40:40 +00002726 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002727 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002728 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002729 */
drh308c2a52010-05-14 11:30:18 +00002730 if( pFile->eFileLock>=eFileLock ){
2731 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2732 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002733 return SQLITE_OK;
2734 }
2735
2736 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002737 ** (1) We never move from unlocked to anything higher than shared lock.
2738 ** (2) SQLite never explicitly requests a pendig lock.
2739 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002740 */
drh308c2a52010-05-14 11:30:18 +00002741 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2742 assert( eFileLock!=PENDING_LOCK );
2743 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002744
drh8af6c222010-05-14 12:43:01 +00002745 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002746 */
drh6c7d5c52008-11-21 20:32:33 +00002747 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002748 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002749
2750 /* If some thread using this PID has a lock via a different unixFile*
2751 ** handle that precludes the requested lock, return BUSY.
2752 */
drh8af6c222010-05-14 12:43:01 +00002753 if( (pFile->eFileLock!=pInode->eFileLock &&
2754 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002755 ){
2756 rc = SQLITE_BUSY;
2757 goto afp_end_lock;
2758 }
2759
2760 /* If a SHARED lock is requested, and some thread using this PID already
2761 ** has a SHARED or RESERVED lock, then increment reference counts and
2762 ** return SQLITE_OK.
2763 */
drh308c2a52010-05-14 11:30:18 +00002764 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002765 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002766 assert( eFileLock==SHARED_LOCK );
2767 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002768 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002769 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002770 pInode->nShared++;
2771 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002772 goto afp_end_lock;
2773 }
drhbfe66312006-10-03 17:40:40 +00002774
2775 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002776 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2777 ** be released.
2778 */
drh308c2a52010-05-14 11:30:18 +00002779 if( eFileLock==SHARED_LOCK
2780 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002781 ){
2782 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002783 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002784 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002785 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002786 goto afp_end_lock;
2787 }
2788 }
2789
2790 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002791 ** operating system calls for the specified lock.
2792 */
drh308c2a52010-05-14 11:30:18 +00002793 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002794 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002795 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002796
drh8af6c222010-05-14 12:43:01 +00002797 assert( pInode->nShared==0 );
2798 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002799
2800 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002801 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002802 /* note that the quality of the randomness doesn't matter that much */
2803 lk = random();
drh8af6c222010-05-14 12:43:01 +00002804 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002805 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002806 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002807 if( IS_LOCK_ERROR(lrc1) ){
2808 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002809 }
aswift5b1a2562008-08-22 00:22:35 +00002810 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002811 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002812
aswift5b1a2562008-08-22 00:22:35 +00002813 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002814 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002815 rc = lrc1;
2816 goto afp_end_lock;
2817 } else if( IS_LOCK_ERROR(lrc2) ){
2818 rc = lrc2;
2819 goto afp_end_lock;
2820 } else if( lrc1 != SQLITE_OK ) {
2821 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002822 } else {
drh308c2a52010-05-14 11:30:18 +00002823 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002824 pInode->nLock++;
2825 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002826 }
drh8af6c222010-05-14 12:43:01 +00002827 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002828 /* We are trying for an exclusive lock but another thread in this
2829 ** same process is still holding a shared lock. */
2830 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002831 }else{
2832 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2833 ** assumed that there is a SHARED or greater lock on the file
2834 ** already.
2835 */
2836 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002837 assert( 0!=pFile->eFileLock );
2838 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002839 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002840 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002841 if( !failed ){
2842 context->reserved = 1;
2843 }
drhbfe66312006-10-03 17:40:40 +00002844 }
drh308c2a52010-05-14 11:30:18 +00002845 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002846 /* Acquire an EXCLUSIVE lock */
2847
2848 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002849 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002850 */
drh6b9d6dd2008-12-03 19:34:47 +00002851 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002852 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002853 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002854 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002855 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002856 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002857 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002858 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002859 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2860 ** a critical I/O error
2861 */
2862 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2863 SQLITE_IOERR_LOCK;
2864 goto afp_end_lock;
2865 }
2866 }else{
aswift5b1a2562008-08-22 00:22:35 +00002867 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002868 }
2869 }
aswift5b1a2562008-08-22 00:22:35 +00002870 if( failed ){
2871 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002872 }
2873 }
2874
2875 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002876 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002877 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002878 }else if( eFileLock==EXCLUSIVE_LOCK ){
2879 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002880 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002881 }
2882
2883afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002884 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002885 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2886 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002887 return rc;
2888}
2889
2890/*
drh308c2a52010-05-14 11:30:18 +00002891** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002892** must be either NO_LOCK or SHARED_LOCK.
2893**
2894** If the locking level of the file descriptor is already at or below
2895** the requested locking level, this routine is a no-op.
2896*/
drh308c2a52010-05-14 11:30:18 +00002897static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002898 int rc = SQLITE_OK;
2899 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002900 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002901 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2902 int skipShared = 0;
2903#ifdef SQLITE_TEST
2904 int h = pFile->h;
2905#endif
drhbfe66312006-10-03 17:40:40 +00002906
2907 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002908 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002909 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002910 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002911
drh308c2a52010-05-14 11:30:18 +00002912 assert( eFileLock<=SHARED_LOCK );
2913 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002914 return SQLITE_OK;
2915 }
drh6c7d5c52008-11-21 20:32:33 +00002916 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002917 pInode = pFile->pInode;
2918 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002919 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002920 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002921 SimulateIOErrorBenign(1);
2922 SimulateIOError( h=(-1) )
2923 SimulateIOErrorBenign(0);
2924
drhd3d8c042012-05-29 17:02:40 +00002925#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002926 /* When reducing a lock such that other processes can start
2927 ** reading the database file again, make sure that the
2928 ** transaction counter was updated if any part of the database
2929 ** file changed. If the transaction counter is not updated,
2930 ** other connections to the same file might not realize that
2931 ** the file has changed and hence might not know to flush their
2932 ** cache. The use of a stale cache can lead to database corruption.
2933 */
2934 assert( pFile->inNormalWrite==0
2935 || pFile->dbUpdate==0
2936 || pFile->transCntrChng==1 );
2937 pFile->inNormalWrite = 0;
2938#endif
aswiftaebf4132008-11-21 00:10:35 +00002939
drh308c2a52010-05-14 11:30:18 +00002940 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002941 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002942 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002943 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002944 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002945 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2946 } else {
2947 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002948 }
2949 }
drh308c2a52010-05-14 11:30:18 +00002950 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002951 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002952 }
drh308c2a52010-05-14 11:30:18 +00002953 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002954 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2955 if( !rc ){
2956 context->reserved = 0;
2957 }
aswiftaebf4132008-11-21 00:10:35 +00002958 }
drh8af6c222010-05-14 12:43:01 +00002959 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2960 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002961 }
aswiftaebf4132008-11-21 00:10:35 +00002962 }
drh308c2a52010-05-14 11:30:18 +00002963 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002964
drh7ed97b92010-01-20 13:07:21 +00002965 /* Decrement the shared lock counter. Release the lock using an
2966 ** OS call only when all threads in this same process have released
2967 ** the lock.
2968 */
drh8af6c222010-05-14 12:43:01 +00002969 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2970 pInode->nShared--;
2971 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002972 SimulateIOErrorBenign(1);
2973 SimulateIOError( h=(-1) )
2974 SimulateIOErrorBenign(0);
2975 if( !skipShared ){
2976 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2977 }
2978 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002979 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002980 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002981 }
2982 }
2983 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002984 pInode->nLock--;
2985 assert( pInode->nLock>=0 );
2986 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002987 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002988 }
2989 }
drhbfe66312006-10-03 17:40:40 +00002990 }
drh7ed97b92010-01-20 13:07:21 +00002991
drh6c7d5c52008-11-21 20:32:33 +00002992 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002993 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002994 return rc;
2995}
2996
2997/*
drh339eb0b2008-03-07 15:34:11 +00002998** Close a file & cleanup AFP specific locking context
2999*/
danielk1977e339d652008-06-28 11:23:00 +00003000static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003001 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003002 unixFile *pFile = (unixFile*)id;
3003 assert( id!=0 );
3004 afpUnlock(id, NO_LOCK);
3005 unixEnterMutex();
3006 if( pFile->pInode && pFile->pInode->nLock ){
3007 /* If there are outstanding locks, do not actually close the file just
3008 ** yet because that would clear those locks. Instead, add the file
3009 ** descriptor to pInode->aPending. It will be automatically closed when
3010 ** the last lock is cleared.
3011 */
3012 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003013 }
drha8de1e12015-11-30 00:05:39 +00003014 releaseInodeInfo(pFile);
3015 sqlite3_free(pFile->lockingContext);
3016 rc = closeUnixFile(id);
3017 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003018 return rc;
drhbfe66312006-10-03 17:40:40 +00003019}
3020
drhd2cb50b2009-01-09 21:41:17 +00003021#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003022/*
3023** The code above is the AFP lock implementation. The code is specific
3024** to MacOSX and does not work on other unix platforms. No alternative
3025** is available. If you don't compile for a mac, then the "unix-afp"
3026** VFS is not available.
3027**
3028********************* End of the AFP lock implementation **********************
3029******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003030
drh7ed97b92010-01-20 13:07:21 +00003031/******************************************************************************
3032*************************** Begin NFS Locking ********************************/
3033
3034#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3035/*
drh308c2a52010-05-14 11:30:18 +00003036 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003037 ** must be either NO_LOCK or SHARED_LOCK.
3038 **
3039 ** If the locking level of the file descriptor is already at or below
3040 ** the requested locking level, this routine is a no-op.
3041 */
drh308c2a52010-05-14 11:30:18 +00003042static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003043 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003044}
3045
3046#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3047/*
3048** The code above is the NFS lock implementation. The code is specific
3049** to MacOSX and does not work on other unix platforms. No alternative
3050** is available.
3051**
3052********************* End of the NFS lock implementation **********************
3053******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003054
3055/******************************************************************************
3056**************** Non-locking sqlite3_file methods *****************************
3057**
3058** The next division contains implementations for all methods of the
3059** sqlite3_file object other than the locking methods. The locking
3060** methods were defined in divisions above (one locking method per
3061** division). Those methods that are common to all locking modes
3062** are gather together into this division.
3063*/
drhbfe66312006-10-03 17:40:40 +00003064
3065/*
drh734c9862008-11-28 15:37:20 +00003066** Seek to the offset passed as the second argument, then read cnt
3067** bytes into pBuf. Return the number of bytes actually read.
3068**
3069** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3070** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3071** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003072** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003073** See tickets #2741 and #2681.
3074**
3075** To avoid stomping the errno value on a failed read the lastErrno value
3076** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003077*/
drh734c9862008-11-28 15:37:20 +00003078static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3079 int got;
drh58024642011-11-07 18:16:00 +00003080 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003081#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003082 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003083#endif
drh734c9862008-11-28 15:37:20 +00003084 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003085 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003086 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003087 do{
drh734c9862008-11-28 15:37:20 +00003088#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003089 got = osPread(id->h, pBuf, cnt, offset);
3090 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003091#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003092 got = osPread64(id->h, pBuf, cnt, offset);
3093 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003094#else
drh58024642011-11-07 18:16:00 +00003095 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003096 SimulateIOError( newOffset = -1 );
3097 if( newOffset<0 ){
3098 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003099 return -1;
drh734c9862008-11-28 15:37:20 +00003100 }
drh58024642011-11-07 18:16:00 +00003101 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003102#endif
drh58024642011-11-07 18:16:00 +00003103 if( got==cnt ) break;
3104 if( got<0 ){
3105 if( errno==EINTR ){ got = 1; continue; }
3106 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003107 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003108 break;
3109 }else if( got>0 ){
3110 cnt -= got;
3111 offset += got;
3112 prior += got;
3113 pBuf = (void*)(got + (char*)pBuf);
3114 }
3115 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003116 TIMER_END;
drh58024642011-11-07 18:16:00 +00003117 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3118 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3119 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003120}
3121
3122/*
drh734c9862008-11-28 15:37:20 +00003123** Read data from a file into a buffer. Return SQLITE_OK if all
3124** bytes were read successfully and SQLITE_IOERR if anything goes
3125** wrong.
drh339eb0b2008-03-07 15:34:11 +00003126*/
drh734c9862008-11-28 15:37:20 +00003127static int unixRead(
3128 sqlite3_file *id,
3129 void *pBuf,
3130 int amt,
3131 sqlite3_int64 offset
3132){
dan08da86a2009-08-21 17:18:03 +00003133 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003134 int got;
3135 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003136 assert( offset>=0 );
3137 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003138
dan08da86a2009-08-21 17:18:03 +00003139 /* If this is a database file (not a journal, master-journal or temp
3140 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003141#if 0
dane946c392009-08-22 11:39:46 +00003142 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003143 || offset>=PENDING_BYTE+512
3144 || offset+amt<=PENDING_BYTE
3145 );
dan7c246102010-04-12 19:00:29 +00003146#endif
drh08c6d442009-02-09 17:34:07 +00003147
drh9b4c59f2013-04-15 17:03:42 +00003148#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003149 /* Deal with as much of this read request as possible by transfering
3150 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003151 if( offset<pFile->mmapSize ){
3152 if( offset+amt <= pFile->mmapSize ){
3153 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3154 return SQLITE_OK;
3155 }else{
3156 int nCopy = pFile->mmapSize - offset;
3157 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3158 pBuf = &((u8 *)pBuf)[nCopy];
3159 amt -= nCopy;
3160 offset += nCopy;
3161 }
3162 }
drh6e0b6d52013-04-09 16:19:20 +00003163#endif
danf23da962013-03-23 21:00:41 +00003164
dan08da86a2009-08-21 17:18:03 +00003165 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003166 if( got==amt ){
3167 return SQLITE_OK;
3168 }else if( got<0 ){
3169 /* lastErrno set by seekAndRead */
3170 return SQLITE_IOERR_READ;
3171 }else{
drh4bf66fd2015-02-19 02:43:02 +00003172 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003173 /* Unread parts of the buffer must be zero-filled */
3174 memset(&((char*)pBuf)[got], 0, amt-got);
3175 return SQLITE_IOERR_SHORT_READ;
3176 }
3177}
3178
3179/*
dan47a2b4a2013-04-26 16:09:29 +00003180** Attempt to seek the file-descriptor passed as the first argument to
3181** absolute offset iOff, then attempt to write nBuf bytes of data from
3182** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3183** return the actual number of bytes written (which may be less than
3184** nBuf).
3185*/
3186static int seekAndWriteFd(
3187 int fd, /* File descriptor to write to */
3188 i64 iOff, /* File offset to begin writing at */
3189 const void *pBuf, /* Copy data from this buffer to the file */
3190 int nBuf, /* Size of buffer pBuf in bytes */
3191 int *piErrno /* OUT: Error number if error occurs */
3192){
3193 int rc = 0; /* Value returned by system call */
3194
3195 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003196 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003197 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003198 nBuf &= 0x1ffff;
3199 TIMER_START;
3200
3201#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003202 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003203#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003204 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003205#else
3206 do{
3207 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003208 SimulateIOError( iSeek = -1 );
3209 if( iSeek<0 ){
3210 rc = -1;
3211 break;
dan47a2b4a2013-04-26 16:09:29 +00003212 }
3213 rc = osWrite(fd, pBuf, nBuf);
3214 }while( rc<0 && errno==EINTR );
3215#endif
3216
3217 TIMER_END;
3218 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3219
drhe1818ec2015-12-01 16:21:35 +00003220 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003221 return rc;
3222}
3223
3224
3225/*
drh734c9862008-11-28 15:37:20 +00003226** Seek to the offset in id->offset then read cnt bytes into pBuf.
3227** Return the number of bytes actually read. Update the offset.
3228**
3229** To avoid stomping the errno value on a failed write the lastErrno value
3230** is set before returning.
3231*/
3232static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003233 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003234}
3235
3236
3237/*
3238** Write data from a buffer into a file. Return SQLITE_OK on success
3239** or some other error code on failure.
3240*/
3241static int unixWrite(
3242 sqlite3_file *id,
3243 const void *pBuf,
3244 int amt,
3245 sqlite3_int64 offset
3246){
dan08da86a2009-08-21 17:18:03 +00003247 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003248 int wrote = 0;
3249 assert( id );
3250 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003251
dan08da86a2009-08-21 17:18:03 +00003252 /* If this is a database file (not a journal, master-journal or temp
3253 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003254#if 0
dane946c392009-08-22 11:39:46 +00003255 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003256 || offset>=PENDING_BYTE+512
3257 || offset+amt<=PENDING_BYTE
3258 );
dan7c246102010-04-12 19:00:29 +00003259#endif
drh08c6d442009-02-09 17:34:07 +00003260
drhd3d8c042012-05-29 17:02:40 +00003261#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003262 /* If we are doing a normal write to a database file (as opposed to
3263 ** doing a hot-journal rollback or a write to some file other than a
3264 ** normal database file) then record the fact that the database
3265 ** has changed. If the transaction counter is modified, record that
3266 ** fact too.
3267 */
dan08da86a2009-08-21 17:18:03 +00003268 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003269 pFile->dbUpdate = 1; /* The database has been modified */
3270 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003271 int rc;
drh8f941bc2009-01-14 23:03:40 +00003272 char oldCntr[4];
3273 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003274 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003275 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003276 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003277 pFile->transCntrChng = 1; /* The transaction counter has changed */
3278 }
3279 }
3280 }
3281#endif
3282
danfe33e392015-11-17 20:56:06 +00003283#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003284 /* Deal with as much of this write request as possible by transfering
3285 ** data from the memory mapping using memcpy(). */
3286 if( offset<pFile->mmapSize ){
3287 if( offset+amt <= pFile->mmapSize ){
3288 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3289 return SQLITE_OK;
3290 }else{
3291 int nCopy = pFile->mmapSize - offset;
3292 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3293 pBuf = &((u8 *)pBuf)[nCopy];
3294 amt -= nCopy;
3295 offset += nCopy;
3296 }
3297 }
drh6e0b6d52013-04-09 16:19:20 +00003298#endif
drh02bf8b42015-09-01 23:51:53 +00003299
3300 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003301 amt -= wrote;
3302 offset += wrote;
3303 pBuf = &((char*)pBuf)[wrote];
3304 }
3305 SimulateIOError(( wrote=(-1), amt=1 ));
3306 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003307
drh02bf8b42015-09-01 23:51:53 +00003308 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003309 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003310 /* lastErrno set by seekAndWrite */
3311 return SQLITE_IOERR_WRITE;
3312 }else{
drh4bf66fd2015-02-19 02:43:02 +00003313 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003314 return SQLITE_FULL;
3315 }
3316 }
dan6e09d692010-07-27 18:34:15 +00003317
drh734c9862008-11-28 15:37:20 +00003318 return SQLITE_OK;
3319}
3320
3321#ifdef SQLITE_TEST
3322/*
3323** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003324** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003325*/
3326int sqlite3_sync_count = 0;
3327int sqlite3_fullsync_count = 0;
3328#endif
3329
3330/*
drh89240432009-03-25 01:06:01 +00003331** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003332** Others do no. To be safe, we will stick with the (slightly slower)
3333** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003334** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003335*/
drhf7a4a1b2015-01-10 18:02:45 +00003336#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003337# define fdatasync fsync
3338#endif
3339
3340/*
3341** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3342** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3343** only available on Mac OS X. But that could change.
3344*/
3345#ifdef F_FULLFSYNC
3346# define HAVE_FULLFSYNC 1
3347#else
3348# define HAVE_FULLFSYNC 0
3349#endif
3350
3351
3352/*
3353** The fsync() system call does not work as advertised on many
3354** unix systems. The following procedure is an attempt to make
3355** it work better.
3356**
3357** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3358** for testing when we want to run through the test suite quickly.
3359** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3360** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3361** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003362**
3363** SQLite sets the dataOnly flag if the size of the file is unchanged.
3364** The idea behind dataOnly is that it should only write the file content
3365** to disk, not the inode. We only set dataOnly if the file size is
3366** unchanged since the file size is part of the inode. However,
3367** Ted Ts'o tells us that fdatasync() will also write the inode if the
3368** file size has changed. The only real difference between fdatasync()
3369** and fsync(), Ted tells us, is that fdatasync() will not flush the
3370** inode if the mtime or owner or other inode attributes have changed.
3371** We only care about the file size, not the other file attributes, so
3372** as far as SQLite is concerned, an fdatasync() is always adequate.
3373** So, we always use fdatasync() if it is available, regardless of
3374** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003375*/
3376static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003377 int rc;
drh734c9862008-11-28 15:37:20 +00003378
3379 /* The following "ifdef/elif/else/" block has the same structure as
3380 ** the one below. It is replicated here solely to avoid cluttering
3381 ** up the real code with the UNUSED_PARAMETER() macros.
3382 */
3383#ifdef SQLITE_NO_SYNC
3384 UNUSED_PARAMETER(fd);
3385 UNUSED_PARAMETER(fullSync);
3386 UNUSED_PARAMETER(dataOnly);
3387#elif HAVE_FULLFSYNC
3388 UNUSED_PARAMETER(dataOnly);
3389#else
3390 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003391 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003392#endif
3393
3394 /* Record the number of times that we do a normal fsync() and
3395 ** FULLSYNC. This is used during testing to verify that this procedure
3396 ** gets called with the correct arguments.
3397 */
3398#ifdef SQLITE_TEST
3399 if( fullSync ) sqlite3_fullsync_count++;
3400 sqlite3_sync_count++;
3401#endif
3402
3403 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003404 ** no-op. But go ahead and call fstat() to validate the file
3405 ** descriptor as we need a method to provoke a failure during
3406 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003407 */
3408#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003409 {
3410 struct stat buf;
3411 rc = osFstat(fd, &buf);
3412 }
drh734c9862008-11-28 15:37:20 +00003413#elif HAVE_FULLFSYNC
3414 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003415 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003416 }else{
3417 rc = 1;
3418 }
3419 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003420 ** It shouldn't be possible for fullfsync to fail on the local
3421 ** file system (on OSX), so failure indicates that FULLFSYNC
3422 ** isn't supported for this file system. So, attempt an fsync
3423 ** and (for now) ignore the overhead of a superfluous fcntl call.
3424 ** It'd be better to detect fullfsync support once and avoid
3425 ** the fcntl call every time sync is called.
3426 */
drh734c9862008-11-28 15:37:20 +00003427 if( rc ) rc = fsync(fd);
3428
drh7ed97b92010-01-20 13:07:21 +00003429#elif defined(__APPLE__)
3430 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3431 ** so currently we default to the macro that redefines fdatasync to fsync
3432 */
3433 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003434#else
drh0b647ff2009-03-21 14:41:04 +00003435 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003436#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003437 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003438 rc = fsync(fd);
3439 }
drh0b647ff2009-03-21 14:41:04 +00003440#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003441#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3442
3443 if( OS_VXWORKS && rc!= -1 ){
3444 rc = 0;
3445 }
chw97185482008-11-17 08:05:31 +00003446 return rc;
drhbfe66312006-10-03 17:40:40 +00003447}
3448
drh734c9862008-11-28 15:37:20 +00003449/*
drh0059eae2011-08-08 23:48:40 +00003450** Open a file descriptor to the directory containing file zFilename.
3451** If successful, *pFd is set to the opened file descriptor and
3452** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3453** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3454** value.
3455**
drh90315a22011-08-10 01:52:12 +00003456** The directory file descriptor is used for only one thing - to
3457** fsync() a directory to make sure file creation and deletion events
3458** are flushed to disk. Such fsyncs are not needed on newer
3459** journaling filesystems, but are required on older filesystems.
3460**
3461** This routine can be overridden using the xSetSysCall interface.
3462** The ability to override this routine was added in support of the
3463** chromium sandbox. Opening a directory is a security risk (we are
3464** told) so making it overrideable allows the chromium sandbox to
3465** replace this routine with a harmless no-op. To make this routine
3466** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3467** *pFd set to a negative number.
3468**
drh0059eae2011-08-08 23:48:40 +00003469** If SQLITE_OK is returned, the caller is responsible for closing
3470** the file descriptor *pFd using close().
3471*/
3472static int openDirectory(const char *zFilename, int *pFd){
3473 int ii;
3474 int fd = -1;
3475 char zDirname[MAX_PATHNAME+1];
3476
3477 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003478 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3479 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003480 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003481 }else{
3482 if( zDirname[0]!='/' ) zDirname[0] = '.';
3483 zDirname[1] = 0;
3484 }
3485 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3486 if( fd>=0 ){
3487 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003488 }
3489 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003490 if( fd>=0 ) return SQLITE_OK;
3491 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003492}
3493
3494/*
drh734c9862008-11-28 15:37:20 +00003495** Make sure all writes to a particular file are committed to disk.
3496**
3497** If dataOnly==0 then both the file itself and its metadata (file
3498** size, access time, etc) are synced. If dataOnly!=0 then only the
3499** file data is synced.
3500**
3501** Under Unix, also make sure that the directory entry for the file
3502** has been created by fsync-ing the directory that contains the file.
3503** If we do not do this and we encounter a power failure, the directory
3504** entry for the journal might not exist after we reboot. The next
3505** SQLite to access the file will not know that the journal exists (because
3506** the directory entry for the journal was never created) and the transaction
3507** will not roll back - possibly leading to database corruption.
3508*/
3509static int unixSync(sqlite3_file *id, int flags){
3510 int rc;
3511 unixFile *pFile = (unixFile*)id;
3512
3513 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3514 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3515
3516 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3517 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3518 || (flags&0x0F)==SQLITE_SYNC_FULL
3519 );
3520
3521 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3522 ** line is to test that doing so does not cause any problems.
3523 */
3524 SimulateDiskfullError( return SQLITE_FULL );
3525
3526 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003527 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003528 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3529 SimulateIOError( rc=1 );
3530 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003531 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003532 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003533 }
drh0059eae2011-08-08 23:48:40 +00003534
3535 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003536 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003537 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003538 */
3539 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3540 int dirfd;
3541 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003542 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003543 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003544 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003545 full_fsync(dirfd, 0, 0);
3546 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003547 }else{
3548 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003549 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003550 }
drh0059eae2011-08-08 23:48:40 +00003551 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003552 }
3553 return rc;
3554}
3555
3556/*
3557** Truncate an open file to a specified size
3558*/
3559static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003560 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003561 int rc;
dan6e09d692010-07-27 18:34:15 +00003562 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003563 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003564
3565 /* If the user has configured a chunk-size for this file, truncate the
3566 ** file so that it consists of an integer number of chunks (i.e. the
3567 ** actual file size after the operation may be larger than the requested
3568 ** size).
3569 */
drhb8af4b72012-04-05 20:04:39 +00003570 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003571 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3572 }
3573
dan2ee53412014-09-06 16:49:40 +00003574 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003575 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003576 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003577 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003578 }else{
drhd3d8c042012-05-29 17:02:40 +00003579#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003580 /* If we are doing a normal write to a database file (as opposed to
3581 ** doing a hot-journal rollback or a write to some file other than a
3582 ** normal database file) and we truncate the file to zero length,
3583 ** that effectively updates the change counter. This might happen
3584 ** when restoring a database using the backup API from a zero-length
3585 ** source.
3586 */
dan6e09d692010-07-27 18:34:15 +00003587 if( pFile->inNormalWrite && nByte==0 ){
3588 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003589 }
danf23da962013-03-23 21:00:41 +00003590#endif
danc0003312013-03-22 17:46:11 +00003591
mistachkine98844f2013-08-24 00:59:24 +00003592#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003593 /* If the file was just truncated to a size smaller than the currently
3594 ** mapped region, reduce the effective mapping size as well. SQLite will
3595 ** use read() and write() to access data beyond this point from now on.
3596 */
3597 if( nByte<pFile->mmapSize ){
3598 pFile->mmapSize = nByte;
3599 }
mistachkine98844f2013-08-24 00:59:24 +00003600#endif
drh3313b142009-11-06 04:13:18 +00003601
drh734c9862008-11-28 15:37:20 +00003602 return SQLITE_OK;
3603 }
3604}
3605
3606/*
3607** Determine the current size of a file in bytes
3608*/
3609static int unixFileSize(sqlite3_file *id, i64 *pSize){
3610 int rc;
3611 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003612 assert( id );
3613 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003614 SimulateIOError( rc=1 );
3615 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003616 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003617 return SQLITE_IOERR_FSTAT;
3618 }
3619 *pSize = buf.st_size;
3620
drh8af6c222010-05-14 12:43:01 +00003621 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003622 ** writes a single byte into that file in order to work around a bug
3623 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3624 ** layers, we need to report this file size as zero even though it is
3625 ** really 1. Ticket #3260.
3626 */
3627 if( *pSize==1 ) *pSize = 0;
3628
3629
3630 return SQLITE_OK;
3631}
3632
drhd2cb50b2009-01-09 21:41:17 +00003633#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003634/*
3635** Handler for proxy-locking file-control verbs. Defined below in the
3636** proxying locking division.
3637*/
3638static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003639#endif
drh715ff302008-12-03 22:32:44 +00003640
dan502019c2010-07-28 14:26:17 +00003641/*
3642** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003643** file-control operation. Enlarge the database to nBytes in size
3644** (rounded up to the next chunk-size). If the database is already
3645** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003646*/
3647static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003648 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003649 i64 nSize; /* Required file size */
3650 struct stat buf; /* Used to hold return values of fstat() */
3651
drh4bf66fd2015-02-19 02:43:02 +00003652 if( osFstat(pFile->h, &buf) ){
3653 return SQLITE_IOERR_FSTAT;
3654 }
dan502019c2010-07-28 14:26:17 +00003655
3656 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3657 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003658
dan502019c2010-07-28 14:26:17 +00003659#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003660 /* The code below is handling the return value of osFallocate()
3661 ** correctly. posix_fallocate() is defined to "returns zero on success,
3662 ** or an error number on failure". See the manpage for details. */
3663 int err;
drhff812312011-02-23 13:33:46 +00003664 do{
dan661d71a2011-03-30 19:08:03 +00003665 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3666 }while( err==EINTR );
3667 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003668#else
dan592bf7f2014-12-30 19:58:31 +00003669 /* If the OS does not have posix_fallocate(), fake it. Write a
3670 ** single byte to the last byte in each block that falls entirely
3671 ** within the extended region. Then, if required, a single byte
3672 ** at offset (nSize-1), to set the size of the file correctly.
3673 ** This is a similar technique to that used by glibc on systems
3674 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003675 */
3676 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003677 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003678 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003679
drh053378d2015-12-01 22:09:42 +00003680 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003681 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003682 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003683 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3684 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003685 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003686 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003687 }
dan502019c2010-07-28 14:26:17 +00003688#endif
3689 }
3690 }
3691
mistachkine98844f2013-08-24 00:59:24 +00003692#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003693 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003694 int rc;
3695 if( pFile->szChunk<=0 ){
3696 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003697 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003698 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3699 }
3700 }
3701
3702 rc = unixMapfile(pFile, nByte);
3703 return rc;
3704 }
mistachkine98844f2013-08-24 00:59:24 +00003705#endif
danf23da962013-03-23 21:00:41 +00003706
dan502019c2010-07-28 14:26:17 +00003707 return SQLITE_OK;
3708}
danielk1977ad94b582007-08-20 06:44:22 +00003709
danielk1977e3026632004-06-22 11:29:02 +00003710/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003711** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003712** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3713**
3714** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3715*/
3716static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3717 if( *pArg<0 ){
3718 *pArg = (pFile->ctrlFlags & mask)!=0;
3719 }else if( (*pArg)==0 ){
3720 pFile->ctrlFlags &= ~mask;
3721 }else{
3722 pFile->ctrlFlags |= mask;
3723 }
3724}
3725
drh696b33e2012-12-06 19:01:42 +00003726/* Forward declaration */
3727static int unixGetTempname(int nBuf, char *zBuf);
3728
drhf12b3f62011-12-21 14:42:29 +00003729/*
drh9e33c2c2007-08-31 18:34:59 +00003730** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003731*/
drhcc6bb3e2007-08-31 16:11:35 +00003732static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003733 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003734 switch( op ){
3735 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003736 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003737 return SQLITE_OK;
3738 }
drh4bf66fd2015-02-19 02:43:02 +00003739 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003740 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003741 return SQLITE_OK;
3742 }
dan6e09d692010-07-27 18:34:15 +00003743 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003744 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003745 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003746 }
drh9ff27ec2010-05-19 19:26:05 +00003747 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003748 int rc;
3749 SimulateIOErrorBenign(1);
3750 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3751 SimulateIOErrorBenign(0);
3752 return rc;
drhf0b190d2011-07-26 16:03:07 +00003753 }
3754 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003755 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3756 return SQLITE_OK;
3757 }
drhcb15f352011-12-23 01:04:17 +00003758 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3759 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003760 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003761 }
drhde60fc22011-12-14 17:53:36 +00003762 case SQLITE_FCNTL_VFSNAME: {
3763 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3764 return SQLITE_OK;
3765 }
drh696b33e2012-12-06 19:01:42 +00003766 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003767 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003768 if( zTFile ){
3769 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3770 *(char**)pArg = zTFile;
3771 }
3772 return SQLITE_OK;
3773 }
drhb959a012013-12-07 12:29:22 +00003774 case SQLITE_FCNTL_HAS_MOVED: {
3775 *(int*)pArg = fileHasMoved(pFile);
3776 return SQLITE_OK;
3777 }
mistachkine98844f2013-08-24 00:59:24 +00003778#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003779 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003780 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003781 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003782 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3783 newLimit = sqlite3GlobalConfig.mxMmap;
3784 }
3785 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003786 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003787 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003788 if( pFile->mmapSize>0 ){
3789 unixUnmapfile(pFile);
3790 rc = unixMapfile(pFile, -1);
3791 }
danbcb8a862013-04-08 15:30:41 +00003792 }
drh34e258c2013-05-23 01:40:53 +00003793 return rc;
danb2d3de32013-03-14 18:34:37 +00003794 }
mistachkine98844f2013-08-24 00:59:24 +00003795#endif
drhd3d8c042012-05-29 17:02:40 +00003796#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003797 /* The pager calls this method to signal that it has done
3798 ** a rollback and that the database is therefore unchanged and
3799 ** it hence it is OK for the transaction change counter to be
3800 ** unchanged.
3801 */
3802 case SQLITE_FCNTL_DB_UNCHANGED: {
3803 ((unixFile*)id)->dbUpdate = 0;
3804 return SQLITE_OK;
3805 }
3806#endif
drhd2cb50b2009-01-09 21:41:17 +00003807#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003808 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3809 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003810 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003811 }
drhd2cb50b2009-01-09 21:41:17 +00003812#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003813 }
drh0b52b7d2011-01-26 19:46:22 +00003814 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003815}
3816
3817/*
danielk1977a3d4c882007-03-23 10:08:38 +00003818** Return the sector size in bytes of the underlying block device for
3819** the specified file. This is almost always 512 bytes, but may be
3820** larger for some devices.
3821**
3822** SQLite code assumes this function cannot fail. It also assumes that
3823** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003824** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003825** same for both.
3826*/
drh537dddf2012-10-26 13:46:24 +00003827#ifndef __QNXNTO__
3828static int unixSectorSize(sqlite3_file *NotUsed){
3829 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003830 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003831}
drh537dddf2012-10-26 13:46:24 +00003832#endif
3833
3834/*
3835** The following version of unixSectorSize() is optimized for QNX.
3836*/
3837#ifdef __QNXNTO__
3838#include <sys/dcmd_blk.h>
3839#include <sys/statvfs.h>
3840static int unixSectorSize(sqlite3_file *id){
3841 unixFile *pFile = (unixFile*)id;
3842 if( pFile->sectorSize == 0 ){
3843 struct statvfs fsInfo;
3844
3845 /* Set defaults for non-supported filesystems */
3846 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3847 pFile->deviceCharacteristics = 0;
3848 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3849 return pFile->sectorSize;
3850 }
3851
3852 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3853 pFile->sectorSize = fsInfo.f_bsize;
3854 pFile->deviceCharacteristics =
3855 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3856 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3857 ** the write succeeds */
3858 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3859 ** so it is ordered */
3860 0;
3861 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3862 pFile->sectorSize = fsInfo.f_bsize;
3863 pFile->deviceCharacteristics =
3864 /* etfs cluster size writes are atomic */
3865 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3866 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3867 ** the write succeeds */
3868 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3869 ** so it is ordered */
3870 0;
3871 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3872 pFile->sectorSize = fsInfo.f_bsize;
3873 pFile->deviceCharacteristics =
3874 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3875 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3876 ** the write succeeds */
3877 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3878 ** so it is ordered */
3879 0;
3880 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3881 pFile->sectorSize = fsInfo.f_bsize;
3882 pFile->deviceCharacteristics =
3883 /* full bitset of atomics from max sector size and smaller */
3884 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3885 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3886 ** so it is ordered */
3887 0;
3888 }else if( strstr(fsInfo.f_basetype, "dos") ){
3889 pFile->sectorSize = fsInfo.f_bsize;
3890 pFile->deviceCharacteristics =
3891 /* full bitset of atomics from max sector size and smaller */
3892 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3893 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3894 ** so it is ordered */
3895 0;
3896 }else{
3897 pFile->deviceCharacteristics =
3898 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3899 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3900 ** the write succeeds */
3901 0;
3902 }
3903 }
3904 /* Last chance verification. If the sector size isn't a multiple of 512
3905 ** then it isn't valid.*/
3906 if( pFile->sectorSize % 512 != 0 ){
3907 pFile->deviceCharacteristics = 0;
3908 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3909 }
3910 return pFile->sectorSize;
3911}
3912#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003913
danielk197790949c22007-08-17 16:50:38 +00003914/*
drhf12b3f62011-12-21 14:42:29 +00003915** Return the device characteristics for the file.
3916**
drhcb15f352011-12-23 01:04:17 +00003917** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003918** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003919** file system does not always provide powersafe overwrites. (In other
3920** words, after a power-loss event, parts of the file that were never
3921** written might end up being altered.) However, non-PSOW behavior is very,
3922** very rare. And asserting PSOW makes a large reduction in the amount
3923** of required I/O for journaling, since a lot of padding is eliminated.
3924** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3925** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003926*/
drhf12b3f62011-12-21 14:42:29 +00003927static int unixDeviceCharacteristics(sqlite3_file *id){
3928 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003929 int rc = 0;
3930#ifdef __QNXNTO__
3931 if( p->sectorSize==0 ) unixSectorSize(id);
3932 rc = p->deviceCharacteristics;
3933#endif
drhcb15f352011-12-23 01:04:17 +00003934 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003935 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003936 }
drh537dddf2012-10-26 13:46:24 +00003937 return rc;
danielk197762079062007-08-15 17:08:46 +00003938}
3939
dan702eec12014-06-23 10:04:58 +00003940#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003941
dan702eec12014-06-23 10:04:58 +00003942/*
3943** Return the system page size.
3944**
3945** This function should not be called directly by other code in this file.
3946** Instead, it should be called via macro osGetpagesize().
3947*/
3948static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003949#if OS_VXWORKS
3950 return 1024;
3951#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003952 return getpagesize();
3953#else
3954 return (int)sysconf(_SC_PAGESIZE);
3955#endif
3956}
3957
3958#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3959
3960#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003961
3962/*
drhd91c68f2010-05-14 14:52:25 +00003963** Object used to represent an shared memory buffer.
3964**
3965** When multiple threads all reference the same wal-index, each thread
3966** has its own unixShm object, but they all point to a single instance
3967** of this unixShmNode object. In other words, each wal-index is opened
3968** only once per process.
3969**
3970** Each unixShmNode object is connected to a single unixInodeInfo object.
3971** We could coalesce this object into unixInodeInfo, but that would mean
3972** every open file that does not use shared memory (in other words, most
3973** open files) would have to carry around this extra information. So
3974** the unixInodeInfo object contains a pointer to this unixShmNode object
3975** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003976**
3977** unixMutexHeld() must be true when creating or destroying
3978** this object or while reading or writing the following fields:
3979**
3980** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003981**
3982** The following fields are read-only after the object is created:
3983**
3984** fid
3985** zFilename
3986**
drhd91c68f2010-05-14 14:52:25 +00003987** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003988** unixMutexHeld() is true when reading or writing any other field
3989** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003990*/
drhd91c68f2010-05-14 14:52:25 +00003991struct unixShmNode {
3992 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003993 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003994 char *zFilename; /* Name of the mmapped file */
3995 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003996 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003997 u16 nRegion; /* Size of array apRegion */
3998 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003999 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004000 int nRef; /* Number of unixShm objects pointing to this */
4001 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004002#ifdef SQLITE_DEBUG
4003 u8 exclMask; /* Mask of exclusive locks held */
4004 u8 sharedMask; /* Mask of shared locks held */
4005 u8 nextShmId; /* Next available unixShm.id value */
4006#endif
4007};
4008
4009/*
drhd9e5c4f2010-05-12 18:01:39 +00004010** Structure used internally by this VFS to record the state of an
4011** open shared memory connection.
4012**
drhd91c68f2010-05-14 14:52:25 +00004013** The following fields are initialized when this object is created and
4014** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004015**
drhd91c68f2010-05-14 14:52:25 +00004016** unixShm.pFile
4017** unixShm.id
4018**
4019** All other fields are read/write. The unixShm.pFile->mutex must be held
4020** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004021*/
4022struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004023 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4024 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004025 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004026 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004027 u16 sharedMask; /* Mask of shared locks held */
4028 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004029};
4030
4031/*
drhd9e5c4f2010-05-12 18:01:39 +00004032** Constants used for locking
4033*/
drhbd9676c2010-06-23 17:58:38 +00004034#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004035#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004036
drhd9e5c4f2010-05-12 18:01:39 +00004037/*
drh73b64e42010-05-30 19:55:15 +00004038** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004039**
4040** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4041** otherwise.
4042*/
4043static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004044 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004045 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004046 int ofst, /* First byte of the locking range */
4047 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004048){
drhbbf76ee2015-03-10 20:22:35 +00004049 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4050 struct flock f; /* The posix advisory locking structure */
4051 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004052
drhd91c68f2010-05-14 14:52:25 +00004053 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004054 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004055 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004056
drh73b64e42010-05-30 19:55:15 +00004057 /* Shared locks never span more than one byte */
4058 assert( n==1 || lockType!=F_RDLCK );
4059
4060 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004061 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004062
drh3cb93392011-03-12 18:10:44 +00004063 if( pShmNode->h>=0 ){
4064 /* Initialize the locking parameters */
4065 memset(&f, 0, sizeof(f));
4066 f.l_type = lockType;
4067 f.l_whence = SEEK_SET;
4068 f.l_start = ofst;
4069 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004070
drhdcfb9652015-12-02 00:05:26 +00004071 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004072 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4073 }
drhd9e5c4f2010-05-12 18:01:39 +00004074
4075 /* Update the global lock state and do debug tracing */
4076#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004077 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004078 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004079 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004080 if( rc==SQLITE_OK ){
4081 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004082 OSTRACE(("unlock %d ok", ofst));
4083 pShmNode->exclMask &= ~mask;
4084 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004085 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004086 OSTRACE(("read-lock %d ok", ofst));
4087 pShmNode->exclMask &= ~mask;
4088 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004089 }else{
4090 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004091 OSTRACE(("write-lock %d ok", ofst));
4092 pShmNode->exclMask |= mask;
4093 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004094 }
4095 }else{
4096 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004097 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004098 }else if( lockType==F_RDLCK ){
4099 OSTRACE(("read-lock failed"));
4100 }else{
4101 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004102 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004103 }
4104 }
drh20e1f082010-05-31 16:10:12 +00004105 OSTRACE((" - afterwards %03x,%03x\n",
4106 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004107 }
drhd9e5c4f2010-05-12 18:01:39 +00004108#endif
4109
4110 return rc;
4111}
4112
dan781e34c2014-03-20 08:59:47 +00004113/*
dan781e34c2014-03-20 08:59:47 +00004114** Return the minimum number of 32KB shm regions that should be mapped at
4115** a time, assuming that each mapping must be an integer multiple of the
4116** current system page-size.
4117**
4118** Usually, this is 1. The exception seems to be systems that are configured
4119** to use 64KB pages - in this case each mapping must cover at least two
4120** shm regions.
4121*/
4122static int unixShmRegionPerMap(void){
4123 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004124 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004125 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4126 if( pgsz<shmsz ) return 1;
4127 return pgsz/shmsz;
4128}
drhd9e5c4f2010-05-12 18:01:39 +00004129
4130/*
drhd91c68f2010-05-14 14:52:25 +00004131** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004132**
4133** This is not a VFS shared-memory method; it is a utility function called
4134** by VFS shared-memory methods.
4135*/
drhd91c68f2010-05-14 14:52:25 +00004136static void unixShmPurge(unixFile *pFd){
4137 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004138 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004139 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004140 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004141 int i;
drhd91c68f2010-05-14 14:52:25 +00004142 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004143 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004144 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004145 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004146 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004147 }else{
4148 sqlite3_free(p->apRegion[i]);
4149 }
dan13a3cb82010-06-11 19:04:21 +00004150 }
dan18801912010-06-14 14:07:50 +00004151 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004152 if( p->h>=0 ){
4153 robust_close(pFd, p->h, __LINE__);
4154 p->h = -1;
4155 }
drhd91c68f2010-05-14 14:52:25 +00004156 p->pInode->pShmNode = 0;
4157 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004158 }
4159}
4160
4161/*
danda9fe0c2010-07-13 18:44:03 +00004162** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004163** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004164**
drh7234c6d2010-06-19 15:10:09 +00004165** The file used to implement shared-memory is in the same directory
4166** as the open database file and has the same name as the open database
4167** file with the "-shm" suffix added. For example, if the database file
4168** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004169** for shared memory will be called "/home/user1/config.db-shm".
4170**
4171** Another approach to is to use files in /dev/shm or /dev/tmp or an
4172** some other tmpfs mount. But if a file in a different directory
4173** from the database file is used, then differing access permissions
4174** or a chroot() might cause two different processes on the same
4175** database to end up using different files for shared memory -
4176** meaning that their memory would not really be shared - resulting
4177** in database corruption. Nevertheless, this tmpfs file usage
4178** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4179** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4180** option results in an incompatible build of SQLite; builds of SQLite
4181** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4182** same database file at the same time, database corruption will likely
4183** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4184** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004185**
4186** When opening a new shared-memory file, if no other instances of that
4187** file are currently open, in this process or in other processes, then
4188** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004189**
4190** If the original database file (pDbFd) is using the "unix-excl" VFS
4191** that means that an exclusive lock is held on the database file and
4192** that no other processes are able to read or write the database. In
4193** that case, we do not really need shared memory. No shared memory
4194** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004195*/
danda9fe0c2010-07-13 18:44:03 +00004196static int unixOpenSharedMemory(unixFile *pDbFd){
4197 struct unixShm *p = 0; /* The connection to be opened */
4198 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4199 int rc; /* Result code */
4200 unixInodeInfo *pInode; /* The inode of fd */
4201 char *zShmFilename; /* Name of the file used for SHM */
4202 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004203
danda9fe0c2010-07-13 18:44:03 +00004204 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004205 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004206 if( p==0 ) return SQLITE_NOMEM;
4207 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004208 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004209
danda9fe0c2010-07-13 18:44:03 +00004210 /* Check to see if a unixShmNode object already exists. Reuse an existing
4211 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004212 */
4213 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004214 pInode = pDbFd->pInode;
4215 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004216 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004217 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004218#ifndef SQLITE_SHM_DIRECTORY
4219 const char *zBasePath = pDbFd->zPath;
4220#endif
danddb0ac42010-07-14 14:48:58 +00004221
4222 /* Call fstat() to figure out the permissions on the database file. If
4223 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004224 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004225 */
drhf3b1ed02015-12-02 13:11:03 +00004226 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004227 rc = SQLITE_IOERR_FSTAT;
4228 goto shm_open_err;
4229 }
4230
drha4ced192010-07-15 18:32:40 +00004231#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004232 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004233#else
drh4bf66fd2015-02-19 02:43:02 +00004234 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004235#endif
drhf3cdcdc2015-04-29 16:50:28 +00004236 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004237 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004238 rc = SQLITE_NOMEM;
4239 goto shm_open_err;
4240 }
drh9cb5a0d2012-01-05 21:19:54 +00004241 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004242 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004243#ifdef SQLITE_SHM_DIRECTORY
4244 sqlite3_snprintf(nShmFilename, zShmFilename,
4245 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4246 (u32)sStat.st_ino, (u32)sStat.st_dev);
4247#else
drh4bf66fd2015-02-19 02:43:02 +00004248 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004249 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004250#endif
drhd91c68f2010-05-14 14:52:25 +00004251 pShmNode->h = -1;
4252 pDbFd->pInode->pShmNode = pShmNode;
4253 pShmNode->pInode = pDbFd->pInode;
4254 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4255 if( pShmNode->mutex==0 ){
4256 rc = SQLITE_NOMEM;
4257 goto shm_open_err;
4258 }
drhd9e5c4f2010-05-12 18:01:39 +00004259
drh3cb93392011-03-12 18:10:44 +00004260 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004261 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004262 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004263 openFlags = O_RDONLY;
4264 pShmNode->isReadonly = 1;
4265 }
4266 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004267 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004268 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4269 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004270 }
drhac7c3ac2012-02-11 19:23:48 +00004271
4272 /* If this process is running as root, make sure that the SHM file
4273 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004274 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004275 */
drh6226ca22015-11-24 15:06:28 +00004276 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004277
4278 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004279 ** If not, truncate the file to zero length.
4280 */
4281 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004282 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004283 if( robust_ftruncate(pShmNode->h, 0) ){
4284 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004285 }
4286 }
drh66dfec8b2011-06-01 20:01:49 +00004287 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004288 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004289 }
4290 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004291 }
drhd9e5c4f2010-05-12 18:01:39 +00004292 }
4293
drhd91c68f2010-05-14 14:52:25 +00004294 /* Make the new connection a child of the unixShmNode */
4295 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004296#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004297 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004298#endif
drhd91c68f2010-05-14 14:52:25 +00004299 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004300 pDbFd->pShm = p;
4301 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004302
4303 /* The reference count on pShmNode has already been incremented under
4304 ** the cover of the unixEnterMutex() mutex and the pointer from the
4305 ** new (struct unixShm) object to the pShmNode has been set. All that is
4306 ** left to do is to link the new object into the linked list starting
4307 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4308 ** mutex.
4309 */
4310 sqlite3_mutex_enter(pShmNode->mutex);
4311 p->pNext = pShmNode->pFirst;
4312 pShmNode->pFirst = p;
4313 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004314 return SQLITE_OK;
4315
4316 /* Jump here on any error */
4317shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004318 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004319 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004320 unixLeaveMutex();
4321 return rc;
4322}
4323
4324/*
danda9fe0c2010-07-13 18:44:03 +00004325** This function is called to obtain a pointer to region iRegion of the
4326** shared-memory associated with the database file fd. Shared-memory regions
4327** are numbered starting from zero. Each shared-memory region is szRegion
4328** bytes in size.
4329**
4330** If an error occurs, an error code is returned and *pp is set to NULL.
4331**
4332** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4333** region has not been allocated (by any client, including one running in a
4334** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4335** bExtend is non-zero and the requested shared-memory region has not yet
4336** been allocated, it is allocated by this function.
4337**
4338** If the shared-memory region has already been allocated or is allocated by
4339** this call as described above, then it is mapped into this processes
4340** address space (if it is not already), *pp is set to point to the mapped
4341** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004342*/
danda9fe0c2010-07-13 18:44:03 +00004343static int unixShmMap(
4344 sqlite3_file *fd, /* Handle open on database file */
4345 int iRegion, /* Region to retrieve */
4346 int szRegion, /* Size of regions */
4347 int bExtend, /* True to extend file if necessary */
4348 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004349){
danda9fe0c2010-07-13 18:44:03 +00004350 unixFile *pDbFd = (unixFile*)fd;
4351 unixShm *p;
4352 unixShmNode *pShmNode;
4353 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004354 int nShmPerMap = unixShmRegionPerMap();
4355 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004356
danda9fe0c2010-07-13 18:44:03 +00004357 /* If the shared-memory file has not yet been opened, open it now. */
4358 if( pDbFd->pShm==0 ){
4359 rc = unixOpenSharedMemory(pDbFd);
4360 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004361 }
drhd9e5c4f2010-05-12 18:01:39 +00004362
danda9fe0c2010-07-13 18:44:03 +00004363 p = pDbFd->pShm;
4364 pShmNode = p->pShmNode;
4365 sqlite3_mutex_enter(pShmNode->mutex);
4366 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004367 assert( pShmNode->pInode==pDbFd->pInode );
4368 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4369 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004370
dan781e34c2014-03-20 08:59:47 +00004371 /* Minimum number of regions required to be mapped. */
4372 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4373
4374 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004375 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004376 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004377 struct stat sStat; /* Used by fstat() */
4378
4379 pShmNode->szRegion = szRegion;
4380
drh3cb93392011-03-12 18:10:44 +00004381 if( pShmNode->h>=0 ){
4382 /* The requested region is not mapped into this processes address space.
4383 ** Check to see if it has been allocated (i.e. if the wal-index file is
4384 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004385 */
drh3cb93392011-03-12 18:10:44 +00004386 if( osFstat(pShmNode->h, &sStat) ){
4387 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004388 goto shmpage_out;
4389 }
drh3cb93392011-03-12 18:10:44 +00004390
4391 if( sStat.st_size<nByte ){
4392 /* The requested memory region does not exist. If bExtend is set to
4393 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004394 */
dan47a2b4a2013-04-26 16:09:29 +00004395 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004396 goto shmpage_out;
4397 }
dan47a2b4a2013-04-26 16:09:29 +00004398
4399 /* Alternatively, if bExtend is true, extend the file. Do this by
4400 ** writing a single byte to the end of each (OS) page being
4401 ** allocated or extended. Technically, we need only write to the
4402 ** last page in order to extend the file. But writing to all new
4403 ** pages forces the OS to allocate them immediately, which reduces
4404 ** the chances of SIGBUS while accessing the mapped region later on.
4405 */
4406 else{
4407 static const int pgsz = 4096;
4408 int iPg;
4409
4410 /* Write to the last byte of each newly allocated or extended page */
4411 assert( (nByte % pgsz)==0 );
4412 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004413 int x = 0;
4414 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004415 const char *zFile = pShmNode->zFilename;
4416 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4417 goto shmpage_out;
4418 }
4419 }
drh3cb93392011-03-12 18:10:44 +00004420 }
4421 }
danda9fe0c2010-07-13 18:44:03 +00004422 }
4423
4424 /* Map the requested memory region into this processes address space. */
4425 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004426 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004427 );
4428 if( !apNew ){
4429 rc = SQLITE_IOERR_NOMEM;
4430 goto shmpage_out;
4431 }
4432 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004433 while( pShmNode->nRegion<nReqRegion ){
4434 int nMap = szRegion*nShmPerMap;
4435 int i;
drh3cb93392011-03-12 18:10:44 +00004436 void *pMem;
4437 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004438 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004439 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004440 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004441 );
4442 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004443 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004444 goto shmpage_out;
4445 }
4446 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004447 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004448 if( pMem==0 ){
4449 rc = SQLITE_NOMEM;
4450 goto shmpage_out;
4451 }
4452 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004453 }
dan781e34c2014-03-20 08:59:47 +00004454
4455 for(i=0; i<nShmPerMap; i++){
4456 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4457 }
4458 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004459 }
4460 }
4461
4462shmpage_out:
4463 if( pShmNode->nRegion>iRegion ){
4464 *pp = pShmNode->apRegion[iRegion];
4465 }else{
4466 *pp = 0;
4467 }
drh66dfec8b2011-06-01 20:01:49 +00004468 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004469 sqlite3_mutex_leave(pShmNode->mutex);
4470 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004471}
4472
4473/*
drhd9e5c4f2010-05-12 18:01:39 +00004474** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004475**
4476** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4477** different here than in posix. In xShmLock(), one can go from unlocked
4478** to shared and back or from unlocked to exclusive and back. But one may
4479** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004480*/
4481static int unixShmLock(
4482 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004483 int ofst, /* First lock to acquire or release */
4484 int n, /* Number of locks to acquire or release */
4485 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004486){
drh73b64e42010-05-30 19:55:15 +00004487 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4488 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4489 unixShm *pX; /* For looping over all siblings */
4490 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4491 int rc = SQLITE_OK; /* Result code */
4492 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004493
drhd91c68f2010-05-14 14:52:25 +00004494 assert( pShmNode==pDbFd->pInode->pShmNode );
4495 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004496 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004497 assert( n>=1 );
4498 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4499 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4500 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4501 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4502 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004503 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4504 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004505
drhc99597c2010-05-31 01:41:15 +00004506 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004507 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004508 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004509 if( flags & SQLITE_SHM_UNLOCK ){
4510 u16 allMask = 0; /* Mask of locks held by siblings */
4511
4512 /* See if any siblings hold this same lock */
4513 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4514 if( pX==p ) continue;
4515 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4516 allMask |= pX->sharedMask;
4517 }
4518
4519 /* Unlock the system-level locks */
4520 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004521 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004522 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004523 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004524 }
drh73b64e42010-05-30 19:55:15 +00004525
4526 /* Undo the local locks */
4527 if( rc==SQLITE_OK ){
4528 p->exclMask &= ~mask;
4529 p->sharedMask &= ~mask;
4530 }
4531 }else if( flags & SQLITE_SHM_SHARED ){
4532 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4533
4534 /* Find out which shared locks are already held by sibling connections.
4535 ** If any sibling already holds an exclusive lock, go ahead and return
4536 ** SQLITE_BUSY.
4537 */
4538 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004539 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004540 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004541 break;
4542 }
4543 allShared |= pX->sharedMask;
4544 }
4545
4546 /* Get shared locks at the system level, if necessary */
4547 if( rc==SQLITE_OK ){
4548 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004549 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004550 }else{
drh73b64e42010-05-30 19:55:15 +00004551 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004552 }
drhd9e5c4f2010-05-12 18:01:39 +00004553 }
drh73b64e42010-05-30 19:55:15 +00004554
4555 /* Get the local shared locks */
4556 if( rc==SQLITE_OK ){
4557 p->sharedMask |= mask;
4558 }
4559 }else{
4560 /* Make sure no sibling connections hold locks that will block this
4561 ** lock. If any do, return SQLITE_BUSY right away.
4562 */
4563 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004564 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4565 rc = SQLITE_BUSY;
4566 break;
4567 }
4568 }
4569
4570 /* Get the exclusive locks at the system level. Then if successful
4571 ** also mark the local connection as being locked.
4572 */
4573 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004574 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004575 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004576 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004577 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004578 }
drhd9e5c4f2010-05-12 18:01:39 +00004579 }
4580 }
drhd91c68f2010-05-14 14:52:25 +00004581 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004582 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004583 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004584 return rc;
4585}
4586
drh286a2882010-05-20 23:51:06 +00004587/*
4588** Implement a memory barrier or memory fence on shared memory.
4589**
4590** All loads and stores begun before the barrier must complete before
4591** any load or store begun after the barrier.
4592*/
4593static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004594 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004595){
drhff828942010-06-26 21:34:06 +00004596 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004597 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4598 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004599 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004600}
4601
dan18801912010-06-14 14:07:50 +00004602/*
danda9fe0c2010-07-13 18:44:03 +00004603** Close a connection to shared-memory. Delete the underlying
4604** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004605**
4606** If there is no shared memory associated with the connection then this
4607** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004608*/
danda9fe0c2010-07-13 18:44:03 +00004609static int unixShmUnmap(
4610 sqlite3_file *fd, /* The underlying database file */
4611 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004612){
danda9fe0c2010-07-13 18:44:03 +00004613 unixShm *p; /* The connection to be closed */
4614 unixShmNode *pShmNode; /* The underlying shared-memory file */
4615 unixShm **pp; /* For looping over sibling connections */
4616 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004617
danda9fe0c2010-07-13 18:44:03 +00004618 pDbFd = (unixFile*)fd;
4619 p = pDbFd->pShm;
4620 if( p==0 ) return SQLITE_OK;
4621 pShmNode = p->pShmNode;
4622
4623 assert( pShmNode==pDbFd->pInode->pShmNode );
4624 assert( pShmNode->pInode==pDbFd->pInode );
4625
4626 /* Remove connection p from the set of connections associated
4627 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004628 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004629 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4630 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004631
danda9fe0c2010-07-13 18:44:03 +00004632 /* Free the connection p */
4633 sqlite3_free(p);
4634 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004635 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004636
4637 /* If pShmNode->nRef has reached 0, then close the underlying
4638 ** shared-memory file, too */
4639 unixEnterMutex();
4640 assert( pShmNode->nRef>0 );
4641 pShmNode->nRef--;
4642 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004643 if( deleteFlag && pShmNode->h>=0 ){
4644 osUnlink(pShmNode->zFilename);
4645 }
danda9fe0c2010-07-13 18:44:03 +00004646 unixShmPurge(pDbFd);
4647 }
4648 unixLeaveMutex();
4649
4650 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004651}
drh286a2882010-05-20 23:51:06 +00004652
danda9fe0c2010-07-13 18:44:03 +00004653
drhd9e5c4f2010-05-12 18:01:39 +00004654#else
drh6b017cc2010-06-14 18:01:46 +00004655# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004656# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004657# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004658# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004659#endif /* #ifndef SQLITE_OMIT_WAL */
4660
mistachkine98844f2013-08-24 00:59:24 +00004661#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004662/*
danaef49d72013-03-25 16:28:54 +00004663** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004664*/
danf23da962013-03-23 21:00:41 +00004665static void unixUnmapfile(unixFile *pFd){
4666 assert( pFd->nFetchOut==0 );
4667 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004668 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004669 pFd->pMapRegion = 0;
4670 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004671 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004672 }
4673}
dan5d8a1372013-03-19 19:28:06 +00004674
danaef49d72013-03-25 16:28:54 +00004675/*
dane6ecd662013-04-01 17:56:59 +00004676** Attempt to set the size of the memory mapping maintained by file
4677** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4678**
4679** If successful, this function sets the following variables:
4680**
4681** unixFile.pMapRegion
4682** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004683** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004684**
4685** If unsuccessful, an error message is logged via sqlite3_log() and
4686** the three variables above are zeroed. In this case SQLite should
4687** continue accessing the database using the xRead() and xWrite()
4688** methods.
4689*/
4690static void unixRemapfile(
4691 unixFile *pFd, /* File descriptor object */
4692 i64 nNew /* Required mapping size */
4693){
dan4ff7bc42013-04-02 12:04:09 +00004694 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004695 int h = pFd->h; /* File descriptor open on db file */
4696 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004697 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004698 u8 *pNew = 0; /* Location of new mapping */
4699 int flags = PROT_READ; /* Flags to pass to mmap() */
4700
4701 assert( pFd->nFetchOut==0 );
4702 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004703 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004704 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004705 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004706 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004707
danfe33e392015-11-17 20:56:06 +00004708#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004709 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004710#endif
dane6ecd662013-04-01 17:56:59 +00004711
4712 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004713#if HAVE_MREMAP
4714 i64 nReuse = pFd->mmapSize;
4715#else
danbc760632014-03-20 09:42:09 +00004716 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004717 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004718#endif
dane6ecd662013-04-01 17:56:59 +00004719 u8 *pReq = &pOrig[nReuse];
4720
4721 /* Unmap any pages of the existing mapping that cannot be reused. */
4722 if( nReuse!=nOrig ){
4723 osMunmap(pReq, nOrig-nReuse);
4724 }
4725
4726#if HAVE_MREMAP
4727 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004728 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004729#else
4730 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4731 if( pNew!=MAP_FAILED ){
4732 if( pNew!=pReq ){
4733 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004734 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004735 }else{
4736 pNew = pOrig;
4737 }
4738 }
4739#endif
4740
dan48ccef82013-04-02 20:55:01 +00004741 /* The attempt to extend the existing mapping failed. Free it. */
4742 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004743 osMunmap(pOrig, nReuse);
4744 }
4745 }
4746
4747 /* If pNew is still NULL, try to create an entirely new mapping. */
4748 if( pNew==0 ){
4749 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004750 }
4751
dan4ff7bc42013-04-02 12:04:09 +00004752 if( pNew==MAP_FAILED ){
4753 pNew = 0;
4754 nNew = 0;
4755 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4756
4757 /* If the mmap() above failed, assume that all subsequent mmap() calls
4758 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4759 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004760 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004761 }
dane6ecd662013-04-01 17:56:59 +00004762 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004763 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004764}
4765
4766/*
danaef49d72013-03-25 16:28:54 +00004767** Memory map or remap the file opened by file-descriptor pFd (if the file
4768** is already mapped, the existing mapping is replaced by the new). Or, if
4769** there already exists a mapping for this file, and there are still
4770** outstanding xFetch() references to it, this function is a no-op.
4771**
4772** If parameter nByte is non-negative, then it is the requested size of
4773** the mapping to create. Otherwise, if nByte is less than zero, then the
4774** requested size is the size of the file on disk. The actual size of the
4775** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004776** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004777**
4778** SQLITE_OK is returned if no error occurs (even if the mapping is not
4779** recreated as a result of outstanding references) or an SQLite error
4780** code otherwise.
4781*/
drhf3b1ed02015-12-02 13:11:03 +00004782static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004783 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004784 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004785 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4786
4787 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004788 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004789 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004790 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004791 }
drh3044b512014-06-16 16:41:52 +00004792 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004793 }
drh9b4c59f2013-04-15 17:03:42 +00004794 if( nMap>pFd->mmapSizeMax ){
4795 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004796 }
4797
drh333e6ca2015-12-02 15:44:39 +00004798 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004799 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004800 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004801 }
4802
danf23da962013-03-23 21:00:41 +00004803 return SQLITE_OK;
4804}
mistachkine98844f2013-08-24 00:59:24 +00004805#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004806
danaef49d72013-03-25 16:28:54 +00004807/*
4808** If possible, return a pointer to a mapping of file fd starting at offset
4809** iOff. The mapping must be valid for at least nAmt bytes.
4810**
4811** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4812** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4813** Finally, if an error does occur, return an SQLite error code. The final
4814** value of *pp is undefined in this case.
4815**
4816** If this function does return a pointer, the caller must eventually
4817** release the reference by calling unixUnfetch().
4818*/
danf23da962013-03-23 21:00:41 +00004819static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004820#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004821 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004822#endif
danf23da962013-03-23 21:00:41 +00004823 *pp = 0;
4824
drh9b4c59f2013-04-15 17:03:42 +00004825#if SQLITE_MAX_MMAP_SIZE>0
4826 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004827 if( pFd->pMapRegion==0 ){
4828 int rc = unixMapfile(pFd, -1);
4829 if( rc!=SQLITE_OK ) return rc;
4830 }
4831 if( pFd->mmapSize >= iOff+nAmt ){
4832 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4833 pFd->nFetchOut++;
4834 }
4835 }
drh6e0b6d52013-04-09 16:19:20 +00004836#endif
danf23da962013-03-23 21:00:41 +00004837 return SQLITE_OK;
4838}
4839
danaef49d72013-03-25 16:28:54 +00004840/*
dandf737fe2013-03-25 17:00:24 +00004841** If the third argument is non-NULL, then this function releases a
4842** reference obtained by an earlier call to unixFetch(). The second
4843** argument passed to this function must be the same as the corresponding
4844** argument that was passed to the unixFetch() invocation.
4845**
4846** Or, if the third argument is NULL, then this function is being called
4847** to inform the VFS layer that, according to POSIX, any existing mapping
4848** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004849*/
dandf737fe2013-03-25 17:00:24 +00004850static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004851#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004852 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004853 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004854
danaef49d72013-03-25 16:28:54 +00004855 /* If p==0 (unmap the entire file) then there must be no outstanding
4856 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4857 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004858 assert( (p==0)==(pFd->nFetchOut==0) );
4859
dandf737fe2013-03-25 17:00:24 +00004860 /* If p!=0, it must match the iOff value. */
4861 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4862
danf23da962013-03-23 21:00:41 +00004863 if( p ){
4864 pFd->nFetchOut--;
4865 }else{
4866 unixUnmapfile(pFd);
4867 }
4868
4869 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004870#else
4871 UNUSED_PARAMETER(fd);
4872 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004873 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004874#endif
danf23da962013-03-23 21:00:41 +00004875 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004876}
4877
4878/*
drh734c9862008-11-28 15:37:20 +00004879** Here ends the implementation of all sqlite3_file methods.
4880**
4881********************** End sqlite3_file Methods *******************************
4882******************************************************************************/
4883
4884/*
drh6b9d6dd2008-12-03 19:34:47 +00004885** This division contains definitions of sqlite3_io_methods objects that
4886** implement various file locking strategies. It also contains definitions
4887** of "finder" functions. A finder-function is used to locate the appropriate
4888** sqlite3_io_methods object for a particular database file. The pAppData
4889** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4890** the correct finder-function for that VFS.
4891**
4892** Most finder functions return a pointer to a fixed sqlite3_io_methods
4893** object. The only interesting finder-function is autolockIoFinder, which
4894** looks at the filesystem type and tries to guess the best locking
4895** strategy from that.
4896**
peter.d.reid60ec9142014-09-06 16:39:46 +00004897** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004898**
4899** (1) The real finder-function named "FImpt()".
4900**
dane946c392009-08-22 11:39:46 +00004901** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004902**
4903**
4904** A pointer to the F pointer is used as the pAppData value for VFS
4905** objects. We have to do this instead of letting pAppData point
4906** directly at the finder-function since C90 rules prevent a void*
4907** from be cast into a function pointer.
4908**
drh6b9d6dd2008-12-03 19:34:47 +00004909**
drh7708e972008-11-29 00:56:52 +00004910** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004911**
drh7708e972008-11-29 00:56:52 +00004912** * A constant sqlite3_io_methods object call METHOD that has locking
4913** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4914**
4915** * An I/O method finder function called FINDER that returns a pointer
4916** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004917*/
drhe6d41732015-02-21 00:49:00 +00004918#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004919static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004920 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004921 CLOSE, /* xClose */ \
4922 unixRead, /* xRead */ \
4923 unixWrite, /* xWrite */ \
4924 unixTruncate, /* xTruncate */ \
4925 unixSync, /* xSync */ \
4926 unixFileSize, /* xFileSize */ \
4927 LOCK, /* xLock */ \
4928 UNLOCK, /* xUnlock */ \
4929 CKLOCK, /* xCheckReservedLock */ \
4930 unixFileControl, /* xFileControl */ \
4931 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004932 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004933 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004934 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004935 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004936 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004937 unixFetch, /* xFetch */ \
4938 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004939}; \
drh0c2694b2009-09-03 16:23:44 +00004940static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4941 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004942 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004943} \
drh0c2694b2009-09-03 16:23:44 +00004944static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004945 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004946
4947/*
4948** Here are all of the sqlite3_io_methods objects for each of the
4949** locking strategies. Functions that return pointers to these methods
4950** are also created.
4951*/
4952IOMETHODS(
4953 posixIoFinder, /* Finder function name */
4954 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004955 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004956 unixClose, /* xClose method */
4957 unixLock, /* xLock method */
4958 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004959 unixCheckReservedLock, /* xCheckReservedLock method */
4960 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004961)
drh7708e972008-11-29 00:56:52 +00004962IOMETHODS(
4963 nolockIoFinder, /* Finder function name */
4964 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004965 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004966 nolockClose, /* xClose method */
4967 nolockLock, /* xLock method */
4968 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004969 nolockCheckReservedLock, /* xCheckReservedLock method */
4970 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004971)
drh7708e972008-11-29 00:56:52 +00004972IOMETHODS(
4973 dotlockIoFinder, /* Finder function name */
4974 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004975 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004976 dotlockClose, /* xClose method */
4977 dotlockLock, /* xLock method */
4978 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004979 dotlockCheckReservedLock, /* xCheckReservedLock method */
4980 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004981)
drh7708e972008-11-29 00:56:52 +00004982
drhe89b2912015-03-03 20:42:01 +00004983#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004984IOMETHODS(
4985 flockIoFinder, /* Finder function name */
4986 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004987 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004988 flockClose, /* xClose method */
4989 flockLock, /* xLock method */
4990 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004991 flockCheckReservedLock, /* xCheckReservedLock method */
4992 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004993)
drh7708e972008-11-29 00:56:52 +00004994#endif
4995
drh6c7d5c52008-11-21 20:32:33 +00004996#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004997IOMETHODS(
4998 semIoFinder, /* Finder function name */
4999 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005000 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005001 semXClose, /* xClose method */
5002 semXLock, /* xLock method */
5003 semXUnlock, /* xUnlock method */
5004 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005005 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005006)
aswiftaebf4132008-11-21 00:10:35 +00005007#endif
drh7708e972008-11-29 00:56:52 +00005008
drhd2cb50b2009-01-09 21:41:17 +00005009#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005010IOMETHODS(
5011 afpIoFinder, /* Finder function name */
5012 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005013 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005014 afpClose, /* xClose method */
5015 afpLock, /* xLock method */
5016 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005017 afpCheckReservedLock, /* xCheckReservedLock method */
5018 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005019)
drh715ff302008-12-03 22:32:44 +00005020#endif
5021
5022/*
5023** The proxy locking method is a "super-method" in the sense that it
5024** opens secondary file descriptors for the conch and lock files and
5025** it uses proxy, dot-file, AFP, and flock() locking methods on those
5026** secondary files. For this reason, the division that implements
5027** proxy locking is located much further down in the file. But we need
5028** to go ahead and define the sqlite3_io_methods and finder function
5029** for proxy locking here. So we forward declare the I/O methods.
5030*/
drhd2cb50b2009-01-09 21:41:17 +00005031#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005032static int proxyClose(sqlite3_file*);
5033static int proxyLock(sqlite3_file*, int);
5034static int proxyUnlock(sqlite3_file*, int);
5035static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005036IOMETHODS(
5037 proxyIoFinder, /* Finder function name */
5038 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005039 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005040 proxyClose, /* xClose method */
5041 proxyLock, /* xLock method */
5042 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005043 proxyCheckReservedLock, /* xCheckReservedLock method */
5044 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005045)
aswiftaebf4132008-11-21 00:10:35 +00005046#endif
drh7708e972008-11-29 00:56:52 +00005047
drh7ed97b92010-01-20 13:07:21 +00005048/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5049#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5050IOMETHODS(
5051 nfsIoFinder, /* Finder function name */
5052 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005053 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005054 unixClose, /* xClose method */
5055 unixLock, /* xLock method */
5056 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005057 unixCheckReservedLock, /* xCheckReservedLock method */
5058 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005059)
5060#endif
drh7708e972008-11-29 00:56:52 +00005061
drhd2cb50b2009-01-09 21:41:17 +00005062#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005063/*
drh6b9d6dd2008-12-03 19:34:47 +00005064** This "finder" function attempts to determine the best locking strategy
5065** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005066** object that implements that strategy.
5067**
5068** This is for MacOSX only.
5069*/
drh1875f7a2008-12-08 18:19:17 +00005070static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005071 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005072 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005073){
5074 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005075 const char *zFilesystem; /* Filesystem type name */
5076 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005077 } aMap[] = {
5078 { "hfs", &posixIoMethods },
5079 { "ufs", &posixIoMethods },
5080 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005081 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005082 { "webdav", &nolockIoMethods },
5083 { 0, 0 }
5084 };
5085 int i;
5086 struct statfs fsInfo;
5087 struct flock lockInfo;
5088
5089 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005090 /* If filePath==NULL that means we are dealing with a transient file
5091 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005092 return &nolockIoMethods;
5093 }
5094 if( statfs(filePath, &fsInfo) != -1 ){
5095 if( fsInfo.f_flags & MNT_RDONLY ){
5096 return &nolockIoMethods;
5097 }
5098 for(i=0; aMap[i].zFilesystem; i++){
5099 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5100 return aMap[i].pMethods;
5101 }
5102 }
5103 }
5104
5105 /* Default case. Handles, amongst others, "nfs".
5106 ** Test byte-range lock using fcntl(). If the call succeeds,
5107 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005108 */
drh7708e972008-11-29 00:56:52 +00005109 lockInfo.l_len = 1;
5110 lockInfo.l_start = 0;
5111 lockInfo.l_whence = SEEK_SET;
5112 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005113 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005114 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5115 return &nfsIoMethods;
5116 } else {
5117 return &posixIoMethods;
5118 }
drh7708e972008-11-29 00:56:52 +00005119 }else{
5120 return &dotlockIoMethods;
5121 }
5122}
drh0c2694b2009-09-03 16:23:44 +00005123static const sqlite3_io_methods
5124 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005125
drhd2cb50b2009-01-09 21:41:17 +00005126#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005127
drhe89b2912015-03-03 20:42:01 +00005128#if OS_VXWORKS
5129/*
5130** This "finder" function for VxWorks checks to see if posix advisory
5131** locking works. If it does, then that is what is used. If it does not
5132** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005133*/
drhe89b2912015-03-03 20:42:01 +00005134static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005135 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005136 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005137){
5138 struct flock lockInfo;
5139
5140 if( !filePath ){
5141 /* If filePath==NULL that means we are dealing with a transient file
5142 ** that does not need to be locked. */
5143 return &nolockIoMethods;
5144 }
5145
5146 /* Test if fcntl() is supported and use POSIX style locks.
5147 ** Otherwise fall back to the named semaphore method.
5148 */
5149 lockInfo.l_len = 1;
5150 lockInfo.l_start = 0;
5151 lockInfo.l_whence = SEEK_SET;
5152 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005153 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005154 return &posixIoMethods;
5155 }else{
5156 return &semIoMethods;
5157 }
5158}
drh0c2694b2009-09-03 16:23:44 +00005159static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005160 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005161
drhe89b2912015-03-03 20:42:01 +00005162#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005163
drh7708e972008-11-29 00:56:52 +00005164/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005165** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005166*/
drh0c2694b2009-09-03 16:23:44 +00005167typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005168
aswiftaebf4132008-11-21 00:10:35 +00005169
drh734c9862008-11-28 15:37:20 +00005170/****************************************************************************
5171**************************** sqlite3_vfs methods ****************************
5172**
5173** This division contains the implementation of methods on the
5174** sqlite3_vfs object.
5175*/
5176
danielk1977a3d4c882007-03-23 10:08:38 +00005177/*
danielk1977e339d652008-06-28 11:23:00 +00005178** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005179*/
5180static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005181 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005182 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005183 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005184 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005185 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005186){
drh7708e972008-11-29 00:56:52 +00005187 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005188 unixFile *pNew = (unixFile *)pId;
5189 int rc = SQLITE_OK;
5190
drh8af6c222010-05-14 12:43:01 +00005191 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005192
dan00157392010-10-05 11:33:15 +00005193 /* Usually the path zFilename should not be a relative pathname. The
5194 ** exception is when opening the proxy "conch" file in builds that
5195 ** include the special Apple locking styles.
5196 */
dan00157392010-10-05 11:33:15 +00005197#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005198 assert( zFilename==0 || zFilename[0]=='/'
5199 || pVfs->pAppData==(void*)&autolockIoFinder );
5200#else
5201 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005202#endif
dan00157392010-10-05 11:33:15 +00005203
drhb07028f2011-10-14 21:49:18 +00005204 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005205 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005206
drh308c2a52010-05-14 11:30:18 +00005207 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005208 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005209 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005210 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005211 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005212#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005213 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005214#endif
drhc02a43a2012-01-10 23:18:38 +00005215 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5216 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005217 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005218 }
drh503a6862013-03-01 01:07:17 +00005219 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005220 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005221 }
drh339eb0b2008-03-07 15:34:11 +00005222
drh6c7d5c52008-11-21 20:32:33 +00005223#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005224 pNew->pId = vxworksFindFileId(zFilename);
5225 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005226 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005227 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005228 }
5229#endif
5230
drhc02a43a2012-01-10 23:18:38 +00005231 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005232 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005233 }else{
drh0c2694b2009-09-03 16:23:44 +00005234 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005235#if SQLITE_ENABLE_LOCKING_STYLE
5236 /* Cache zFilename in the locking context (AFP and dotlock override) for
5237 ** proxyLock activation is possible (remote proxy is based on db name)
5238 ** zFilename remains valid until file is closed, to support */
5239 pNew->lockingContext = (void*)zFilename;
5240#endif
drhda0e7682008-07-30 15:27:54 +00005241 }
danielk1977e339d652008-06-28 11:23:00 +00005242
drh7ed97b92010-01-20 13:07:21 +00005243 if( pLockingStyle == &posixIoMethods
5244#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5245 || pLockingStyle == &nfsIoMethods
5246#endif
5247 ){
drh7708e972008-11-29 00:56:52 +00005248 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005249 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005250 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005251 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005252 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005253 ** in two scenarios:
5254 **
5255 ** (a) A call to fstat() failed.
5256 ** (b) A malloc failed.
5257 **
5258 ** Scenario (b) may only occur if the process is holding no other
5259 ** file descriptors open on the same file. If there were other file
5260 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005261 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005262 ** handle h - as it is guaranteed that no posix locks will be released
5263 ** by doing so.
5264 **
5265 ** If scenario (a) caused the error then things are not so safe. The
5266 ** implicit assumption here is that if fstat() fails, things are in
5267 ** such bad shape that dropping a lock or two doesn't matter much.
5268 */
drh0e9365c2011-03-02 02:08:13 +00005269 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005270 h = -1;
5271 }
drh7708e972008-11-29 00:56:52 +00005272 unixLeaveMutex();
5273 }
danielk1977e339d652008-06-28 11:23:00 +00005274
drhd2cb50b2009-01-09 21:41:17 +00005275#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005276 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005277 /* AFP locking uses the file path so it needs to be included in
5278 ** the afpLockingContext.
5279 */
5280 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005281 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005282 if( pCtx==0 ){
5283 rc = SQLITE_NOMEM;
5284 }else{
5285 /* NB: zFilename exists and remains valid until the file is closed
5286 ** according to requirement F11141. So we do not need to make a
5287 ** copy of the filename. */
5288 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005289 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005290 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005291 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005292 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005293 if( rc!=SQLITE_OK ){
5294 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005295 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005296 h = -1;
5297 }
drh7708e972008-11-29 00:56:52 +00005298 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005299 }
drh7708e972008-11-29 00:56:52 +00005300 }
5301#endif
danielk1977e339d652008-06-28 11:23:00 +00005302
drh7708e972008-11-29 00:56:52 +00005303 else if( pLockingStyle == &dotlockIoMethods ){
5304 /* Dotfile locking uses the file path so it needs to be included in
5305 ** the dotlockLockingContext
5306 */
5307 char *zLockFile;
5308 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005309 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005310 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005311 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005312 if( zLockFile==0 ){
5313 rc = SQLITE_NOMEM;
5314 }else{
5315 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005316 }
drh7708e972008-11-29 00:56:52 +00005317 pNew->lockingContext = zLockFile;
5318 }
danielk1977e339d652008-06-28 11:23:00 +00005319
drh6c7d5c52008-11-21 20:32:33 +00005320#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005321 else if( pLockingStyle == &semIoMethods ){
5322 /* Named semaphore locking uses the file path so it needs to be
5323 ** included in the semLockingContext
5324 */
5325 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005326 rc = findInodeInfo(pNew, &pNew->pInode);
5327 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5328 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005329 int n;
drh2238dcc2009-08-27 17:56:20 +00005330 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005331 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005332 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005333 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005334 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5335 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005336 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005337 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005338 }
chw97185482008-11-17 08:05:31 +00005339 }
drh7708e972008-11-29 00:56:52 +00005340 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005341 }
drh7708e972008-11-29 00:56:52 +00005342#endif
aswift5b1a2562008-08-22 00:22:35 +00005343
drh4bf66fd2015-02-19 02:43:02 +00005344 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005345#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005346 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005347 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005348 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005349 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005350 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005351 }
chw97185482008-11-17 08:05:31 +00005352#endif
danielk1977e339d652008-06-28 11:23:00 +00005353 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005354 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005355 }else{
drh7708e972008-11-29 00:56:52 +00005356 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005357 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005358 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005359 }
danielk1977e339d652008-06-28 11:23:00 +00005360 return rc;
drh054889e2005-11-30 03:20:31 +00005361}
drh9c06c952005-11-26 00:25:00 +00005362
danielk1977ad94b582007-08-20 06:44:22 +00005363/*
drh8b3cf822010-06-01 21:02:51 +00005364** Return the name of a directory in which to put temporary files.
5365** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005366*/
drh7234c6d2010-06-19 15:10:09 +00005367static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005368 static const char *azDirs[] = {
5369 0,
aswiftaebf4132008-11-21 00:10:35 +00005370 0,
danielk197717b90b52008-06-06 11:11:25 +00005371 "/var/tmp",
5372 "/usr/tmp",
5373 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005374 "."
danielk197717b90b52008-06-06 11:11:25 +00005375 };
drh8b3cf822010-06-01 21:02:51 +00005376 unsigned int i;
5377 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005378 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005379
drhb7e50ad2015-11-28 21:49:53 +00005380 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5381 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005382 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005383 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005384 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005385 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005386 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005387 break;
5388 }
5389 return zDir;
5390}
5391
5392/*
5393** Create a temporary file name in zBuf. zBuf must be allocated
5394** by the calling process and must be big enough to hold at least
5395** pVfs->mxPathname bytes.
5396*/
5397static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005398 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005399 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005400
5401 /* It's odd to simulate an io-error here, but really this is just
5402 ** using the io-error infrastructure to test that SQLite handles this
5403 ** function failing.
5404 */
5405 SimulateIOError( return SQLITE_IOERR );
5406
drh7234c6d2010-06-19 15:10:09 +00005407 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005408 do{
drh970942e2015-11-25 23:13:14 +00005409 u64 r;
5410 sqlite3_randomness(sizeof(r), &r);
5411 assert( nBuf>2 );
5412 zBuf[nBuf-2] = 0;
5413 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5414 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005415 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005416 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005417 return SQLITE_OK;
5418}
5419
drhd2cb50b2009-01-09 21:41:17 +00005420#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005421/*
5422** Routine to transform a unixFile into a proxy-locking unixFile.
5423** Implementation in the proxy-lock division, but used by unixOpen()
5424** if SQLITE_PREFER_PROXY_LOCKING is defined.
5425*/
5426static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005427#endif
drhc66d5b62008-12-03 22:48:32 +00005428
dan08da86a2009-08-21 17:18:03 +00005429/*
5430** Search for an unused file descriptor that was opened on the database
5431** file (not a journal or master-journal file) identified by pathname
5432** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5433** argument to this function.
5434**
5435** Such a file descriptor may exist if a database connection was closed
5436** but the associated file descriptor could not be closed because some
5437** other file descriptor open on the same file is holding a file-lock.
5438** Refer to comments in the unixClose() function and the lengthy comment
5439** describing "Posix Advisory Locking" at the start of this file for
5440** further details. Also, ticket #4018.
5441**
5442** If a suitable file descriptor is found, then it is returned. If no
5443** such file descriptor is located, -1 is returned.
5444*/
dane946c392009-08-22 11:39:46 +00005445static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5446 UnixUnusedFd *pUnused = 0;
5447
5448 /* Do not search for an unused file descriptor on vxworks. Not because
5449 ** vxworks would not benefit from the change (it might, we're not sure),
5450 ** but because no way to test it is currently available. It is better
5451 ** not to risk breaking vxworks support for the sake of such an obscure
5452 ** feature. */
5453#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005454 struct stat sStat; /* Results of stat() call */
5455
5456 /* A stat() call may fail for various reasons. If this happens, it is
5457 ** almost certain that an open() call on the same path will also fail.
5458 ** For this reason, if an error occurs in the stat() call here, it is
5459 ** ignored and -1 is returned. The caller will try to open a new file
5460 ** descriptor on the same path, fail, and return an error to SQLite.
5461 **
5462 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005463 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005464 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005465 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005466
5467 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005468 pInode = inodeList;
5469 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5470 || pInode->fileId.ino!=sStat.st_ino) ){
5471 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005472 }
drh8af6c222010-05-14 12:43:01 +00005473 if( pInode ){
dane946c392009-08-22 11:39:46 +00005474 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005475 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005476 pUnused = *pp;
5477 if( pUnused ){
5478 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005479 }
5480 }
5481 unixLeaveMutex();
5482 }
dane946c392009-08-22 11:39:46 +00005483#endif /* if !OS_VXWORKS */
5484 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005485}
danielk197717b90b52008-06-06 11:11:25 +00005486
5487/*
danddb0ac42010-07-14 14:48:58 +00005488** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005489** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005490** and a value suitable for passing as the third argument to open(2) is
5491** written to *pMode. If an IO error occurs, an SQLite error code is
5492** returned and the value of *pMode is not modified.
5493**
peter.d.reid60ec9142014-09-06 16:39:46 +00005494** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005495** an indication to robust_open() to create the file using
5496** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5497** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005498** this function queries the file-system for the permissions on the
5499** corresponding database file and sets *pMode to this value. Whenever
5500** possible, WAL and journal files are created using the same permissions
5501** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005502**
5503** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5504** original filename is unavailable. But 8_3_NAMES is only used for
5505** FAT filesystems and permissions do not matter there, so just use
5506** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005507*/
5508static int findCreateFileMode(
5509 const char *zPath, /* Path of file (possibly) being created */
5510 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005511 mode_t *pMode, /* OUT: Permissions to open file with */
5512 uid_t *pUid, /* OUT: uid to set on the file */
5513 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005514){
5515 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005516 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005517 *pUid = 0;
5518 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005519 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005520 char zDb[MAX_PATHNAME+1]; /* Database file path */
5521 int nDb; /* Number of valid bytes in zDb */
5522 struct stat sStat; /* Output of stat() on database file */
5523
dana0c989d2010-11-05 18:07:37 +00005524 /* zPath is a path to a WAL or journal file. The following block derives
5525 ** the path to the associated database file from zPath. This block handles
5526 ** the following naming conventions:
5527 **
5528 ** "<path to db>-journal"
5529 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005530 ** "<path to db>-journalNN"
5531 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005532 **
drhd337c5b2011-10-20 18:23:35 +00005533 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005534 ** used by the test_multiplex.c module.
5535 */
5536 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005537 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005538#ifndef SQLITE_ENABLE_8_3_NAMES
5539 /* In the normal case (8+3 filenames disabled) the journal filename
5540 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005541 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005542 assert( sqlite3Isalnum(zPath[nDb]) );
5543#else
5544 /* If 8+3 names are possible, then the journal file might not contain
5545 ** a '-' character. So check for that case and return early. */
5546 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5547#endif
drhc47167a2011-10-05 15:26:13 +00005548 nDb--;
5549 }
danddb0ac42010-07-14 14:48:58 +00005550 memcpy(zDb, zPath, nDb);
5551 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005552
drh58384f12011-07-28 00:14:45 +00005553 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005554 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005555 *pUid = sStat.st_uid;
5556 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005557 }else{
5558 rc = SQLITE_IOERR_FSTAT;
5559 }
5560 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5561 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005562 }
5563 return rc;
5564}
5565
5566/*
danielk1977ad94b582007-08-20 06:44:22 +00005567** Open the file zPath.
5568**
danielk1977b4b47412007-08-17 15:53:36 +00005569** Previously, the SQLite OS layer used three functions in place of this
5570** one:
5571**
5572** sqlite3OsOpenReadWrite();
5573** sqlite3OsOpenReadOnly();
5574** sqlite3OsOpenExclusive();
5575**
5576** These calls correspond to the following combinations of flags:
5577**
5578** ReadWrite() -> (READWRITE | CREATE)
5579** ReadOnly() -> (READONLY)
5580** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5581**
5582** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5583** true, the file was configured to be automatically deleted when the
5584** file handle closed. To achieve the same effect using this new
5585** interface, add the DELETEONCLOSE flag to those specified above for
5586** OpenExclusive().
5587*/
5588static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005589 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5590 const char *zPath, /* Pathname of file to be opened */
5591 sqlite3_file *pFile, /* The file descriptor to be filled in */
5592 int flags, /* Input flags to control the opening */
5593 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005594){
dan08da86a2009-08-21 17:18:03 +00005595 unixFile *p = (unixFile *)pFile;
5596 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005597 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005598 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005599 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005600 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005601 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005602
5603 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5604 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5605 int isCreate = (flags & SQLITE_OPEN_CREATE);
5606 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5607 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005608#if SQLITE_ENABLE_LOCKING_STYLE
5609 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5610#endif
drh3d4435b2011-08-26 20:55:50 +00005611#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5612 struct statfs fsInfo;
5613#endif
danielk1977b4b47412007-08-17 15:53:36 +00005614
danielk1977fee2d252007-08-18 10:59:19 +00005615 /* If creating a master or main-file journal, this function will open
5616 ** a file-descriptor on the directory too. The first time unixSync()
5617 ** is called the directory file descriptor will be fsync()ed and close()d.
5618 */
drh0059eae2011-08-08 23:48:40 +00005619 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005620 eType==SQLITE_OPEN_MASTER_JOURNAL
5621 || eType==SQLITE_OPEN_MAIN_JOURNAL
5622 || eType==SQLITE_OPEN_WAL
5623 ));
danielk1977fee2d252007-08-18 10:59:19 +00005624
danielk197717b90b52008-06-06 11:11:25 +00005625 /* If argument zPath is a NULL pointer, this function is required to open
5626 ** a temporary file. Use this buffer to store the file name in.
5627 */
drhc02a43a2012-01-10 23:18:38 +00005628 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005629 const char *zName = zPath;
5630
danielk1977fee2d252007-08-18 10:59:19 +00005631 /* Check the following statements are true:
5632 **
5633 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5634 ** (b) if CREATE is set, then READWRITE must also be set, and
5635 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005636 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005637 */
danielk1977b4b47412007-08-17 15:53:36 +00005638 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005639 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005640 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005641 assert(isDelete==0 || isCreate);
5642
danddb0ac42010-07-14 14:48:58 +00005643 /* The main DB, main journal, WAL file and master journal are never
5644 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005645 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5646 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5647 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005648 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005649
danielk1977fee2d252007-08-18 10:59:19 +00005650 /* Assert that the upper layer has set one of the "file-type" flags. */
5651 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5652 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5653 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005654 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005655 );
5656
drhb00d8622014-01-01 15:18:36 +00005657 /* Detect a pid change and reset the PRNG. There is a race condition
5658 ** here such that two or more threads all trying to open databases at
5659 ** the same instant might all reset the PRNG. But multiple resets
5660 ** are harmless.
5661 */
drh5ac93652015-03-21 20:59:43 +00005662 if( randomnessPid!=osGetpid(0) ){
5663 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005664 sqlite3_randomness(0,0);
5665 }
5666
dan08da86a2009-08-21 17:18:03 +00005667 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005668
dan08da86a2009-08-21 17:18:03 +00005669 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005670 UnixUnusedFd *pUnused;
5671 pUnused = findReusableFd(zName, flags);
5672 if( pUnused ){
5673 fd = pUnused->fd;
5674 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005675 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005676 if( !pUnused ){
5677 return SQLITE_NOMEM;
5678 }
5679 }
5680 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005681
5682 /* Database filenames are double-zero terminated if they are not
5683 ** URIs with parameters. Hence, they can always be passed into
5684 ** sqlite3_uri_parameter(). */
5685 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5686
dan08da86a2009-08-21 17:18:03 +00005687 }else if( !zName ){
5688 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005689 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005690 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005691 if( rc!=SQLITE_OK ){
5692 return rc;
5693 }
5694 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005695
5696 /* Generated temporary filenames are always double-zero terminated
5697 ** for use by sqlite3_uri_parameter(). */
5698 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005699 }
5700
dan08da86a2009-08-21 17:18:03 +00005701 /* Determine the value of the flags parameter passed to POSIX function
5702 ** open(). These must be calculated even if open() is not called, as
5703 ** they may be stored as part of the file handle and used by the
5704 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005705 if( isReadonly ) openFlags |= O_RDONLY;
5706 if( isReadWrite ) openFlags |= O_RDWR;
5707 if( isCreate ) openFlags |= O_CREAT;
5708 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5709 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005710
danielk1977b4b47412007-08-17 15:53:36 +00005711 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005712 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005713 uid_t uid; /* Userid for the file */
5714 gid_t gid; /* Groupid for the file */
5715 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005716 if( rc!=SQLITE_OK ){
5717 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005718 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005719 return rc;
5720 }
drhad4f1e52011-03-04 15:43:57 +00005721 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005722 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005723 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5724 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005725 /* Failed to open the file for read/write access. Try read-only. */
5726 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005727 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005728 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005729 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005730 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005731 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005732 }
5733 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005734 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005735 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005736 }
drhac7c3ac2012-02-11 19:23:48 +00005737
5738 /* If this process is running as root and if creating a new rollback
5739 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005740 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005741 */
5742 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005743 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005744 }
danielk1977b4b47412007-08-17 15:53:36 +00005745 }
dan08da86a2009-08-21 17:18:03 +00005746 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005747 if( pOutFlags ){
5748 *pOutFlags = flags;
5749 }
5750
dane946c392009-08-22 11:39:46 +00005751 if( p->pUnused ){
5752 p->pUnused->fd = fd;
5753 p->pUnused->flags = flags;
5754 }
5755
danielk1977b4b47412007-08-17 15:53:36 +00005756 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005757#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005758 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005759#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5760 zPath = sqlite3_mprintf("%s", zName);
5761 if( zPath==0 ){
5762 robust_close(p, fd, __LINE__);
5763 return SQLITE_NOMEM;
5764 }
chw97185482008-11-17 08:05:31 +00005765#else
drh036ac7f2011-08-08 23:18:05 +00005766 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005767#endif
danielk1977b4b47412007-08-17 15:53:36 +00005768 }
drh41022642008-11-21 00:24:42 +00005769#if SQLITE_ENABLE_LOCKING_STYLE
5770 else{
dan08da86a2009-08-21 17:18:03 +00005771 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005772 }
5773#endif
5774
drhda0e7682008-07-30 15:27:54 +00005775 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005776
drh7ed97b92010-01-20 13:07:21 +00005777
5778#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005779 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005780 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005781 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005782 return SQLITE_IOERR_ACCESS;
5783 }
5784 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5785 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5786 }
drh4bf66fd2015-02-19 02:43:02 +00005787 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5788 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5789 }
drh7ed97b92010-01-20 13:07:21 +00005790#endif
drhc02a43a2012-01-10 23:18:38 +00005791
5792 /* Set up appropriate ctrlFlags */
5793 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5794 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5795 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5796 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5797 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5798
drh7ed97b92010-01-20 13:07:21 +00005799#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005800#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005801 isAutoProxy = 1;
5802#endif
5803 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005804 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5805 int useProxy = 0;
5806
dan08da86a2009-08-21 17:18:03 +00005807 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5808 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005809 if( envforce!=NULL ){
5810 useProxy = atoi(envforce)>0;
5811 }else{
aswiftaebf4132008-11-21 00:10:35 +00005812 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5813 }
5814 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005815 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005816 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005817 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005818 if( rc!=SQLITE_OK ){
5819 /* Use unixClose to clean up the resources added in fillInUnixFile
5820 ** and clear all the structure's references. Specifically,
5821 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5822 */
5823 unixClose(pFile);
5824 return rc;
5825 }
aswiftaebf4132008-11-21 00:10:35 +00005826 }
dane946c392009-08-22 11:39:46 +00005827 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005828 }
5829 }
5830#endif
5831
drhc02a43a2012-01-10 23:18:38 +00005832 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5833
dane946c392009-08-22 11:39:46 +00005834open_finished:
5835 if( rc!=SQLITE_OK ){
5836 sqlite3_free(p->pUnused);
5837 }
5838 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005839}
5840
dane946c392009-08-22 11:39:46 +00005841
danielk1977b4b47412007-08-17 15:53:36 +00005842/*
danielk1977fee2d252007-08-18 10:59:19 +00005843** Delete the file at zPath. If the dirSync argument is true, fsync()
5844** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005845*/
drh6b9d6dd2008-12-03 19:34:47 +00005846static int unixDelete(
5847 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5848 const char *zPath, /* Name of file to be deleted */
5849 int dirSync /* If true, fsync() directory after deleting file */
5850){
danielk1977fee2d252007-08-18 10:59:19 +00005851 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005852 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005853 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005854 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005855 if( errno==ENOENT
5856#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005857 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005858#endif
5859 ){
dan9fc5b4a2012-11-09 20:17:26 +00005860 rc = SQLITE_IOERR_DELETE_NOENT;
5861 }else{
drhb4308162012-11-09 21:40:02 +00005862 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005863 }
drhb4308162012-11-09 21:40:02 +00005864 return rc;
drh5d4feff2010-07-14 01:45:22 +00005865 }
danielk1977d39fa702008-10-16 13:27:40 +00005866#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005867 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005868 int fd;
drh90315a22011-08-10 01:52:12 +00005869 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005870 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005871#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005872 if( fsync(fd)==-1 )
5873#else
5874 if( fsync(fd) )
5875#endif
5876 {
dane18d4952011-02-21 11:46:24 +00005877 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005878 }
drh0e9365c2011-03-02 02:08:13 +00005879 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005880 }else{
5881 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005882 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005883 }
5884 }
danielk1977d138dd82008-10-15 16:02:48 +00005885#endif
danielk1977fee2d252007-08-18 10:59:19 +00005886 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005887}
5888
danielk197790949c22007-08-17 16:50:38 +00005889/*
mistachkin48864df2013-03-21 21:20:32 +00005890** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005891** test performed depends on the value of flags:
5892**
5893** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5894** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5895** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5896**
5897** Otherwise return 0.
5898*/
danielk1977861f7452008-06-05 11:39:11 +00005899static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005900 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5901 const char *zPath, /* Path of the file to examine */
5902 int flags, /* What do we want to learn about the zPath file? */
5903 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005904){
danielk1977397d65f2008-11-19 11:35:39 +00005905 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005906 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005907 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005908
drhd260b5b2015-11-25 18:03:33 +00005909 /* The spec says there are three possible values for flags. But only
5910 ** two of them are actually used */
5911 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5912
5913 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005914 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005915 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5916 }else{
5917 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005918 }
danielk1977861f7452008-06-05 11:39:11 +00005919 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005920}
5921
danielk1977b4b47412007-08-17 15:53:36 +00005922
5923/*
5924** Turn a relative pathname into a full pathname. The relative path
5925** is stored as a nul-terminated string in the buffer pointed to by
5926** zPath.
5927**
5928** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5929** (in this case, MAX_PATHNAME bytes). The full-path is written to
5930** this buffer before returning.
5931*/
danielk1977adfb9b02007-09-17 07:02:56 +00005932static int unixFullPathname(
5933 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5934 const char *zPath, /* Possibly relative input path */
5935 int nOut, /* Size of output buffer in bytes */
5936 char *zOut /* Output buffer */
5937){
dan245fdc62015-10-31 17:58:33 +00005938 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005939
5940 /* It's odd to simulate an io-error here, but really this is just
5941 ** using the io-error infrastructure to test that SQLite handles this
5942 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005943 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005944 */
5945 SimulateIOError( return SQLITE_ERROR );
5946
drh153c62c2007-08-24 03:51:33 +00005947 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005948 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005949
dan245fdc62015-10-31 17:58:33 +00005950 /* Attempt to resolve the path as if it were a symbolic link. If it is
5951 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5952 ** the identified file is not a symbolic link or does not exist, then
5953 ** zPath is copied directly into zOut. Either way, nByte is left set to
5954 ** the size of the string copied into zOut[] in bytes. */
5955 nByte = osReadlink(zPath, zOut, nOut-1);
5956 if( nByte<0 ){
5957 if( errno!=EINVAL && errno!=ENOENT ){
5958 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5959 }
drhd260b5b2015-11-25 18:03:33 +00005960 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005961 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005962 }else{
dan245fdc62015-10-31 17:58:33 +00005963 zOut[nByte] = '\0';
5964 }
5965
5966 /* If buffer zOut[] now contains an absolute path there is nothing more
5967 ** to do. If it contains a relative path, do the following:
5968 **
5969 ** * move the relative path string so that it is at the end of th
5970 ** zOut[] buffer.
5971 ** * Call getcwd() to read the path of the current working directory
5972 ** into the start of the zOut[] buffer.
5973 ** * Append a '/' character to the cwd string and move the
5974 ** relative path back within the buffer so that it immediately
5975 ** follows the '/'.
5976 **
5977 ** This code is written so that if the combination of the CWD and relative
5978 ** path are larger than the allocated size of zOut[] the CWD is silently
5979 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5980 ** file for which this function returns a full path larger than (nOut-8)
5981 ** bytes in size. */
drh025d2f72015-11-30 22:22:23 +00005982 testcase( nByte==nOut-5 );
5983 testcase( nByte==nOut-4 );
5984 if( zOut[0]!='/' && nByte<nOut-4 ){
danielk1977b4b47412007-08-17 15:53:36 +00005985 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005986 int nRem = nOut-nByte-1;
5987 memmove(&zOut[nRem], zOut, nByte+1);
5988 zOut[nRem-1] = '\0';
5989 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005990 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005991 }
dan245fdc62015-10-31 17:58:33 +00005992 nCwd = sqlite3Strlen30(zOut);
5993 assert( nCwd<=nRem-1 );
5994 zOut[nCwd] = '/';
5995 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00005996 }
dan245fdc62015-10-31 17:58:33 +00005997
danielk1977b4b47412007-08-17 15:53:36 +00005998 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005999}
6000
drh0ccebe72005-06-07 22:22:50 +00006001
drh761df872006-12-21 01:29:22 +00006002#ifndef SQLITE_OMIT_LOAD_EXTENSION
6003/*
6004** Interfaces for opening a shared library, finding entry points
6005** within the shared library, and closing the shared library.
6006*/
6007#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006008static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6009 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006010 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6011}
danielk197795c8a542007-09-01 06:51:27 +00006012
6013/*
6014** SQLite calls this function immediately after a call to unixDlSym() or
6015** unixDlOpen() fails (returns a null pointer). If a more detailed error
6016** message is available, it is written to zBufOut. If no error message
6017** is available, zBufOut is left unmodified and SQLite uses a default
6018** error message.
6019*/
danielk1977397d65f2008-11-19 11:35:39 +00006020static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006021 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006022 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006023 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006024 zErr = dlerror();
6025 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006026 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006027 }
drh6c7d5c52008-11-21 20:32:33 +00006028 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006029}
drh1875f7a2008-12-08 18:19:17 +00006030static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6031 /*
6032 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6033 ** cast into a pointer to a function. And yet the library dlsym() routine
6034 ** returns a void* which is really a pointer to a function. So how do we
6035 ** use dlsym() with -pedantic-errors?
6036 **
6037 ** Variable x below is defined to be a pointer to a function taking
6038 ** parameters void* and const char* and returning a pointer to a function.
6039 ** We initialize x by assigning it a pointer to the dlsym() function.
6040 ** (That assignment requires a cast.) Then we call the function that
6041 ** x points to.
6042 **
6043 ** This work-around is unlikely to work correctly on any system where
6044 ** you really cannot cast a function pointer into void*. But then, on the
6045 ** other hand, dlsym() will not work on such a system either, so we have
6046 ** not really lost anything.
6047 */
6048 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006049 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006050 x = (void(*(*)(void*,const char*))(void))dlsym;
6051 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006052}
danielk1977397d65f2008-11-19 11:35:39 +00006053static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6054 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006055 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006056}
danielk1977b4b47412007-08-17 15:53:36 +00006057#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6058 #define unixDlOpen 0
6059 #define unixDlError 0
6060 #define unixDlSym 0
6061 #define unixDlClose 0
6062#endif
6063
6064/*
danielk197790949c22007-08-17 16:50:38 +00006065** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006066*/
danielk1977397d65f2008-11-19 11:35:39 +00006067static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6068 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006069 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006070
drhbbd42a62004-05-22 17:41:58 +00006071 /* We have to initialize zBuf to prevent valgrind from reporting
6072 ** errors. The reports issued by valgrind are incorrect - we would
6073 ** prefer that the randomness be increased by making use of the
6074 ** uninitialized space in zBuf - but valgrind errors tend to worry
6075 ** some users. Rather than argue, it seems easier just to initialize
6076 ** the whole array and silence valgrind, even if that means less randomness
6077 ** in the random seed.
6078 **
6079 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006080 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006081 ** tests repeatable.
6082 */
danielk1977b4b47412007-08-17 15:53:36 +00006083 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006084 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006085#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006086 {
drhb00d8622014-01-01 15:18:36 +00006087 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006088 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006089 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006090 time_t t;
6091 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006092 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006093 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6094 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6095 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006096 }else{
drhc18b4042012-02-10 03:10:27 +00006097 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006098 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006099 }
drhbbd42a62004-05-22 17:41:58 +00006100 }
6101#endif
drh72cbd072008-10-14 17:58:38 +00006102 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006103}
6104
danielk1977b4b47412007-08-17 15:53:36 +00006105
drhbbd42a62004-05-22 17:41:58 +00006106/*
6107** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006108** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006109** The return value is the number of microseconds of sleep actually
6110** requested from the underlying operating system, a number which
6111** might be greater than or equal to the argument, but not less
6112** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006113*/
danielk1977397d65f2008-11-19 11:35:39 +00006114static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006115#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006116 struct timespec sp;
6117
6118 sp.tv_sec = microseconds / 1000000;
6119 sp.tv_nsec = (microseconds % 1000000) * 1000;
6120 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006121 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006122 return microseconds;
6123#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006124 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006125 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006126 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006127#else
danielk1977b4b47412007-08-17 15:53:36 +00006128 int seconds = (microseconds+999999)/1000000;
6129 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006130 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006131 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006132#endif
drh88f474a2006-01-02 20:00:12 +00006133}
6134
6135/*
drh6b9d6dd2008-12-03 19:34:47 +00006136** The following variable, if set to a non-zero value, is interpreted as
6137** the number of seconds since 1970 and is used to set the result of
6138** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006139*/
6140#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006141int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006142#endif
6143
6144/*
drhb7e8ea22010-05-03 14:32:30 +00006145** Find the current time (in Universal Coordinated Time). Write into *piNow
6146** the current time and date as a Julian Day number times 86_400_000. In
6147** other words, write into *piNow the number of milliseconds since the Julian
6148** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6149** proleptic Gregorian calendar.
6150**
drh31702252011-10-12 23:13:43 +00006151** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6152** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006153*/
6154static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6155 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006156 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006157#if defined(NO_GETTOD)
6158 time_t t;
6159 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006160 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006161#elif OS_VXWORKS
6162 struct timespec sNow;
6163 clock_gettime(CLOCK_REALTIME, &sNow);
6164 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6165#else
6166 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006167 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6168 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006169#endif
6170
6171#ifdef SQLITE_TEST
6172 if( sqlite3_current_time ){
6173 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6174 }
6175#endif
6176 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006177 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006178}
6179
drh5337dac2015-11-25 15:15:03 +00006180#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006181/*
drhbbd42a62004-05-22 17:41:58 +00006182** Find the current time (in Universal Coordinated Time). Write the
6183** current time and date as a Julian Day number into *prNow and
6184** return 0. Return 1 if the time and date cannot be found.
6185*/
danielk1977397d65f2008-11-19 11:35:39 +00006186static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006187 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006188 int rc;
drhff828942010-06-26 21:34:06 +00006189 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006190 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006191 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006192 return rc;
drhbbd42a62004-05-22 17:41:58 +00006193}
drh5337dac2015-11-25 15:15:03 +00006194#else
6195# define unixCurrentTime 0
6196#endif
danielk1977b4b47412007-08-17 15:53:36 +00006197
drh5337dac2015-11-25 15:15:03 +00006198#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006199/*
6200** We added the xGetLastError() method with the intention of providing
6201** better low-level error messages when operating-system problems come up
6202** during SQLite operation. But so far, none of that has been implemented
6203** in the core. So this routine is never called. For now, it is merely
6204** a place-holder.
6205*/
danielk1977397d65f2008-11-19 11:35:39 +00006206static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6207 UNUSED_PARAMETER(NotUsed);
6208 UNUSED_PARAMETER(NotUsed2);
6209 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006210 return 0;
6211}
drh5337dac2015-11-25 15:15:03 +00006212#else
6213# define unixGetLastError 0
6214#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006215
drhf2424c52010-04-26 00:04:55 +00006216
6217/*
drh734c9862008-11-28 15:37:20 +00006218************************ End of sqlite3_vfs methods ***************************
6219******************************************************************************/
6220
drh715ff302008-12-03 22:32:44 +00006221/******************************************************************************
6222************************** Begin Proxy Locking ********************************
6223**
6224** Proxy locking is a "uber-locking-method" in this sense: It uses the
6225** other locking methods on secondary lock files. Proxy locking is a
6226** meta-layer over top of the primitive locking implemented above. For
6227** this reason, the division that implements of proxy locking is deferred
6228** until late in the file (here) after all of the other I/O methods have
6229** been defined - so that the primitive locking methods are available
6230** as services to help with the implementation of proxy locking.
6231**
6232****
6233**
6234** The default locking schemes in SQLite use byte-range locks on the
6235** database file to coordinate safe, concurrent access by multiple readers
6236** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6237** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6238** as POSIX read & write locks over fixed set of locations (via fsctl),
6239** on AFP and SMB only exclusive byte-range locks are available via fsctl
6240** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6241** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6242** address in the shared range is taken for a SHARED lock, the entire
6243** shared range is taken for an EXCLUSIVE lock):
6244**
drhf2f105d2012-08-20 15:53:54 +00006245** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006246** RESERVED_BYTE 0x40000001
6247** SHARED_RANGE 0x40000002 -> 0x40000200
6248**
6249** This works well on the local file system, but shows a nearly 100x
6250** slowdown in read performance on AFP because the AFP client disables
6251** the read cache when byte-range locks are present. Enabling the read
6252** cache exposes a cache coherency problem that is present on all OS X
6253** supported network file systems. NFS and AFP both observe the
6254** close-to-open semantics for ensuring cache coherency
6255** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6256** address the requirements for concurrent database access by multiple
6257** readers and writers
6258** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6259**
6260** To address the performance and cache coherency issues, proxy file locking
6261** changes the way database access is controlled by limiting access to a
6262** single host at a time and moving file locks off of the database file
6263** and onto a proxy file on the local file system.
6264**
6265**
6266** Using proxy locks
6267** -----------------
6268**
6269** C APIs
6270**
drh4bf66fd2015-02-19 02:43:02 +00006271** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006272** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006273** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6274** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006275**
6276**
6277** SQL pragmas
6278**
6279** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6280** PRAGMA [database.]lock_proxy_file
6281**
6282** Specifying ":auto:" means that if there is a conch file with a matching
6283** host ID in it, the proxy path in the conch file will be used, otherwise
6284** a proxy path based on the user's temp dir
6285** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6286** actual proxy file name is generated from the name and path of the
6287** database file. For example:
6288**
6289** For database path "/Users/me/foo.db"
6290** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6291**
6292** Once a lock proxy is configured for a database connection, it can not
6293** be removed, however it may be switched to a different proxy path via
6294** the above APIs (assuming the conch file is not being held by another
6295** connection or process).
6296**
6297**
6298** How proxy locking works
6299** -----------------------
6300**
6301** Proxy file locking relies primarily on two new supporting files:
6302**
6303** * conch file to limit access to the database file to a single host
6304** at a time
6305**
6306** * proxy file to act as a proxy for the advisory locks normally
6307** taken on the database
6308**
6309** The conch file - to use a proxy file, sqlite must first "hold the conch"
6310** by taking an sqlite-style shared lock on the conch file, reading the
6311** contents and comparing the host's unique host ID (see below) and lock
6312** proxy path against the values stored in the conch. The conch file is
6313** stored in the same directory as the database file and the file name
6314** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006315** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006316** host ID and/or proxy path, then the lock is escalated to an exclusive
6317** lock and the conch file contents is updated with the host ID and proxy
6318** path and the lock is downgraded to a shared lock again. If the conch
6319** is held by another process (with a shared lock), the exclusive lock
6320** will fail and SQLITE_BUSY is returned.
6321**
6322** The proxy file - a single-byte file used for all advisory file locks
6323** normally taken on the database file. This allows for safe sharing
6324** of the database file for multiple readers and writers on the same
6325** host (the conch ensures that they all use the same local lock file).
6326**
drh715ff302008-12-03 22:32:44 +00006327** Requesting the lock proxy does not immediately take the conch, it is
6328** only taken when the first request to lock database file is made.
6329** This matches the semantics of the traditional locking behavior, where
6330** opening a connection to a database file does not take a lock on it.
6331** The shared lock and an open file descriptor are maintained until
6332** the connection to the database is closed.
6333**
6334** The proxy file and the lock file are never deleted so they only need
6335** to be created the first time they are used.
6336**
6337** Configuration options
6338** ---------------------
6339**
6340** SQLITE_PREFER_PROXY_LOCKING
6341**
6342** Database files accessed on non-local file systems are
6343** automatically configured for proxy locking, lock files are
6344** named automatically using the same logic as
6345** PRAGMA lock_proxy_file=":auto:"
6346**
6347** SQLITE_PROXY_DEBUG
6348**
6349** Enables the logging of error messages during host id file
6350** retrieval and creation
6351**
drh715ff302008-12-03 22:32:44 +00006352** LOCKPROXYDIR
6353**
6354** Overrides the default directory used for lock proxy files that
6355** are named automatically via the ":auto:" setting
6356**
6357** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6358**
6359** Permissions to use when creating a directory for storing the
6360** lock proxy files, only used when LOCKPROXYDIR is not set.
6361**
6362**
6363** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6364** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6365** force proxy locking to be used for every database file opened, and 0
6366** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006367** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006368** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6369*/
6370
6371/*
6372** Proxy locking is only available on MacOSX
6373*/
drhd2cb50b2009-01-09 21:41:17 +00006374#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006375
drh715ff302008-12-03 22:32:44 +00006376/*
6377** The proxyLockingContext has the path and file structures for the remote
6378** and local proxy files in it
6379*/
6380typedef struct proxyLockingContext proxyLockingContext;
6381struct proxyLockingContext {
6382 unixFile *conchFile; /* Open conch file */
6383 char *conchFilePath; /* Name of the conch file */
6384 unixFile *lockProxy; /* Open proxy lock file */
6385 char *lockProxyPath; /* Name of the proxy lock file */
6386 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006387 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006388 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006389 void *oldLockingContext; /* Original lockingcontext to restore on close */
6390 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6391};
6392
drh7ed97b92010-01-20 13:07:21 +00006393/*
6394** The proxy lock file path for the database at dbPath is written into lPath,
6395** which must point to valid, writable memory large enough for a maxLen length
6396** file path.
drh715ff302008-12-03 22:32:44 +00006397*/
drh715ff302008-12-03 22:32:44 +00006398static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6399 int len;
6400 int dbLen;
6401 int i;
6402
6403#ifdef LOCKPROXYDIR
6404 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6405#else
6406# ifdef _CS_DARWIN_USER_TEMP_DIR
6407 {
drh7ed97b92010-01-20 13:07:21 +00006408 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006409 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006410 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006411 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006412 }
drh7ed97b92010-01-20 13:07:21 +00006413 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006414 }
6415# else
6416 len = strlcpy(lPath, "/tmp/", maxLen);
6417# endif
6418#endif
6419
6420 if( lPath[len-1]!='/' ){
6421 len = strlcat(lPath, "/", maxLen);
6422 }
6423
6424 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006425 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006426 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006427 char c = dbPath[i];
6428 lPath[i+len] = (c=='/')?'_':c;
6429 }
6430 lPath[i+len]='\0';
6431 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006432 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006433 return SQLITE_OK;
6434}
6435
drh7ed97b92010-01-20 13:07:21 +00006436/*
6437 ** Creates the lock file and any missing directories in lockPath
6438 */
6439static int proxyCreateLockPath(const char *lockPath){
6440 int i, len;
6441 char buf[MAXPATHLEN];
6442 int start = 0;
6443
6444 assert(lockPath!=NULL);
6445 /* try to create all the intermediate directories */
6446 len = (int)strlen(lockPath);
6447 buf[0] = lockPath[0];
6448 for( i=1; i<len; i++ ){
6449 if( lockPath[i] == '/' && (i - start > 0) ){
6450 /* only mkdir if leaf dir != "." or "/" or ".." */
6451 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6452 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6453 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006454 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006455 int err=errno;
6456 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006457 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006458 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006459 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006460 return err;
6461 }
6462 }
6463 }
6464 start=i+1;
6465 }
6466 buf[i] = lockPath[i];
6467 }
drh62aaa6c2015-11-21 17:27:42 +00006468 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006469 return 0;
6470}
6471
drh715ff302008-12-03 22:32:44 +00006472/*
6473** Create a new VFS file descriptor (stored in memory obtained from
6474** sqlite3_malloc) and open the file named "path" in the file descriptor.
6475**
6476** The caller is responsible not only for closing the file descriptor
6477** but also for freeing the memory associated with the file descriptor.
6478*/
drh7ed97b92010-01-20 13:07:21 +00006479static int proxyCreateUnixFile(
6480 const char *path, /* path for the new unixFile */
6481 unixFile **ppFile, /* unixFile created and returned by ref */
6482 int islockfile /* if non zero missing dirs will be created */
6483) {
6484 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006485 unixFile *pNew;
6486 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006487 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006488 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006489 int terrno = 0;
6490 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006491
drh7ed97b92010-01-20 13:07:21 +00006492 /* 1. first try to open/create the file
6493 ** 2. if that fails, and this is a lock file (not-conch), try creating
6494 ** the parent directories and then try again.
6495 ** 3. if that fails, try to open the file read-only
6496 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6497 */
6498 pUnused = findReusableFd(path, openFlags);
6499 if( pUnused ){
6500 fd = pUnused->fd;
6501 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006502 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006503 if( !pUnused ){
6504 return SQLITE_NOMEM;
6505 }
6506 }
6507 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006508 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006509 terrno = errno;
6510 if( fd<0 && errno==ENOENT && islockfile ){
6511 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006512 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006513 }
6514 }
6515 }
6516 if( fd<0 ){
6517 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006518 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006519 terrno = errno;
6520 }
6521 if( fd<0 ){
6522 if( islockfile ){
6523 return SQLITE_BUSY;
6524 }
6525 switch (terrno) {
6526 case EACCES:
6527 return SQLITE_PERM;
6528 case EIO:
6529 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6530 default:
drh9978c972010-02-23 17:36:32 +00006531 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006532 }
6533 }
6534
drhf3cdcdc2015-04-29 16:50:28 +00006535 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006536 if( pNew==NULL ){
6537 rc = SQLITE_NOMEM;
6538 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006539 }
6540 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006541 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006542 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006543 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006544 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006545 pUnused->fd = fd;
6546 pUnused->flags = openFlags;
6547 pNew->pUnused = pUnused;
6548
drhc02a43a2012-01-10 23:18:38 +00006549 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006550 if( rc==SQLITE_OK ){
6551 *ppFile = pNew;
6552 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006553 }
drh7ed97b92010-01-20 13:07:21 +00006554end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006555 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006556 sqlite3_free(pNew);
6557 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006558 return rc;
6559}
6560
drh7ed97b92010-01-20 13:07:21 +00006561#ifdef SQLITE_TEST
6562/* simulate multiple hosts by creating unique hostid file paths */
6563int sqlite3_hostid_num = 0;
6564#endif
6565
6566#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6567
drh6bca6512015-04-13 23:05:28 +00006568#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006569/* Not always defined in the headers as it ought to be */
6570extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006571#endif
drh0ab216a2010-07-02 17:10:40 +00006572
drh7ed97b92010-01-20 13:07:21 +00006573/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6574** bytes of writable memory.
6575*/
6576static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006577 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6578 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006579#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006580 {
drh4bf66fd2015-02-19 02:43:02 +00006581 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006582 if( gethostuuid(pHostID, &timeout) ){
6583 int err = errno;
6584 if( pError ){
6585 *pError = err;
6586 }
6587 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006588 }
drh7ed97b92010-01-20 13:07:21 +00006589 }
drh3d4435b2011-08-26 20:55:50 +00006590#else
6591 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006592#endif
drh7ed97b92010-01-20 13:07:21 +00006593#ifdef SQLITE_TEST
6594 /* simulate multiple hosts by creating unique hostid file paths */
6595 if( sqlite3_hostid_num != 0){
6596 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6597 }
6598#endif
6599
6600 return SQLITE_OK;
6601}
6602
6603/* The conch file contains the header, host id and lock file path
6604 */
6605#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6606#define PROXY_HEADERLEN 1 /* conch file header length */
6607#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6608#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6609
6610/*
6611** Takes an open conch file, copies the contents to a new path and then moves
6612** it back. The newly created file's file descriptor is assigned to the
6613** conch file structure and finally the original conch file descriptor is
6614** closed. Returns zero if successful.
6615*/
6616static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6617 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6618 unixFile *conchFile = pCtx->conchFile;
6619 char tPath[MAXPATHLEN];
6620 char buf[PROXY_MAXCONCHLEN];
6621 char *cPath = pCtx->conchFilePath;
6622 size_t readLen = 0;
6623 size_t pathLen = 0;
6624 char errmsg[64] = "";
6625 int fd = -1;
6626 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006627 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006628
6629 /* create a new path by replace the trailing '-conch' with '-break' */
6630 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6631 if( pathLen>MAXPATHLEN || pathLen<6 ||
6632 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006633 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006634 goto end_breaklock;
6635 }
6636 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006637 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006638 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006639 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006640 goto end_breaklock;
6641 }
6642 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006643 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006644 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006645 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006646 goto end_breaklock;
6647 }
drhe562be52011-03-02 18:01:10 +00006648 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006649 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006650 goto end_breaklock;
6651 }
6652 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006653 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006654 goto end_breaklock;
6655 }
6656 rc = 0;
6657 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006658 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006659 conchFile->h = fd;
6660 conchFile->openFlags = O_RDWR | O_CREAT;
6661
6662end_breaklock:
6663 if( rc ){
6664 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006665 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006666 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006667 }
6668 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6669 }
6670 return rc;
6671}
6672
6673/* Take the requested lock on the conch file and break a stale lock if the
6674** host id matches.
6675*/
6676static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6677 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6678 unixFile *conchFile = pCtx->conchFile;
6679 int rc = SQLITE_OK;
6680 int nTries = 0;
6681 struct timespec conchModTime;
6682
drh3d4435b2011-08-26 20:55:50 +00006683 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006684 do {
6685 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6686 nTries ++;
6687 if( rc==SQLITE_BUSY ){
6688 /* If the lock failed (busy):
6689 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6690 * 2nd try: fail if the mod time changed or host id is different, wait
6691 * 10 sec and try again
6692 * 3rd try: break the lock unless the mod time has changed.
6693 */
6694 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006695 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006696 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006697 return SQLITE_IOERR_LOCK;
6698 }
6699
6700 if( nTries==1 ){
6701 conchModTime = buf.st_mtimespec;
6702 usleep(500000); /* wait 0.5 sec and try the lock again*/
6703 continue;
6704 }
6705
6706 assert( nTries>1 );
6707 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6708 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6709 return SQLITE_BUSY;
6710 }
6711
6712 if( nTries==2 ){
6713 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006714 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006715 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006716 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006717 return SQLITE_IOERR_LOCK;
6718 }
6719 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6720 /* don't break the lock if the host id doesn't match */
6721 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6722 return SQLITE_BUSY;
6723 }
6724 }else{
6725 /* don't break the lock on short read or a version mismatch */
6726 return SQLITE_BUSY;
6727 }
6728 usleep(10000000); /* wait 10 sec and try the lock again */
6729 continue;
6730 }
6731
6732 assert( nTries==3 );
6733 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6734 rc = SQLITE_OK;
6735 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006736 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006737 }
6738 if( !rc ){
6739 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6740 }
6741 }
6742 }
6743 } while( rc==SQLITE_BUSY && nTries<3 );
6744
6745 return rc;
6746}
6747
6748/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006749** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6750** lockPath means that the lockPath in the conch file will be used if the
6751** host IDs match, or a new lock path will be generated automatically
6752** and written to the conch file.
6753*/
6754static int proxyTakeConch(unixFile *pFile){
6755 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6756
drh7ed97b92010-01-20 13:07:21 +00006757 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006758 return SQLITE_OK;
6759 }else{
6760 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006761 uuid_t myHostID;
6762 int pError = 0;
6763 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006764 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006765 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006766 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006767 int createConch = 0;
6768 int hostIdMatch = 0;
6769 int readLen = 0;
6770 int tryOldLockPath = 0;
6771 int forceNewLockPath = 0;
6772
drh308c2a52010-05-14 11:30:18 +00006773 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006774 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006775 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006776
drh7ed97b92010-01-20 13:07:21 +00006777 rc = proxyGetHostID(myHostID, &pError);
6778 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006779 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006780 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006781 }
drh7ed97b92010-01-20 13:07:21 +00006782 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006783 if( rc!=SQLITE_OK ){
6784 goto end_takeconch;
6785 }
drh7ed97b92010-01-20 13:07:21 +00006786 /* read the existing conch file */
6787 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6788 if( readLen<0 ){
6789 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006790 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006791 rc = SQLITE_IOERR_READ;
6792 goto end_takeconch;
6793 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6794 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6795 /* a short read or version format mismatch means we need to create a new
6796 ** conch file.
6797 */
6798 createConch = 1;
6799 }
6800 /* if the host id matches and the lock path already exists in the conch
6801 ** we'll try to use the path there, if we can't open that path, we'll
6802 ** retry with a new auto-generated path
6803 */
6804 do { /* in case we need to try again for an :auto: named lock file */
6805
6806 if( !createConch && !forceNewLockPath ){
6807 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6808 PROXY_HOSTIDLEN);
6809 /* if the conch has data compare the contents */
6810 if( !pCtx->lockProxyPath ){
6811 /* for auto-named local lock file, just check the host ID and we'll
6812 ** use the local lock file path that's already in there
6813 */
6814 if( hostIdMatch ){
6815 size_t pathLen = (readLen - PROXY_PATHINDEX);
6816
6817 if( pathLen>=MAXPATHLEN ){
6818 pathLen=MAXPATHLEN-1;
6819 }
6820 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6821 lockPath[pathLen] = 0;
6822 tempLockPath = lockPath;
6823 tryOldLockPath = 1;
6824 /* create a copy of the lock path if the conch is taken */
6825 goto end_takeconch;
6826 }
6827 }else if( hostIdMatch
6828 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6829 readLen-PROXY_PATHINDEX)
6830 ){
6831 /* conch host and lock path match */
6832 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006833 }
drh7ed97b92010-01-20 13:07:21 +00006834 }
6835
6836 /* if the conch isn't writable and doesn't match, we can't take it */
6837 if( (conchFile->openFlags&O_RDWR) == 0 ){
6838 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006839 goto end_takeconch;
6840 }
drh7ed97b92010-01-20 13:07:21 +00006841
6842 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006843 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006844 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6845 tempLockPath = lockPath;
6846 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006847 }
drh7ed97b92010-01-20 13:07:21 +00006848
6849 /* update conch with host and path (this will fail if other process
6850 ** has a shared lock already), if the host id matches, use the big
6851 ** stick.
drh715ff302008-12-03 22:32:44 +00006852 */
drh7ed97b92010-01-20 13:07:21 +00006853 futimes(conchFile->h, NULL);
6854 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006855 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006856 /* We are trying for an exclusive lock but another thread in this
6857 ** same process is still holding a shared lock. */
6858 rc = SQLITE_BUSY;
6859 } else {
6860 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006861 }
drh715ff302008-12-03 22:32:44 +00006862 }else{
drh4bf66fd2015-02-19 02:43:02 +00006863 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006864 }
drh7ed97b92010-01-20 13:07:21 +00006865 if( rc==SQLITE_OK ){
6866 char writeBuffer[PROXY_MAXCONCHLEN];
6867 int writeSize = 0;
6868
6869 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6870 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6871 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006872 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6873 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006874 }else{
6875 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6876 }
6877 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006878 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006879 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6880 fsync(conchFile->h);
6881 /* If we created a new conch file (not just updated the contents of a
6882 ** valid conch file), try to match the permissions of the database
6883 */
6884 if( rc==SQLITE_OK && createConch ){
6885 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006886 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006887 if( err==0 ){
6888 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6889 S_IROTH|S_IWOTH);
6890 /* try to match the database file R/W permissions, ignore failure */
6891#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006892 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006893#else
drhff812312011-02-23 13:33:46 +00006894 do{
drhe562be52011-03-02 18:01:10 +00006895 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006896 }while( rc==(-1) && errno==EINTR );
6897 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006898 int code = errno;
6899 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6900 cmode, code, strerror(code));
6901 } else {
6902 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6903 }
6904 }else{
6905 int code = errno;
6906 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6907 err, code, strerror(code));
6908#endif
6909 }
drh715ff302008-12-03 22:32:44 +00006910 }
6911 }
drh7ed97b92010-01-20 13:07:21 +00006912 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6913
6914 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006915 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006916 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006917 int fd;
drh7ed97b92010-01-20 13:07:21 +00006918 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006919 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006920 }
6921 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006922 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006923 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006924 if( fd>=0 ){
6925 pFile->h = fd;
6926 }else{
drh9978c972010-02-23 17:36:32 +00006927 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006928 during locking */
6929 }
6930 }
6931 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6932 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6933 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6934 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6935 /* we couldn't create the proxy lock file with the old lock file path
6936 ** so try again via auto-naming
6937 */
6938 forceNewLockPath = 1;
6939 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006940 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006941 }
6942 }
6943 if( rc==SQLITE_OK ){
6944 /* Need to make a copy of path if we extracted the value
6945 ** from the conch file or the path was allocated on the stack
6946 */
6947 if( tempLockPath ){
6948 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6949 if( !pCtx->lockProxyPath ){
6950 rc = SQLITE_NOMEM;
6951 }
6952 }
6953 }
6954 if( rc==SQLITE_OK ){
6955 pCtx->conchHeld = 1;
6956
6957 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6958 afpLockingContext *afpCtx;
6959 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6960 afpCtx->dbPath = pCtx->lockProxyPath;
6961 }
6962 } else {
6963 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6964 }
drh308c2a52010-05-14 11:30:18 +00006965 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6966 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006967 return rc;
drh308c2a52010-05-14 11:30:18 +00006968 } while (1); /* in case we need to retry the :auto: lock file -
6969 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006970 }
6971}
6972
6973/*
6974** If pFile holds a lock on a conch file, then release that lock.
6975*/
6976static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006977 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006978 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6979 unixFile *conchFile; /* Name of the conch file */
6980
6981 pCtx = (proxyLockingContext *)pFile->lockingContext;
6982 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006983 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006984 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006985 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006986 if( pCtx->conchHeld>0 ){
6987 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6988 }
drh715ff302008-12-03 22:32:44 +00006989 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006990 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6991 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006992 return rc;
6993}
6994
6995/*
6996** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00006997** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00006998** Make *pConchPath point to the new name. Return SQLITE_OK on success
6999** or SQLITE_NOMEM if unable to obtain memory.
7000**
7001** The caller is responsible for ensuring that the allocated memory
7002** space is eventually freed.
7003**
7004** *pConchPath is set to NULL if a memory allocation error occurs.
7005*/
7006static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7007 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007008 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007009 char *conchPath; /* buffer in which to construct conch name */
7010
7011 /* Allocate space for the conch filename and initialize the name to
7012 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007013 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007014 if( conchPath==0 ){
7015 return SQLITE_NOMEM;
7016 }
7017 memcpy(conchPath, dbPath, len+1);
7018
7019 /* now insert a "." before the last / character */
7020 for( i=(len-1); i>=0; i-- ){
7021 if( conchPath[i]=='/' ){
7022 i++;
7023 break;
7024 }
7025 }
7026 conchPath[i]='.';
7027 while ( i<len ){
7028 conchPath[i+1]=dbPath[i];
7029 i++;
7030 }
7031
7032 /* append the "-conch" suffix to the file */
7033 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007034 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007035
7036 return SQLITE_OK;
7037}
7038
7039
7040/* Takes a fully configured proxy locking-style unix file and switches
7041** the local lock file path
7042*/
7043static int switchLockProxyPath(unixFile *pFile, const char *path) {
7044 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7045 char *oldPath = pCtx->lockProxyPath;
7046 int rc = SQLITE_OK;
7047
drh308c2a52010-05-14 11:30:18 +00007048 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007049 return SQLITE_BUSY;
7050 }
7051
7052 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7053 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7054 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7055 return SQLITE_OK;
7056 }else{
7057 unixFile *lockProxy = pCtx->lockProxy;
7058 pCtx->lockProxy=NULL;
7059 pCtx->conchHeld = 0;
7060 if( lockProxy!=NULL ){
7061 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7062 if( rc ) return rc;
7063 sqlite3_free(lockProxy);
7064 }
7065 sqlite3_free(oldPath);
7066 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7067 }
7068
7069 return rc;
7070}
7071
7072/*
7073** pFile is a file that has been opened by a prior xOpen call. dbPath
7074** is a string buffer at least MAXPATHLEN+1 characters in size.
7075**
7076** This routine find the filename associated with pFile and writes it
7077** int dbPath.
7078*/
7079static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007080#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007081 if( pFile->pMethod == &afpIoMethods ){
7082 /* afp style keeps a reference to the db path in the filePath field
7083 ** of the struct */
drhea678832008-12-10 19:26:22 +00007084 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007085 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7086 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007087 } else
drh715ff302008-12-03 22:32:44 +00007088#endif
7089 if( pFile->pMethod == &dotlockIoMethods ){
7090 /* dot lock style uses the locking context to store the dot lock
7091 ** file path */
7092 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7093 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7094 }else{
7095 /* all other styles use the locking context to store the db file path */
7096 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007097 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007098 }
7099 return SQLITE_OK;
7100}
7101
7102/*
7103** Takes an already filled in unix file and alters it so all file locking
7104** will be performed on the local proxy lock file. The following fields
7105** are preserved in the locking context so that they can be restored and
7106** the unix structure properly cleaned up at close time:
7107** ->lockingContext
7108** ->pMethod
7109*/
7110static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7111 proxyLockingContext *pCtx;
7112 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7113 char *lockPath=NULL;
7114 int rc = SQLITE_OK;
7115
drh308c2a52010-05-14 11:30:18 +00007116 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007117 return SQLITE_BUSY;
7118 }
7119 proxyGetDbPathForUnixFile(pFile, dbPath);
7120 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7121 lockPath=NULL;
7122 }else{
7123 lockPath=(char *)path;
7124 }
7125
drh308c2a52010-05-14 11:30:18 +00007126 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007127 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007128
drhf3cdcdc2015-04-29 16:50:28 +00007129 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007130 if( pCtx==0 ){
7131 return SQLITE_NOMEM;
7132 }
7133 memset(pCtx, 0, sizeof(*pCtx));
7134
7135 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7136 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007137 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7138 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7139 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7140 ** (c) the file system is read-only, then enable no-locking access.
7141 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7142 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7143 */
7144 struct statfs fsInfo;
7145 struct stat conchInfo;
7146 int goLockless = 0;
7147
drh99ab3b12011-03-02 15:09:07 +00007148 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007149 int err = errno;
7150 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7151 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7152 }
7153 }
7154 if( goLockless ){
7155 pCtx->conchHeld = -1; /* read only FS/ lockless */
7156 rc = SQLITE_OK;
7157 }
7158 }
drh715ff302008-12-03 22:32:44 +00007159 }
7160 if( rc==SQLITE_OK && lockPath ){
7161 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7162 }
7163
7164 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007165 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7166 if( pCtx->dbPath==NULL ){
7167 rc = SQLITE_NOMEM;
7168 }
7169 }
7170 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007171 /* all memory is allocated, proxys are created and assigned,
7172 ** switch the locking context and pMethod then return.
7173 */
drh715ff302008-12-03 22:32:44 +00007174 pCtx->oldLockingContext = pFile->lockingContext;
7175 pFile->lockingContext = pCtx;
7176 pCtx->pOldMethod = pFile->pMethod;
7177 pFile->pMethod = &proxyIoMethods;
7178 }else{
7179 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007180 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007181 sqlite3_free(pCtx->conchFile);
7182 }
drhd56b1212010-08-11 06:14:15 +00007183 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007184 sqlite3_free(pCtx->conchFilePath);
7185 sqlite3_free(pCtx);
7186 }
drh308c2a52010-05-14 11:30:18 +00007187 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7188 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007189 return rc;
7190}
7191
7192
7193/*
7194** This routine handles sqlite3_file_control() calls that are specific
7195** to proxy locking.
7196*/
7197static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7198 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007199 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007200 unixFile *pFile = (unixFile*)id;
7201 if( pFile->pMethod == &proxyIoMethods ){
7202 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7203 proxyTakeConch(pFile);
7204 if( pCtx->lockProxyPath ){
7205 *(const char **)pArg = pCtx->lockProxyPath;
7206 }else{
7207 *(const char **)pArg = ":auto: (not held)";
7208 }
7209 } else {
7210 *(const char **)pArg = NULL;
7211 }
7212 return SQLITE_OK;
7213 }
drh4bf66fd2015-02-19 02:43:02 +00007214 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007215 unixFile *pFile = (unixFile*)id;
7216 int rc = SQLITE_OK;
7217 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7218 if( pArg==NULL || (const char *)pArg==0 ){
7219 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007220 /* turn off proxy locking - not supported. If support is added for
7221 ** switching proxy locking mode off then it will need to fail if
7222 ** the journal mode is WAL mode.
7223 */
drh715ff302008-12-03 22:32:44 +00007224 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7225 }else{
7226 /* turn off proxy locking - already off - NOOP */
7227 rc = SQLITE_OK;
7228 }
7229 }else{
7230 const char *proxyPath = (const char *)pArg;
7231 if( isProxyStyle ){
7232 proxyLockingContext *pCtx =
7233 (proxyLockingContext*)pFile->lockingContext;
7234 if( !strcmp(pArg, ":auto:")
7235 || (pCtx->lockProxyPath &&
7236 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7237 ){
7238 rc = SQLITE_OK;
7239 }else{
7240 rc = switchLockProxyPath(pFile, proxyPath);
7241 }
7242 }else{
7243 /* turn on proxy file locking */
7244 rc = proxyTransformUnixFile(pFile, proxyPath);
7245 }
7246 }
7247 return rc;
7248 }
7249 default: {
7250 assert( 0 ); /* The call assures that only valid opcodes are sent */
7251 }
7252 }
7253 /*NOTREACHED*/
7254 return SQLITE_ERROR;
7255}
7256
7257/*
7258** Within this division (the proxying locking implementation) the procedures
7259** above this point are all utilities. The lock-related methods of the
7260** proxy-locking sqlite3_io_method object follow.
7261*/
7262
7263
7264/*
7265** This routine checks if there is a RESERVED lock held on the specified
7266** file by this or any other process. If such a lock is held, set *pResOut
7267** to a non-zero value otherwise *pResOut is set to zero. The return value
7268** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7269*/
7270static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7271 unixFile *pFile = (unixFile*)id;
7272 int rc = proxyTakeConch(pFile);
7273 if( rc==SQLITE_OK ){
7274 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007275 if( pCtx->conchHeld>0 ){
7276 unixFile *proxy = pCtx->lockProxy;
7277 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7278 }else{ /* conchHeld < 0 is lockless */
7279 pResOut=0;
7280 }
drh715ff302008-12-03 22:32:44 +00007281 }
7282 return rc;
7283}
7284
7285/*
drh308c2a52010-05-14 11:30:18 +00007286** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007287** of the following:
7288**
7289** (1) SHARED_LOCK
7290** (2) RESERVED_LOCK
7291** (3) PENDING_LOCK
7292** (4) EXCLUSIVE_LOCK
7293**
7294** Sometimes when requesting one lock state, additional lock states
7295** are inserted in between. The locking might fail on one of the later
7296** transitions leaving the lock state different from what it started but
7297** still short of its goal. The following chart shows the allowed
7298** transitions and the inserted intermediate states:
7299**
7300** UNLOCKED -> SHARED
7301** SHARED -> RESERVED
7302** SHARED -> (PENDING) -> EXCLUSIVE
7303** RESERVED -> (PENDING) -> EXCLUSIVE
7304** PENDING -> EXCLUSIVE
7305**
7306** This routine will only increase a lock. Use the sqlite3OsUnlock()
7307** routine to lower a locking level.
7308*/
drh308c2a52010-05-14 11:30:18 +00007309static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007310 unixFile *pFile = (unixFile*)id;
7311 int rc = proxyTakeConch(pFile);
7312 if( rc==SQLITE_OK ){
7313 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007314 if( pCtx->conchHeld>0 ){
7315 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007316 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7317 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007318 }else{
7319 /* conchHeld < 0 is lockless */
7320 }
drh715ff302008-12-03 22:32:44 +00007321 }
7322 return rc;
7323}
7324
7325
7326/*
drh308c2a52010-05-14 11:30:18 +00007327** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007328** must be either NO_LOCK or SHARED_LOCK.
7329**
7330** If the locking level of the file descriptor is already at or below
7331** the requested locking level, this routine is a no-op.
7332*/
drh308c2a52010-05-14 11:30:18 +00007333static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007334 unixFile *pFile = (unixFile*)id;
7335 int rc = proxyTakeConch(pFile);
7336 if( rc==SQLITE_OK ){
7337 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007338 if( pCtx->conchHeld>0 ){
7339 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007340 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7341 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007342 }else{
7343 /* conchHeld < 0 is lockless */
7344 }
drh715ff302008-12-03 22:32:44 +00007345 }
7346 return rc;
7347}
7348
7349/*
7350** Close a file that uses proxy locks.
7351*/
7352static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007353 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007354 unixFile *pFile = (unixFile*)id;
7355 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7356 unixFile *lockProxy = pCtx->lockProxy;
7357 unixFile *conchFile = pCtx->conchFile;
7358 int rc = SQLITE_OK;
7359
7360 if( lockProxy ){
7361 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7362 if( rc ) return rc;
7363 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7364 if( rc ) return rc;
7365 sqlite3_free(lockProxy);
7366 pCtx->lockProxy = 0;
7367 }
7368 if( conchFile ){
7369 if( pCtx->conchHeld ){
7370 rc = proxyReleaseConch(pFile);
7371 if( rc ) return rc;
7372 }
7373 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7374 if( rc ) return rc;
7375 sqlite3_free(conchFile);
7376 }
drhd56b1212010-08-11 06:14:15 +00007377 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007378 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007379 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007380 /* restore the original locking context and pMethod then close it */
7381 pFile->lockingContext = pCtx->oldLockingContext;
7382 pFile->pMethod = pCtx->pOldMethod;
7383 sqlite3_free(pCtx);
7384 return pFile->pMethod->xClose(id);
7385 }
7386 return SQLITE_OK;
7387}
7388
7389
7390
drhd2cb50b2009-01-09 21:41:17 +00007391#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007392/*
7393** The proxy locking style is intended for use with AFP filesystems.
7394** And since AFP is only supported on MacOSX, the proxy locking is also
7395** restricted to MacOSX.
7396**
7397**
7398******************* End of the proxy lock implementation **********************
7399******************************************************************************/
7400
drh734c9862008-11-28 15:37:20 +00007401/*
danielk1977e339d652008-06-28 11:23:00 +00007402** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007403**
7404** This routine registers all VFS implementations for unix-like operating
7405** systems. This routine, and the sqlite3_os_end() routine that follows,
7406** should be the only routines in this file that are visible from other
7407** files.
drh6b9d6dd2008-12-03 19:34:47 +00007408**
7409** This routine is called once during SQLite initialization and by a
7410** single thread. The memory allocation and mutex subsystems have not
7411** necessarily been initialized when this routine is called, and so they
7412** should not be used.
drh153c62c2007-08-24 03:51:33 +00007413*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007414int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007415 /*
7416 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007417 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7418 ** to the "finder" function. (pAppData is a pointer to a pointer because
7419 ** silly C90 rules prohibit a void* from being cast to a function pointer
7420 ** and so we have to go through the intermediate pointer to avoid problems
7421 ** when compiling with -pedantic-errors on GCC.)
7422 **
7423 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007424 ** finder-function. The finder-function returns a pointer to the
7425 ** sqlite_io_methods object that implements the desired locking
7426 ** behaviors. See the division above that contains the IOMETHODS
7427 ** macro for addition information on finder-functions.
7428 **
7429 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7430 ** object. But the "autolockIoFinder" available on MacOSX does a little
7431 ** more than that; it looks at the filesystem type that hosts the
7432 ** database file and tries to choose an locking method appropriate for
7433 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007434 */
drh7708e972008-11-29 00:56:52 +00007435 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007436 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007437 sizeof(unixFile), /* szOsFile */ \
7438 MAX_PATHNAME, /* mxPathname */ \
7439 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007440 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007441 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007442 unixOpen, /* xOpen */ \
7443 unixDelete, /* xDelete */ \
7444 unixAccess, /* xAccess */ \
7445 unixFullPathname, /* xFullPathname */ \
7446 unixDlOpen, /* xDlOpen */ \
7447 unixDlError, /* xDlError */ \
7448 unixDlSym, /* xDlSym */ \
7449 unixDlClose, /* xDlClose */ \
7450 unixRandomness, /* xRandomness */ \
7451 unixSleep, /* xSleep */ \
7452 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007453 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007454 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007455 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007456 unixGetSystemCall, /* xGetSystemCall */ \
7457 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007458 }
7459
drh6b9d6dd2008-12-03 19:34:47 +00007460 /*
7461 ** All default VFSes for unix are contained in the following array.
7462 **
7463 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7464 ** by the SQLite core when the VFS is registered. So the following
7465 ** array cannot be const.
7466 */
danielk1977e339d652008-06-28 11:23:00 +00007467 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007468#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007469 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007470#elif OS_VXWORKS
7471 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007472#else
7473 UNIXVFS("unix", posixIoFinder ),
7474#endif
7475 UNIXVFS("unix-none", nolockIoFinder ),
7476 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007477 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007478#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007479 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007480#endif
drhe89b2912015-03-03 20:42:01 +00007481#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007482 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007483#endif
drhe89b2912015-03-03 20:42:01 +00007484#if SQLITE_ENABLE_LOCKING_STYLE
7485 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007486#endif
drhd2cb50b2009-01-09 21:41:17 +00007487#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007488 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007489 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007490 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007491#endif
drh153c62c2007-08-24 03:51:33 +00007492 };
drh6b9d6dd2008-12-03 19:34:47 +00007493 unsigned int i; /* Loop counter */
7494
drh2aa5a002011-04-13 13:42:25 +00007495 /* Double-check that the aSyscall[] array has been constructed
7496 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007497 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007498
drh6b9d6dd2008-12-03 19:34:47 +00007499 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007500 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007501 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007502 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007503 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007504}
danielk1977e339d652008-06-28 11:23:00 +00007505
7506/*
drh6b9d6dd2008-12-03 19:34:47 +00007507** Shutdown the operating system interface.
7508**
7509** Some operating systems might need to do some cleanup in this routine,
7510** to release dynamically allocated objects. But not on unix.
7511** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007512*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007513int sqlite3_os_end(void){
7514 return SQLITE_OK;
7515}
drhdce8bdb2007-08-16 13:01:44 +00007516
danielk197729bafea2008-06-26 10:41:19 +00007517#endif /* SQLITE_OS_UNIX */