blob: ee9b55674baa1ac5912f1c4f8d505e2f367383cb [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
drhe2258a22016-01-12 00:37:55 +0000433#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000434 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000435#else
436 { "fchown", (sqlite3_syscall_ptr)0, 0 },
437#endif
dand3eaebd2012-02-13 08:50:23 +0000438#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000439
drh6226ca22015-11-24 15:06:28 +0000440 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
441#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
442
dan4dd51442013-08-26 14:30:25 +0000443#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000444 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
445#else
446 { "mmap", (sqlite3_syscall_ptr)0, 0 },
447#endif
drh6226ca22015-11-24 15:06:28 +0000448#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000449
drhe4a08f92016-01-08 19:17:30 +0000450#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000451 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000452#else
drha8299922016-01-08 22:31:00 +0000453 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000454#endif
drh6226ca22015-11-24 15:06:28 +0000455#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000456
drhe4a08f92016-01-08 19:17:30 +0000457#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000458 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
459#else
460 { "mremap", (sqlite3_syscall_ptr)0, 0 },
461#endif
drh6226ca22015-11-24 15:06:28 +0000462#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
463
drh24dbeae2016-01-08 22:18:00 +0000464#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000465 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000466#else
467 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
468#endif
drh6226ca22015-11-24 15:06:28 +0000469#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000470
drhe2258a22016-01-12 00:37:55 +0000471#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000472 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000473#else
474 { "readlink", (sqlite3_syscall_ptr)0, 0 },
475#endif
drh6226ca22015-11-24 15:06:28 +0000476#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000477
dan702eec12014-06-23 10:04:58 +0000478
drhe562be52011-03-02 18:01:10 +0000479}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000480
drh6226ca22015-11-24 15:06:28 +0000481
482/*
483** On some systems, calls to fchown() will trigger a message in a security
484** log if they come from non-root processes. So avoid calling fchown() if
485** we are not running as root.
486*/
487static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000488#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000489 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000490#else
491 return 0;
drh6226ca22015-11-24 15:06:28 +0000492#endif
493}
494
drh99ab3b12011-03-02 15:09:07 +0000495/*
496** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000497** "unix" VFSes. Return SQLITE_OK opon successfully updating the
498** system call pointer, or SQLITE_NOTFOUND if there is no configurable
499** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000500*/
501static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000502 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
503 const char *zName, /* Name of system call to override */
504 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000505){
drh58ad5802011-03-23 22:02:23 +0000506 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000507 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000508
509 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000510 if( zName==0 ){
511 /* If no zName is given, restore all system calls to their default
512 ** settings and return NULL
513 */
dan51438a72011-04-02 17:00:47 +0000514 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000515 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
516 if( aSyscall[i].pDefault ){
517 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000518 }
519 }
520 }else{
521 /* If zName is specified, operate on only the one system call
522 ** specified.
523 */
524 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
525 if( strcmp(zName, aSyscall[i].zName)==0 ){
526 if( aSyscall[i].pDefault==0 ){
527 aSyscall[i].pDefault = aSyscall[i].pCurrent;
528 }
drh1df30962011-03-02 19:06:42 +0000529 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000530 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
531 aSyscall[i].pCurrent = pNewFunc;
532 break;
533 }
534 }
535 }
536 return rc;
537}
538
drh1df30962011-03-02 19:06:42 +0000539/*
540** Return the value of a system call. Return NULL if zName is not a
541** recognized system call name. NULL is also returned if the system call
542** is currently undefined.
543*/
drh58ad5802011-03-23 22:02:23 +0000544static sqlite3_syscall_ptr unixGetSystemCall(
545 sqlite3_vfs *pNotUsed,
546 const char *zName
547){
548 unsigned int i;
549
550 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000551 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
552 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
553 }
554 return 0;
555}
556
557/*
558** Return the name of the first system call after zName. If zName==NULL
559** then return the name of the first system call. Return NULL if zName
560** is the last system call or if zName is not the name of a valid
561** system call.
562*/
563static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000564 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000565
566 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000567 if( zName ){
568 for(i=0; i<ArraySize(aSyscall)-1; i++){
569 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000570 }
571 }
dan0fd7d862011-03-29 10:04:23 +0000572 for(i++; i<ArraySize(aSyscall); i++){
573 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000574 }
575 return 0;
576}
577
drhad4f1e52011-03-04 15:43:57 +0000578/*
drh77a3fdc2013-08-30 14:24:12 +0000579** Do not accept any file descriptor less than this value, in order to avoid
580** opening database file using file descriptors that are commonly used for
581** standard input, output, and error.
582*/
583#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
584# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
585#endif
586
587/*
drh8c815d12012-02-13 20:16:37 +0000588** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000589** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000590**
591** If the file creation mode "m" is 0 then set it to the default for
592** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
593** 0644) as modified by the system umask. If m is not 0, then
594** make the file creation mode be exactly m ignoring the umask.
595**
596** The m parameter will be non-zero only when creating -wal, -journal,
597** and -shm files. We want those files to have *exactly* the same
598** permissions as their original database, unadulterated by the umask.
599** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
600** transaction crashes and leaves behind hot journals, then any
601** process that is able to write to the database will also be able to
602** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000603*/
drh8c815d12012-02-13 20:16:37 +0000604static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000605 int fd;
drhe1186ab2013-01-04 20:45:13 +0000606 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000607 while(1){
drh5adc60b2012-04-14 13:25:11 +0000608#if defined(O_CLOEXEC)
609 fd = osOpen(z,f|O_CLOEXEC,m2);
610#else
611 fd = osOpen(z,f,m2);
612#endif
drh5128d002013-08-30 06:20:23 +0000613 if( fd<0 ){
614 if( errno==EINTR ) continue;
615 break;
616 }
drh77a3fdc2013-08-30 14:24:12 +0000617 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000618 osClose(fd);
619 sqlite3_log(SQLITE_WARNING,
620 "attempt to open \"%s\" as file descriptor %d", z, fd);
621 fd = -1;
622 if( osOpen("/dev/null", f, m)<0 ) break;
623 }
drhe1186ab2013-01-04 20:45:13 +0000624 if( fd>=0 ){
625 if( m!=0 ){
626 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000627 if( osFstat(fd, &statbuf)==0
628 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000629 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000630 ){
drhe1186ab2013-01-04 20:45:13 +0000631 osFchmod(fd, m);
632 }
633 }
drh5adc60b2012-04-14 13:25:11 +0000634#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000635 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000636#endif
drhe1186ab2013-01-04 20:45:13 +0000637 }
drh5adc60b2012-04-14 13:25:11 +0000638 return fd;
drhad4f1e52011-03-04 15:43:57 +0000639}
danielk197713adf8a2004-06-03 16:08:41 +0000640
drh107886a2008-11-21 22:21:50 +0000641/*
dan9359c7b2009-08-21 08:29:10 +0000642** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000643** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000644** vxworksFileId objects used by this file, all of which may be
645** shared by multiple threads.
646**
647** Function unixMutexHeld() is used to assert() that the global mutex
648** is held when required. This function is only used as part of assert()
649** statements. e.g.
650**
651** unixEnterMutex()
652** assert( unixMutexHeld() );
653** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000654*/
655static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000656 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000657}
658static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000659 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000660}
dan9359c7b2009-08-21 08:29:10 +0000661#ifdef SQLITE_DEBUG
662static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000663 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000664}
665#endif
drh107886a2008-11-21 22:21:50 +0000666
drh734c9862008-11-28 15:37:20 +0000667
mistachkinfb383e92015-04-16 03:24:38 +0000668#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000669/*
670** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000671** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000672** integer lock-type.
673*/
drh308c2a52010-05-14 11:30:18 +0000674static const char *azFileLock(int eFileLock){
675 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000676 case NO_LOCK: return "NONE";
677 case SHARED_LOCK: return "SHARED";
678 case RESERVED_LOCK: return "RESERVED";
679 case PENDING_LOCK: return "PENDING";
680 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000681 }
682 return "ERROR";
683}
684#endif
685
686#ifdef SQLITE_LOCK_TRACE
687/*
688** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000689**
drh734c9862008-11-28 15:37:20 +0000690** This routine is used for troubleshooting locks on multithreaded
691** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
692** command-line option on the compiler. This code is normally
693** turned off.
694*/
695static int lockTrace(int fd, int op, struct flock *p){
696 char *zOpName, *zType;
697 int s;
698 int savedErrno;
699 if( op==F_GETLK ){
700 zOpName = "GETLK";
701 }else if( op==F_SETLK ){
702 zOpName = "SETLK";
703 }else{
drh99ab3b12011-03-02 15:09:07 +0000704 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000705 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
706 return s;
707 }
708 if( p->l_type==F_RDLCK ){
709 zType = "RDLCK";
710 }else if( p->l_type==F_WRLCK ){
711 zType = "WRLCK";
712 }else if( p->l_type==F_UNLCK ){
713 zType = "UNLCK";
714 }else{
715 assert( 0 );
716 }
717 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000718 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000719 savedErrno = errno;
720 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
721 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
722 (int)p->l_pid, s);
723 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
724 struct flock l2;
725 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000726 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000727 if( l2.l_type==F_RDLCK ){
728 zType = "RDLCK";
729 }else if( l2.l_type==F_WRLCK ){
730 zType = "WRLCK";
731 }else if( l2.l_type==F_UNLCK ){
732 zType = "UNLCK";
733 }else{
734 assert( 0 );
735 }
736 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
737 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
738 }
739 errno = savedErrno;
740 return s;
741}
drh99ab3b12011-03-02 15:09:07 +0000742#undef osFcntl
743#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000744#endif /* SQLITE_LOCK_TRACE */
745
drhff812312011-02-23 13:33:46 +0000746/*
747** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000748**
drhe6d41732015-02-21 00:49:00 +0000749** All calls to ftruncate() within this file should be made through
750** this wrapper. On the Android platform, bypassing the logic below
751** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000752*/
drhff812312011-02-23 13:33:46 +0000753static int robust_ftruncate(int h, sqlite3_int64 sz){
754 int rc;
dan2ee53412014-09-06 16:49:40 +0000755#ifdef __ANDROID__
756 /* On Android, ftruncate() always uses 32-bit offsets, even if
757 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000758 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000759 ** such attempts. */
760 if( sz>(sqlite3_int64)0x7FFFFFFF ){
761 rc = SQLITE_OK;
762 }else
763#endif
drh99ab3b12011-03-02 15:09:07 +0000764 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000765 return rc;
766}
drh734c9862008-11-28 15:37:20 +0000767
768/*
769** This routine translates a standard POSIX errno code into something
770** useful to the clients of the sqlite3 functions. Specifically, it is
771** intended to translate a variety of "try again" errors into SQLITE_BUSY
772** and a variety of "please close the file descriptor NOW" errors into
773** SQLITE_IOERR
774**
775** Errors during initialization of locks, or file system support for locks,
776** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
777*/
778static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000779 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
780 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
781 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
782 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000783 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000784 case EACCES:
drh734c9862008-11-28 15:37:20 +0000785 case EAGAIN:
786 case ETIMEDOUT:
787 case EBUSY:
788 case EINTR:
789 case ENOLCK:
790 /* random NFS retry error, unless during file system support
791 * introspection, in which it actually means what it says */
792 return SQLITE_BUSY;
793
drh734c9862008-11-28 15:37:20 +0000794 case EPERM:
795 return SQLITE_PERM;
796
drh734c9862008-11-28 15:37:20 +0000797 default:
798 return sqliteIOErr;
799 }
800}
801
802
drh734c9862008-11-28 15:37:20 +0000803/******************************************************************************
804****************** Begin Unique File ID Utility Used By VxWorks ***************
805**
806** On most versions of unix, we can get a unique ID for a file by concatenating
807** the device number and the inode number. But this does not work on VxWorks.
808** On VxWorks, a unique file id must be based on the canonical filename.
809**
810** A pointer to an instance of the following structure can be used as a
811** unique file ID in VxWorks. Each instance of this structure contains
812** a copy of the canonical filename. There is also a reference count.
813** The structure is reclaimed when the number of pointers to it drops to
814** zero.
815**
816** There are never very many files open at one time and lookups are not
817** a performance-critical path, so it is sufficient to put these
818** structures on a linked list.
819*/
820struct vxworksFileId {
821 struct vxworksFileId *pNext; /* Next in a list of them all */
822 int nRef; /* Number of references to this one */
823 int nName; /* Length of the zCanonicalName[] string */
824 char *zCanonicalName; /* Canonical filename */
825};
826
827#if OS_VXWORKS
828/*
drh9b35ea62008-11-29 02:20:26 +0000829** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000830** variable:
831*/
832static struct vxworksFileId *vxworksFileList = 0;
833
834/*
835** Simplify a filename into its canonical form
836** by making the following changes:
837**
838** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000839** * convert /./ into just /
840** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000841**
842** Changes are made in-place. Return the new name length.
843**
844** The original filename is in z[0..n-1]. Return the number of
845** characters in the simplified name.
846*/
847static int vxworksSimplifyName(char *z, int n){
848 int i, j;
849 while( n>1 && z[n-1]=='/' ){ n--; }
850 for(i=j=0; i<n; i++){
851 if( z[i]=='/' ){
852 if( z[i+1]=='/' ) continue;
853 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
854 i += 1;
855 continue;
856 }
857 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
858 while( j>0 && z[j-1]!='/' ){ j--; }
859 if( j>0 ){ j--; }
860 i += 2;
861 continue;
862 }
863 }
864 z[j++] = z[i];
865 }
866 z[j] = 0;
867 return j;
868}
869
870/*
871** Find a unique file ID for the given absolute pathname. Return
872** a pointer to the vxworksFileId object. This pointer is the unique
873** file ID.
874**
875** The nRef field of the vxworksFileId object is incremented before
876** the object is returned. A new vxworksFileId object is created
877** and added to the global list if necessary.
878**
879** If a memory allocation error occurs, return NULL.
880*/
881static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
882 struct vxworksFileId *pNew; /* search key and new file ID */
883 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
884 int n; /* Length of zAbsoluteName string */
885
886 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000887 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000888 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000889 if( pNew==0 ) return 0;
890 pNew->zCanonicalName = (char*)&pNew[1];
891 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
892 n = vxworksSimplifyName(pNew->zCanonicalName, n);
893
894 /* Search for an existing entry that matching the canonical name.
895 ** If found, increment the reference count and return a pointer to
896 ** the existing file ID.
897 */
898 unixEnterMutex();
899 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
900 if( pCandidate->nName==n
901 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
902 ){
903 sqlite3_free(pNew);
904 pCandidate->nRef++;
905 unixLeaveMutex();
906 return pCandidate;
907 }
908 }
909
910 /* No match was found. We will make a new file ID */
911 pNew->nRef = 1;
912 pNew->nName = n;
913 pNew->pNext = vxworksFileList;
914 vxworksFileList = pNew;
915 unixLeaveMutex();
916 return pNew;
917}
918
919/*
920** Decrement the reference count on a vxworksFileId object. Free
921** the object when the reference count reaches zero.
922*/
923static void vxworksReleaseFileId(struct vxworksFileId *pId){
924 unixEnterMutex();
925 assert( pId->nRef>0 );
926 pId->nRef--;
927 if( pId->nRef==0 ){
928 struct vxworksFileId **pp;
929 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
930 assert( *pp==pId );
931 *pp = pId->pNext;
932 sqlite3_free(pId);
933 }
934 unixLeaveMutex();
935}
936#endif /* OS_VXWORKS */
937/*************** End of Unique File ID Utility Used By VxWorks ****************
938******************************************************************************/
939
940
941/******************************************************************************
942*************************** Posix Advisory Locking ****************************
943**
drh9b35ea62008-11-29 02:20:26 +0000944** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000945** section 6.5.2.2 lines 483 through 490 specify that when a process
946** sets or clears a lock, that operation overrides any prior locks set
947** by the same process. It does not explicitly say so, but this implies
948** that it overrides locks set by the same process using a different
949** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000950**
951** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000952** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
953**
954** Suppose ./file1 and ./file2 are really the same file (because
955** one is a hard or symbolic link to the other) then if you set
956** an exclusive lock on fd1, then try to get an exclusive lock
957** on fd2, it works. I would have expected the second lock to
958** fail since there was already a lock on the file due to fd1.
959** But not so. Since both locks came from the same process, the
960** second overrides the first, even though they were on different
961** file descriptors opened on different file names.
962**
drh734c9862008-11-28 15:37:20 +0000963** This means that we cannot use POSIX locks to synchronize file access
964** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000965** to synchronize access for threads in separate processes, but not
966** threads within the same process.
967**
968** To work around the problem, SQLite has to manage file locks internally
969** on its own. Whenever a new database is opened, we have to find the
970** specific inode of the database file (the inode is determined by the
971** st_dev and st_ino fields of the stat structure that fstat() fills in)
972** and check for locks already existing on that inode. When locks are
973** created or removed, we have to look at our own internal record of the
974** locks to see if another thread has previously set a lock on that same
975** inode.
976**
drh9b35ea62008-11-29 02:20:26 +0000977** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
978** For VxWorks, we have to use the alternative unique ID system based on
979** canonical filename and implemented in the previous division.)
980**
danielk1977ad94b582007-08-20 06:44:22 +0000981** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000982** descriptor. It is now a structure that holds the integer file
983** descriptor and a pointer to a structure that describes the internal
984** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000985** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000986** point to the same locking structure. The locking structure keeps
987** a reference count (so we will know when to delete it) and a "cnt"
988** field that tells us its internal lock status. cnt==0 means the
989** file is unlocked. cnt==-1 means the file has an exclusive lock.
990** cnt>0 means there are cnt shared locks on the file.
991**
992** Any attempt to lock or unlock a file first checks the locking
993** structure. The fcntl() system call is only invoked to set a
994** POSIX lock if the internal lock structure transitions between
995** a locked and an unlocked state.
996**
drh734c9862008-11-28 15:37:20 +0000997** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000998**
999** If you close a file descriptor that points to a file that has locks,
1000** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001001** released. To work around this problem, each unixInodeInfo object
1002** maintains a count of the number of pending locks on tha inode.
1003** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001004** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001005** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001006** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001007** be closed and that list is walked (and cleared) when the last lock
1008** clears.
1009**
drh9b35ea62008-11-29 02:20:26 +00001010** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001011**
drh9b35ea62008-11-29 02:20:26 +00001012** Many older versions of linux use the LinuxThreads library which is
1013** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001014** A cannot be modified or overridden by a different thread B.
1015** Only thread A can modify the lock. Locking behavior is correct
1016** if the appliation uses the newer Native Posix Thread Library (NPTL)
1017** on linux - with NPTL a lock created by thread A can override locks
1018** in thread B. But there is no way to know at compile-time which
1019** threading library is being used. So there is no way to know at
1020** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001021** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001022** current process.
drh5fdae772004-06-29 03:29:00 +00001023**
drh8af6c222010-05-14 12:43:01 +00001024** SQLite used to support LinuxThreads. But support for LinuxThreads
1025** was dropped beginning with version 3.7.0. SQLite will still work with
1026** LinuxThreads provided that (1) there is no more than one connection
1027** per database file in the same process and (2) database connections
1028** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001029*/
1030
1031/*
1032** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001033** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001034*/
1035struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001036 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001037#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001038 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001039#else
drh107886a2008-11-21 22:21:50 +00001040 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001041#endif
1042};
1043
1044/*
drhbbd42a62004-05-22 17:41:58 +00001045** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001046** inode. Or, on LinuxThreads, there is one of these structures for
1047** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001048**
danielk1977ad94b582007-08-20 06:44:22 +00001049** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001050** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001051** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001052*/
drh8af6c222010-05-14 12:43:01 +00001053struct unixInodeInfo {
1054 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001055 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001056 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1057 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001058 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001059 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1060 int nLock; /* Number of outstanding file locks */
1061 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1062 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1063 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001064#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001065 unsigned long long sharedByte; /* for AFP simulated shared lock */
1066#endif
drh6c7d5c52008-11-21 20:32:33 +00001067#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001068 sem_t *pSem; /* Named POSIX semaphore */
1069 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001070#endif
drhbbd42a62004-05-22 17:41:58 +00001071};
1072
drhda0e7682008-07-30 15:27:54 +00001073/*
drh8af6c222010-05-14 12:43:01 +00001074** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001075*/
drhd91c68f2010-05-14 14:52:25 +00001076static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001077
drh5fdae772004-06-29 03:29:00 +00001078/*
dane18d4952011-02-21 11:46:24 +00001079**
drhaaeaa182015-11-24 15:12:47 +00001080** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001081** unixLogError().
1082**
1083** It is invoked after an error occurs in an OS function and errno has been
1084** set. It logs a message using sqlite3_log() containing the current value of
1085** errno and, if possible, the human-readable equivalent from strerror() or
1086** strerror_r().
1087**
1088** The first argument passed to the macro should be the error code that
1089** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1090** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001091** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001092** if any.
1093*/
drh0e9365c2011-03-02 02:08:13 +00001094#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1095static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001096 int errcode, /* SQLite error code */
1097 const char *zFunc, /* Name of OS function that failed */
1098 const char *zPath, /* File path associated with error */
1099 int iLine /* Source line number where error occurred */
1100){
1101 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001102 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001103
1104 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1105 ** the strerror() function to obtain the human-readable error message
1106 ** equivalent to errno. Otherwise, use strerror_r().
1107 */
1108#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1109 char aErr[80];
1110 memset(aErr, 0, sizeof(aErr));
1111 zErr = aErr;
1112
1113 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001114 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001115 ** returns a pointer to a buffer containing the error message. That pointer
1116 ** may point to aErr[], or it may point to some static storage somewhere.
1117 ** Otherwise, assume that the system provides the POSIX version of
1118 ** strerror_r(), which always writes an error message into aErr[].
1119 **
1120 ** If the code incorrectly assumes that it is the POSIX version that is
1121 ** available, the error message will often be an empty string. Not a
1122 ** huge problem. Incorrectly concluding that the GNU version is available
1123 ** could lead to a segfault though.
1124 */
1125#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1126 zErr =
1127# endif
drh0e9365c2011-03-02 02:08:13 +00001128 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001129
1130#elif SQLITE_THREADSAFE
1131 /* This is a threadsafe build, but strerror_r() is not available. */
1132 zErr = "";
1133#else
1134 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001135 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001136#endif
1137
drh0e9365c2011-03-02 02:08:13 +00001138 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001139 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001140 "os_unix.c:%d: (%d) %s(%s) - %s",
1141 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001142 );
1143
1144 return errcode;
1145}
1146
drh0e9365c2011-03-02 02:08:13 +00001147/*
1148** Close a file descriptor.
1149**
1150** We assume that close() almost always works, since it is only in a
1151** very sick application or on a very sick platform that it might fail.
1152** If it does fail, simply leak the file descriptor, but do log the
1153** error.
1154**
1155** Note that it is not safe to retry close() after EINTR since the
1156** file descriptor might have already been reused by another thread.
1157** So we don't even try to recover from an EINTR. Just log the error
1158** and move on.
1159*/
1160static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001161 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001162 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1163 pFile ? pFile->zPath : 0, lineno);
1164 }
1165}
dane18d4952011-02-21 11:46:24 +00001166
1167/*
drhe6d41732015-02-21 00:49:00 +00001168** Set the pFile->lastErrno. Do this in a subroutine as that provides
1169** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001170*/
1171static void storeLastErrno(unixFile *pFile, int error){
1172 pFile->lastErrno = error;
1173}
1174
1175/*
danb0ac3e32010-06-16 10:55:42 +00001176** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001177*/
drh0e9365c2011-03-02 02:08:13 +00001178static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001179 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001180 UnixUnusedFd *p;
1181 UnixUnusedFd *pNext;
1182 for(p=pInode->pUnused; p; p=pNext){
1183 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001184 robust_close(pFile, p->fd, __LINE__);
1185 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001186 }
drh0e9365c2011-03-02 02:08:13 +00001187 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001188}
1189
1190/*
drh8af6c222010-05-14 12:43:01 +00001191** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001192**
1193** The mutex entered using the unixEnterMutex() function must be held
1194** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001195*/
danb0ac3e32010-06-16 10:55:42 +00001196static void releaseInodeInfo(unixFile *pFile){
1197 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001198 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001199 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001200 pInode->nRef--;
1201 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001202 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001203 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001204 if( pInode->pPrev ){
1205 assert( pInode->pPrev->pNext==pInode );
1206 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001207 }else{
drh8af6c222010-05-14 12:43:01 +00001208 assert( inodeList==pInode );
1209 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001210 }
drh8af6c222010-05-14 12:43:01 +00001211 if( pInode->pNext ){
1212 assert( pInode->pNext->pPrev==pInode );
1213 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001214 }
drh8af6c222010-05-14 12:43:01 +00001215 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001216 }
drhbbd42a62004-05-22 17:41:58 +00001217 }
1218}
1219
1220/*
drh8af6c222010-05-14 12:43:01 +00001221** Given a file descriptor, locate the unixInodeInfo object that
1222** describes that file descriptor. Create a new one if necessary. The
1223** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001224**
dan9359c7b2009-08-21 08:29:10 +00001225** The mutex entered using the unixEnterMutex() function must be held
1226** when this function is called.
1227**
drh6c7d5c52008-11-21 20:32:33 +00001228** Return an appropriate error code.
1229*/
drh8af6c222010-05-14 12:43:01 +00001230static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001231 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001232 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001233){
1234 int rc; /* System call return code */
1235 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001236 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1237 struct stat statbuf; /* Low-level file information */
1238 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001239
dan9359c7b2009-08-21 08:29:10 +00001240 assert( unixMutexHeld() );
1241
drh6c7d5c52008-11-21 20:32:33 +00001242 /* Get low-level information about the file that we can used to
1243 ** create a unique name for the file.
1244 */
1245 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001246 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001247 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001248 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001249#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001250 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1251#endif
1252 return SQLITE_IOERR;
1253 }
1254
drheb0d74f2009-02-03 15:27:02 +00001255#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001256 /* On OS X on an msdos filesystem, the inode number is reported
1257 ** incorrectly for zero-size files. See ticket #3260. To work
1258 ** around this problem (we consider it a bug in OS X, not SQLite)
1259 ** we always increase the file size to 1 by writing a single byte
1260 ** prior to accessing the inode number. The one byte written is
1261 ** an ASCII 'S' character which also happens to be the first byte
1262 ** in the header of every SQLite database. In this way, if there
1263 ** is a race condition such that another thread has already populated
1264 ** the first page of the database, no damage is done.
1265 */
drh7ed97b92010-01-20 13:07:21 +00001266 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001267 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001268 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001269 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001270 return SQLITE_IOERR;
1271 }
drh99ab3b12011-03-02 15:09:07 +00001272 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001273 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001274 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001275 return SQLITE_IOERR;
1276 }
1277 }
drheb0d74f2009-02-03 15:27:02 +00001278#endif
drh6c7d5c52008-11-21 20:32:33 +00001279
drh8af6c222010-05-14 12:43:01 +00001280 memset(&fileId, 0, sizeof(fileId));
1281 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001282#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001283 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001284#else
drh8af6c222010-05-14 12:43:01 +00001285 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001286#endif
drh8af6c222010-05-14 12:43:01 +00001287 pInode = inodeList;
1288 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1289 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001290 }
drh8af6c222010-05-14 12:43:01 +00001291 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001292 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001293 if( pInode==0 ){
1294 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001295 }
drh8af6c222010-05-14 12:43:01 +00001296 memset(pInode, 0, sizeof(*pInode));
1297 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1298 pInode->nRef = 1;
1299 pInode->pNext = inodeList;
1300 pInode->pPrev = 0;
1301 if( inodeList ) inodeList->pPrev = pInode;
1302 inodeList = pInode;
1303 }else{
1304 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001305 }
drh8af6c222010-05-14 12:43:01 +00001306 *ppInode = pInode;
1307 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001308}
drh6c7d5c52008-11-21 20:32:33 +00001309
drhb959a012013-12-07 12:29:22 +00001310/*
1311** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1312*/
1313static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001314#if OS_VXWORKS
1315 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1316#else
drhb959a012013-12-07 12:29:22 +00001317 struct stat buf;
1318 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001319 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001320#endif
drhb959a012013-12-07 12:29:22 +00001321}
1322
aswift5b1a2562008-08-22 00:22:35 +00001323
1324/*
drhfbc7e882013-04-11 01:16:15 +00001325** Check a unixFile that is a database. Verify the following:
1326**
1327** (1) There is exactly one hard link on the file
1328** (2) The file is not a symbolic link
1329** (3) The file has not been renamed or unlinked
1330**
1331** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1332*/
1333static void verifyDbFile(unixFile *pFile){
1334 struct stat buf;
1335 int rc;
drhfbc7e882013-04-11 01:16:15 +00001336 rc = osFstat(pFile->h, &buf);
1337 if( rc!=0 ){
1338 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001339 return;
1340 }
drh3044b512014-06-16 16:41:52 +00001341 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001342 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001343 return;
1344 }
1345 if( buf.st_nlink>1 ){
1346 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001347 return;
1348 }
drhb959a012013-12-07 12:29:22 +00001349 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001350 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001351 return;
1352 }
1353}
1354
1355
1356/*
danielk197713adf8a2004-06-03 16:08:41 +00001357** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001358** file by this or any other process. If such a lock is held, set *pResOut
1359** to a non-zero value otherwise *pResOut is set to zero. The return value
1360** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001361*/
danielk1977861f7452008-06-05 11:39:11 +00001362static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001363 int rc = SQLITE_OK;
1364 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001365 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001366
danielk1977861f7452008-06-05 11:39:11 +00001367 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1368
drh054889e2005-11-30 03:20:31 +00001369 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001370 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001371 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001372
1373 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001374 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001375 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001376 }
1377
drh2ac3ee92004-06-07 16:27:46 +00001378 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001379 */
danielk197709480a92009-02-09 05:32:32 +00001380#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001381 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001382 struct flock lock;
1383 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001384 lock.l_start = RESERVED_BYTE;
1385 lock.l_len = 1;
1386 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001387 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1388 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001389 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001390 } else if( lock.l_type!=F_UNLCK ){
1391 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001392 }
1393 }
danielk197709480a92009-02-09 05:32:32 +00001394#endif
danielk197713adf8a2004-06-03 16:08:41 +00001395
drh6c7d5c52008-11-21 20:32:33 +00001396 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001397 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001398
aswift5b1a2562008-08-22 00:22:35 +00001399 *pResOut = reserved;
1400 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001401}
1402
1403/*
drha7e61d82011-03-12 17:02:57 +00001404** Attempt to set a system-lock on the file pFile. The lock is
1405** described by pLock.
1406**
drh77197112011-03-15 19:08:48 +00001407** If the pFile was opened read/write from unix-excl, then the only lock
1408** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001409** the first time any lock is attempted. All subsequent system locking
1410** operations become no-ops. Locking operations still happen internally,
1411** in order to coordinate access between separate database connections
1412** within this process, but all of that is handled in memory and the
1413** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001414**
1415** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1416** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1417** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001418**
1419** Zero is returned if the call completes successfully, or -1 if a call
1420** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001421*/
1422static int unixFileLock(unixFile *pFile, struct flock *pLock){
1423 int rc;
drh3cb93392011-03-12 18:10:44 +00001424 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001425 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001426 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001427 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001428 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001429 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001430 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001431 lock.l_whence = SEEK_SET;
1432 lock.l_start = SHARED_FIRST;
1433 lock.l_len = SHARED_SIZE;
1434 lock.l_type = F_WRLCK;
1435 rc = osFcntl(pFile->h, F_SETLK, &lock);
1436 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001437 pInode->bProcessLock = 1;
1438 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001439 }else{
1440 rc = 0;
1441 }
1442 }else{
1443 rc = osFcntl(pFile->h, F_SETLK, pLock);
1444 }
1445 return rc;
1446}
1447
1448/*
drh308c2a52010-05-14 11:30:18 +00001449** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001450** of the following:
1451**
drh2ac3ee92004-06-07 16:27:46 +00001452** (1) SHARED_LOCK
1453** (2) RESERVED_LOCK
1454** (3) PENDING_LOCK
1455** (4) EXCLUSIVE_LOCK
1456**
drhb3e04342004-06-08 00:47:47 +00001457** Sometimes when requesting one lock state, additional lock states
1458** are inserted in between. The locking might fail on one of the later
1459** transitions leaving the lock state different from what it started but
1460** still short of its goal. The following chart shows the allowed
1461** transitions and the inserted intermediate states:
1462**
1463** UNLOCKED -> SHARED
1464** SHARED -> RESERVED
1465** SHARED -> (PENDING) -> EXCLUSIVE
1466** RESERVED -> (PENDING) -> EXCLUSIVE
1467** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001468**
drha6abd042004-06-09 17:37:22 +00001469** This routine will only increase a lock. Use the sqlite3OsUnlock()
1470** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001471*/
drh308c2a52010-05-14 11:30:18 +00001472static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001473 /* The following describes the implementation of the various locks and
1474 ** lock transitions in terms of the POSIX advisory shared and exclusive
1475 ** lock primitives (called read-locks and write-locks below, to avoid
1476 ** confusion with SQLite lock names). The algorithms are complicated
1477 ** slightly in order to be compatible with windows systems simultaneously
1478 ** accessing the same database file, in case that is ever required.
1479 **
1480 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1481 ** byte', each single bytes at well known offsets, and the 'shared byte
1482 ** range', a range of 510 bytes at a well known offset.
1483 **
1484 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1485 ** byte'. If this is successful, a random byte from the 'shared byte
1486 ** range' is read-locked and the lock on the 'pending byte' released.
1487 **
danielk197790ba3bd2004-06-25 08:32:25 +00001488 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1489 ** A RESERVED lock is implemented by grabbing a write-lock on the
1490 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001491 **
1492 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001493 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1494 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1495 ** obtained, but existing SHARED locks are allowed to persist. A process
1496 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1497 ** This property is used by the algorithm for rolling back a journal file
1498 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001499 **
danielk197790ba3bd2004-06-25 08:32:25 +00001500 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1501 ** implemented by obtaining a write-lock on the entire 'shared byte
1502 ** range'. Since all other locks require a read-lock on one of the bytes
1503 ** within this range, this ensures that no other locks are held on the
1504 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001505 **
1506 ** The reason a single byte cannot be used instead of the 'shared byte
1507 ** range' is that some versions of windows do not support read-locks. By
1508 ** locking a random byte from a range, concurrent SHARED locks may exist
1509 ** even if the locking primitive used is always a write-lock.
1510 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001511 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001512 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001513 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001514 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001515 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001516
drh054889e2005-11-30 03:20:31 +00001517 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001518 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1519 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001520 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001521 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001522
1523 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001524 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001525 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001526 */
drh308c2a52010-05-14 11:30:18 +00001527 if( pFile->eFileLock>=eFileLock ){
1528 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1529 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001530 return SQLITE_OK;
1531 }
1532
drh0c2694b2009-09-03 16:23:44 +00001533 /* Make sure the locking sequence is correct.
1534 ** (1) We never move from unlocked to anything higher than shared lock.
1535 ** (2) SQLite never explicitly requests a pendig lock.
1536 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001537 */
drh308c2a52010-05-14 11:30:18 +00001538 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1539 assert( eFileLock!=PENDING_LOCK );
1540 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001541
drh8af6c222010-05-14 12:43:01 +00001542 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001543 */
drh6c7d5c52008-11-21 20:32:33 +00001544 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001545 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001546
danielk1977ad94b582007-08-20 06:44:22 +00001547 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001548 ** handle that precludes the requested lock, return BUSY.
1549 */
drh8af6c222010-05-14 12:43:01 +00001550 if( (pFile->eFileLock!=pInode->eFileLock &&
1551 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001552 ){
1553 rc = SQLITE_BUSY;
1554 goto end_lock;
1555 }
1556
1557 /* If a SHARED lock is requested, and some thread using this PID already
1558 ** has a SHARED or RESERVED lock, then increment reference counts and
1559 ** return SQLITE_OK.
1560 */
drh308c2a52010-05-14 11:30:18 +00001561 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001562 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001563 assert( eFileLock==SHARED_LOCK );
1564 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001565 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001566 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001567 pInode->nShared++;
1568 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001569 goto end_lock;
1570 }
1571
danielk19779a1d0ab2004-06-01 14:09:28 +00001572
drh3cde3bb2004-06-12 02:17:14 +00001573 /* A PENDING lock is needed before acquiring a SHARED lock and before
1574 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1575 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001576 */
drh0c2694b2009-09-03 16:23:44 +00001577 lock.l_len = 1L;
1578 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001579 if( eFileLock==SHARED_LOCK
1580 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001581 ){
drh308c2a52010-05-14 11:30:18 +00001582 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001583 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001584 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001585 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001586 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001587 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001588 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001589 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001590 goto end_lock;
1591 }
drh3cde3bb2004-06-12 02:17:14 +00001592 }
1593
1594
1595 /* If control gets to this point, then actually go ahead and make
1596 ** operating system calls for the specified lock.
1597 */
drh308c2a52010-05-14 11:30:18 +00001598 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001599 assert( pInode->nShared==0 );
1600 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001601 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001602
drh2ac3ee92004-06-07 16:27:46 +00001603 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001604 lock.l_start = SHARED_FIRST;
1605 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001606 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001607 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001608 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001609 }
dan661d71a2011-03-30 19:08:03 +00001610
drh2ac3ee92004-06-07 16:27:46 +00001611 /* Drop the temporary PENDING lock */
1612 lock.l_start = PENDING_BYTE;
1613 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001614 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001615 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1616 /* This could happen with a network mount */
1617 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001618 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001619 }
dan661d71a2011-03-30 19:08:03 +00001620
1621 if( rc ){
1622 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001623 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001624 }
dan661d71a2011-03-30 19:08:03 +00001625 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001626 }else{
drh308c2a52010-05-14 11:30:18 +00001627 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001628 pInode->nLock++;
1629 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001630 }
drh8af6c222010-05-14 12:43:01 +00001631 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001632 /* We are trying for an exclusive lock but another thread in this
1633 ** same process is still holding a shared lock. */
1634 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001635 }else{
drh3cde3bb2004-06-12 02:17:14 +00001636 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001637 ** assumed that there is a SHARED or greater lock on the file
1638 ** already.
1639 */
drh308c2a52010-05-14 11:30:18 +00001640 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001641 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001642
1643 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1644 if( eFileLock==RESERVED_LOCK ){
1645 lock.l_start = RESERVED_BYTE;
1646 lock.l_len = 1L;
1647 }else{
1648 lock.l_start = SHARED_FIRST;
1649 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001650 }
dan661d71a2011-03-30 19:08:03 +00001651
1652 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001653 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001654 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001655 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001656 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001657 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001658 }
drhbbd42a62004-05-22 17:41:58 +00001659 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001660
drh8f941bc2009-01-14 23:03:40 +00001661
drhd3d8c042012-05-29 17:02:40 +00001662#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001663 /* Set up the transaction-counter change checking flags when
1664 ** transitioning from a SHARED to a RESERVED lock. The change
1665 ** from SHARED to RESERVED marks the beginning of a normal
1666 ** write operation (not a hot journal rollback).
1667 */
1668 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001669 && pFile->eFileLock<=SHARED_LOCK
1670 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001671 ){
1672 pFile->transCntrChng = 0;
1673 pFile->dbUpdate = 0;
1674 pFile->inNormalWrite = 1;
1675 }
1676#endif
1677
1678
danielk1977ecb2a962004-06-02 06:30:16 +00001679 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001680 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001681 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001682 }else if( eFileLock==EXCLUSIVE_LOCK ){
1683 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001684 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001685 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001686
1687end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001688 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001689 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1690 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001691 return rc;
1692}
1693
1694/*
dan08da86a2009-08-21 17:18:03 +00001695** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001696** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001697*/
1698static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001699 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001700 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001701 p->pNext = pInode->pUnused;
1702 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001703 pFile->h = -1;
1704 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001705}
1706
1707/*
drh308c2a52010-05-14 11:30:18 +00001708** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001709** must be either NO_LOCK or SHARED_LOCK.
1710**
1711** If the locking level of the file descriptor is already at or below
1712** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001713**
1714** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1715** the byte range is divided into 2 parts and the first part is unlocked then
1716** set to a read lock, then the other part is simply unlocked. This works
1717** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1718** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001719*/
drha7e61d82011-03-12 17:02:57 +00001720static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001721 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001722 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001723 struct flock lock;
1724 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001725
drh054889e2005-11-30 03:20:31 +00001726 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001727 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001728 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001729 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001730
drh308c2a52010-05-14 11:30:18 +00001731 assert( eFileLock<=SHARED_LOCK );
1732 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001733 return SQLITE_OK;
1734 }
drh6c7d5c52008-11-21 20:32:33 +00001735 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001736 pInode = pFile->pInode;
1737 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001738 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001739 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001740
drhd3d8c042012-05-29 17:02:40 +00001741#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001742 /* When reducing a lock such that other processes can start
1743 ** reading the database file again, make sure that the
1744 ** transaction counter was updated if any part of the database
1745 ** file changed. If the transaction counter is not updated,
1746 ** other connections to the same file might not realize that
1747 ** the file has changed and hence might not know to flush their
1748 ** cache. The use of a stale cache can lead to database corruption.
1749 */
drh8f941bc2009-01-14 23:03:40 +00001750 pFile->inNormalWrite = 0;
1751#endif
1752
drh7ed97b92010-01-20 13:07:21 +00001753 /* downgrading to a shared lock on NFS involves clearing the write lock
1754 ** before establishing the readlock - to avoid a race condition we downgrade
1755 ** the lock in 2 blocks, so that part of the range will be covered by a
1756 ** write lock until the rest is covered by a read lock:
1757 ** 1: [WWWWW]
1758 ** 2: [....W]
1759 ** 3: [RRRRW]
1760 ** 4: [RRRR.]
1761 */
drh308c2a52010-05-14 11:30:18 +00001762 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001763#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001764 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001765 assert( handleNFSUnlock==0 );
1766#endif
1767#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001768 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001769 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001770 off_t divSize = SHARED_SIZE - 1;
1771
1772 lock.l_type = F_UNLCK;
1773 lock.l_whence = SEEK_SET;
1774 lock.l_start = SHARED_FIRST;
1775 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001776 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001777 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001778 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001779 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001780 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001781 }
drh7ed97b92010-01-20 13:07:21 +00001782 lock.l_type = F_RDLCK;
1783 lock.l_whence = SEEK_SET;
1784 lock.l_start = SHARED_FIRST;
1785 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001786 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001787 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001788 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1789 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001790 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001791 }
1792 goto end_unlock;
1793 }
1794 lock.l_type = F_UNLCK;
1795 lock.l_whence = SEEK_SET;
1796 lock.l_start = SHARED_FIRST+divSize;
1797 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001798 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001799 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001800 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001801 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001802 goto end_unlock;
1803 }
drh30f776f2011-02-25 03:25:07 +00001804 }else
1805#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1806 {
drh7ed97b92010-01-20 13:07:21 +00001807 lock.l_type = F_RDLCK;
1808 lock.l_whence = SEEK_SET;
1809 lock.l_start = SHARED_FIRST;
1810 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001811 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001812 /* In theory, the call to unixFileLock() cannot fail because another
1813 ** process is holding an incompatible lock. If it does, this
1814 ** indicates that the other process is not following the locking
1815 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1816 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1817 ** an assert to fail). */
1818 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001819 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001820 goto end_unlock;
1821 }
drh9c105bb2004-10-02 20:38:28 +00001822 }
1823 }
drhbbd42a62004-05-22 17:41:58 +00001824 lock.l_type = F_UNLCK;
1825 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001826 lock.l_start = PENDING_BYTE;
1827 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001828 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001829 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001830 }else{
danea83bc62011-04-01 11:56:32 +00001831 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001832 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001833 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001834 }
drhbbd42a62004-05-22 17:41:58 +00001835 }
drh308c2a52010-05-14 11:30:18 +00001836 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001837 /* Decrement the shared lock counter. Release the lock using an
1838 ** OS call only when all threads in this same process have released
1839 ** the lock.
1840 */
drh8af6c222010-05-14 12:43:01 +00001841 pInode->nShared--;
1842 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001843 lock.l_type = F_UNLCK;
1844 lock.l_whence = SEEK_SET;
1845 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001846 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001847 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001848 }else{
danea83bc62011-04-01 11:56:32 +00001849 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001850 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001851 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001852 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001853 }
drha6abd042004-06-09 17:37:22 +00001854 }
1855
drhbbd42a62004-05-22 17:41:58 +00001856 /* Decrement the count of locks against this same file. When the
1857 ** count reaches zero, close any other file descriptors whose close
1858 ** was deferred because of outstanding locks.
1859 */
drh8af6c222010-05-14 12:43:01 +00001860 pInode->nLock--;
1861 assert( pInode->nLock>=0 );
1862 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001863 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001864 }
1865 }
drhf2f105d2012-08-20 15:53:54 +00001866
aswift5b1a2562008-08-22 00:22:35 +00001867end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001868 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001869 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001870 return rc;
drhbbd42a62004-05-22 17:41:58 +00001871}
1872
1873/*
drh308c2a52010-05-14 11:30:18 +00001874** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001875** must be either NO_LOCK or SHARED_LOCK.
1876**
1877** If the locking level of the file descriptor is already at or below
1878** the requested locking level, this routine is a no-op.
1879*/
drh308c2a52010-05-14 11:30:18 +00001880static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001881#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001882 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001883#endif
drha7e61d82011-03-12 17:02:57 +00001884 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001885}
1886
mistachkine98844f2013-08-24 00:59:24 +00001887#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001888static int unixMapfile(unixFile *pFd, i64 nByte);
1889static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001890#endif
danf23da962013-03-23 21:00:41 +00001891
drh7ed97b92010-01-20 13:07:21 +00001892/*
danielk1977e339d652008-06-28 11:23:00 +00001893** This function performs the parts of the "close file" operation
1894** common to all locking schemes. It closes the directory and file
1895** handles, if they are valid, and sets all fields of the unixFile
1896** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001897**
1898** It is *not* necessary to hold the mutex when this routine is called,
1899** even on VxWorks. A mutex will be acquired on VxWorks by the
1900** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001901*/
1902static int closeUnixFile(sqlite3_file *id){
1903 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001904#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001905 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001906#endif
dan661d71a2011-03-30 19:08:03 +00001907 if( pFile->h>=0 ){
1908 robust_close(pFile, pFile->h, __LINE__);
1909 pFile->h = -1;
1910 }
1911#if OS_VXWORKS
1912 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001913 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001914 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001915 }
1916 vxworksReleaseFileId(pFile->pId);
1917 pFile->pId = 0;
1918 }
1919#endif
drh0bdbc902014-06-16 18:35:06 +00001920#ifdef SQLITE_UNLINK_AFTER_CLOSE
1921 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1922 osUnlink(pFile->zPath);
1923 sqlite3_free(*(char**)&pFile->zPath);
1924 pFile->zPath = 0;
1925 }
1926#endif
dan661d71a2011-03-30 19:08:03 +00001927 OSTRACE(("CLOSE %-3d\n", pFile->h));
1928 OpenCounter(-1);
1929 sqlite3_free(pFile->pUnused);
1930 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001931 return SQLITE_OK;
1932}
1933
1934/*
danielk1977e3026632004-06-22 11:29:02 +00001935** Close a file.
1936*/
danielk197762079062007-08-15 17:08:46 +00001937static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001938 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001939 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001940 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001941 unixUnlock(id, NO_LOCK);
1942 unixEnterMutex();
1943
1944 /* unixFile.pInode is always valid here. Otherwise, a different close
1945 ** routine (e.g. nolockClose()) would be called instead.
1946 */
1947 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1948 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1949 /* If there are outstanding locks, do not actually close the file just
1950 ** yet because that would clear those locks. Instead, add the file
1951 ** descriptor to pInode->pUnused list. It will be automatically closed
1952 ** when the last lock is cleared.
1953 */
1954 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001955 }
dan661d71a2011-03-30 19:08:03 +00001956 releaseInodeInfo(pFile);
1957 rc = closeUnixFile(id);
1958 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001959 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001960}
1961
drh734c9862008-11-28 15:37:20 +00001962/************** End of the posix advisory lock implementation *****************
1963******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001964
drh734c9862008-11-28 15:37:20 +00001965/******************************************************************************
1966****************************** No-op Locking **********************************
1967**
1968** Of the various locking implementations available, this is by far the
1969** simplest: locking is ignored. No attempt is made to lock the database
1970** file for reading or writing.
1971**
1972** This locking mode is appropriate for use on read-only databases
1973** (ex: databases that are burned into CD-ROM, for example.) It can
1974** also be used if the application employs some external mechanism to
1975** prevent simultaneous access of the same database by two or more
1976** database connections. But there is a serious risk of database
1977** corruption if this locking mode is used in situations where multiple
1978** database connections are accessing the same database file at the same
1979** time and one or more of those connections are writing.
1980*/
drhbfe66312006-10-03 17:40:40 +00001981
drh734c9862008-11-28 15:37:20 +00001982static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1983 UNUSED_PARAMETER(NotUsed);
1984 *pResOut = 0;
1985 return SQLITE_OK;
1986}
drh734c9862008-11-28 15:37:20 +00001987static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1988 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1989 return SQLITE_OK;
1990}
drh734c9862008-11-28 15:37:20 +00001991static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1992 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1993 return SQLITE_OK;
1994}
1995
1996/*
drh9b35ea62008-11-29 02:20:26 +00001997** Close the file.
drh734c9862008-11-28 15:37:20 +00001998*/
1999static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002000 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002001}
2002
2003/******************* End of the no-op lock implementation *********************
2004******************************************************************************/
2005
2006/******************************************************************************
2007************************* Begin dot-file Locking ******************************
2008**
mistachkin48864df2013-03-21 21:20:32 +00002009** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002010** files (really a directory) to control access to the database. This works
2011** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002012**
2013** (1) There is zero concurrency. A single reader blocks all other
2014** connections from reading or writing the database.
2015**
2016** (2) An application crash or power loss can leave stale lock files
2017** sitting around that need to be cleared manually.
2018**
2019** Nevertheless, a dotlock is an appropriate locking mode for use if no
2020** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002021**
drh9ef6bc42011-11-04 02:24:02 +00002022** Dotfile locking works by creating a subdirectory in the same directory as
2023** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002024** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002025** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002026*/
2027
2028/*
2029** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002030** lock directory.
drh734c9862008-11-28 15:37:20 +00002031*/
2032#define DOTLOCK_SUFFIX ".lock"
2033
drh7708e972008-11-29 00:56:52 +00002034/*
2035** This routine checks if there is a RESERVED lock held on the specified
2036** file by this or any other process. If such a lock is held, set *pResOut
2037** to a non-zero value otherwise *pResOut is set to zero. The return value
2038** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2039**
2040** In dotfile locking, either a lock exists or it does not. So in this
2041** variation of CheckReservedLock(), *pResOut is set to true if any lock
2042** is held on the file and false if the file is unlocked.
2043*/
drh734c9862008-11-28 15:37:20 +00002044static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2045 int rc = SQLITE_OK;
2046 int reserved = 0;
2047 unixFile *pFile = (unixFile*)id;
2048
2049 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2050
2051 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002052 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002053 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002054 *pResOut = reserved;
2055 return rc;
2056}
2057
drh7708e972008-11-29 00:56:52 +00002058/*
drh308c2a52010-05-14 11:30:18 +00002059** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002060** of the following:
2061**
2062** (1) SHARED_LOCK
2063** (2) RESERVED_LOCK
2064** (3) PENDING_LOCK
2065** (4) EXCLUSIVE_LOCK
2066**
2067** Sometimes when requesting one lock state, additional lock states
2068** are inserted in between. The locking might fail on one of the later
2069** transitions leaving the lock state different from what it started but
2070** still short of its goal. The following chart shows the allowed
2071** transitions and the inserted intermediate states:
2072**
2073** UNLOCKED -> SHARED
2074** SHARED -> RESERVED
2075** SHARED -> (PENDING) -> EXCLUSIVE
2076** RESERVED -> (PENDING) -> EXCLUSIVE
2077** PENDING -> EXCLUSIVE
2078**
2079** This routine will only increase a lock. Use the sqlite3OsUnlock()
2080** routine to lower a locking level.
2081**
2082** With dotfile locking, we really only support state (4): EXCLUSIVE.
2083** But we track the other locking levels internally.
2084*/
drh308c2a52010-05-14 11:30:18 +00002085static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002086 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002087 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002088 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002089
drh7708e972008-11-29 00:56:52 +00002090
2091 /* If we have any lock, then the lock file already exists. All we have
2092 ** to do is adjust our internal record of the lock level.
2093 */
drh308c2a52010-05-14 11:30:18 +00002094 if( pFile->eFileLock > NO_LOCK ){
2095 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002096 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002097#ifdef HAVE_UTIME
2098 utime(zLockFile, NULL);
2099#else
drh734c9862008-11-28 15:37:20 +00002100 utimes(zLockFile, NULL);
2101#endif
drh7708e972008-11-29 00:56:52 +00002102 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002103 }
2104
2105 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002106 rc = osMkdir(zLockFile, 0777);
2107 if( rc<0 ){
2108 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002109 int tErrno = errno;
2110 if( EEXIST == tErrno ){
2111 rc = SQLITE_BUSY;
2112 } else {
2113 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002114 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002115 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002116 }
2117 }
drh7708e972008-11-29 00:56:52 +00002118 return rc;
drh734c9862008-11-28 15:37:20 +00002119 }
drh734c9862008-11-28 15:37:20 +00002120
2121 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002122 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002123 return rc;
2124}
2125
drh7708e972008-11-29 00:56:52 +00002126/*
drh308c2a52010-05-14 11:30:18 +00002127** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002128** must be either NO_LOCK or SHARED_LOCK.
2129**
2130** If the locking level of the file descriptor is already at or below
2131** the requested locking level, this routine is a no-op.
2132**
2133** When the locking level reaches NO_LOCK, delete the lock file.
2134*/
drh308c2a52010-05-14 11:30:18 +00002135static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002136 unixFile *pFile = (unixFile*)id;
2137 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002138 int rc;
drh734c9862008-11-28 15:37:20 +00002139
2140 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002141 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002142 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002143 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002144
2145 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002146 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002147 return SQLITE_OK;
2148 }
drh7708e972008-11-29 00:56:52 +00002149
2150 /* To downgrade to shared, simply update our internal notion of the
2151 ** lock state. No need to mess with the file on disk.
2152 */
drh308c2a52010-05-14 11:30:18 +00002153 if( eFileLock==SHARED_LOCK ){
2154 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002155 return SQLITE_OK;
2156 }
2157
drh7708e972008-11-29 00:56:52 +00002158 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002159 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002160 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002161 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002162 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002163 if( tErrno==ENOENT ){
2164 rc = SQLITE_OK;
2165 }else{
danea83bc62011-04-01 11:56:32 +00002166 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002167 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002168 }
2169 return rc;
2170 }
drh308c2a52010-05-14 11:30:18 +00002171 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002172 return SQLITE_OK;
2173}
2174
2175/*
drh9b35ea62008-11-29 02:20:26 +00002176** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002177*/
2178static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002179 unixFile *pFile = (unixFile*)id;
2180 assert( id!=0 );
2181 dotlockUnlock(id, NO_LOCK);
2182 sqlite3_free(pFile->lockingContext);
2183 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002184}
2185/****************** End of the dot-file lock implementation *******************
2186******************************************************************************/
2187
2188/******************************************************************************
2189************************** Begin flock Locking ********************************
2190**
2191** Use the flock() system call to do file locking.
2192**
drh6b9d6dd2008-12-03 19:34:47 +00002193** flock() locking is like dot-file locking in that the various
2194** fine-grain locking levels supported by SQLite are collapsed into
2195** a single exclusive lock. In other words, SHARED, RESERVED, and
2196** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2197** still works when you do this, but concurrency is reduced since
2198** only a single process can be reading the database at a time.
2199**
drhe89b2912015-03-03 20:42:01 +00002200** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002201*/
drhe89b2912015-03-03 20:42:01 +00002202#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002203
drh6b9d6dd2008-12-03 19:34:47 +00002204/*
drhff812312011-02-23 13:33:46 +00002205** Retry flock() calls that fail with EINTR
2206*/
2207#ifdef EINTR
2208static int robust_flock(int fd, int op){
2209 int rc;
2210 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2211 return rc;
2212}
2213#else
drh5c819272011-02-23 14:00:12 +00002214# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002215#endif
2216
2217
2218/*
drh6b9d6dd2008-12-03 19:34:47 +00002219** This routine checks if there is a RESERVED lock held on the specified
2220** file by this or any other process. If such a lock is held, set *pResOut
2221** to a non-zero value otherwise *pResOut is set to zero. The return value
2222** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2223*/
drh734c9862008-11-28 15:37:20 +00002224static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2225 int rc = SQLITE_OK;
2226 int reserved = 0;
2227 unixFile *pFile = (unixFile*)id;
2228
2229 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2230
2231 assert( pFile );
2232
2233 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002234 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002235 reserved = 1;
2236 }
2237
2238 /* Otherwise see if some other process holds it. */
2239 if( !reserved ){
2240 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002241 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002242 if( !lrc ){
2243 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002244 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002245 if ( lrc ) {
2246 int tErrno = errno;
2247 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002248 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002249 storeLastErrno(pFile, tErrno);
2250 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002251 }
2252 } else {
2253 int tErrno = errno;
2254 reserved = 1;
2255 /* someone else might have it reserved */
2256 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2257 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002258 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002259 rc = lrc;
2260 }
2261 }
2262 }
drh308c2a52010-05-14 11:30:18 +00002263 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002264
2265#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2266 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2267 rc = SQLITE_OK;
2268 reserved=1;
2269 }
2270#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2271 *pResOut = reserved;
2272 return rc;
2273}
2274
drh6b9d6dd2008-12-03 19:34:47 +00002275/*
drh308c2a52010-05-14 11:30:18 +00002276** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002277** of the following:
2278**
2279** (1) SHARED_LOCK
2280** (2) RESERVED_LOCK
2281** (3) PENDING_LOCK
2282** (4) EXCLUSIVE_LOCK
2283**
2284** Sometimes when requesting one lock state, additional lock states
2285** are inserted in between. The locking might fail on one of the later
2286** transitions leaving the lock state different from what it started but
2287** still short of its goal. The following chart shows the allowed
2288** transitions and the inserted intermediate states:
2289**
2290** UNLOCKED -> SHARED
2291** SHARED -> RESERVED
2292** SHARED -> (PENDING) -> EXCLUSIVE
2293** RESERVED -> (PENDING) -> EXCLUSIVE
2294** PENDING -> EXCLUSIVE
2295**
2296** flock() only really support EXCLUSIVE locks. We track intermediate
2297** lock states in the sqlite3_file structure, but all locks SHARED or
2298** above are really EXCLUSIVE locks and exclude all other processes from
2299** access the file.
2300**
2301** This routine will only increase a lock. Use the sqlite3OsUnlock()
2302** routine to lower a locking level.
2303*/
drh308c2a52010-05-14 11:30:18 +00002304static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002305 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002306 unixFile *pFile = (unixFile*)id;
2307
2308 assert( pFile );
2309
2310 /* if we already have a lock, it is exclusive.
2311 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002312 if (pFile->eFileLock > NO_LOCK) {
2313 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002314 return SQLITE_OK;
2315 }
2316
2317 /* grab an exclusive lock */
2318
drhff812312011-02-23 13:33:46 +00002319 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002320 int tErrno = errno;
2321 /* didn't get, must be busy */
2322 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2323 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002324 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002325 }
2326 } else {
2327 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002328 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002329 }
drh308c2a52010-05-14 11:30:18 +00002330 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2331 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002332#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2333 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2334 rc = SQLITE_BUSY;
2335 }
2336#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2337 return rc;
2338}
2339
drh6b9d6dd2008-12-03 19:34:47 +00002340
2341/*
drh308c2a52010-05-14 11:30:18 +00002342** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002343** must be either NO_LOCK or SHARED_LOCK.
2344**
2345** If the locking level of the file descriptor is already at or below
2346** the requested locking level, this routine is a no-op.
2347*/
drh308c2a52010-05-14 11:30:18 +00002348static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002349 unixFile *pFile = (unixFile*)id;
2350
2351 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002352 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002353 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002354 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002355
2356 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002357 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002358 return SQLITE_OK;
2359 }
2360
2361 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002362 if (eFileLock==SHARED_LOCK) {
2363 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002364 return SQLITE_OK;
2365 }
2366
2367 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002368 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002369#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002370 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002371#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002372 return SQLITE_IOERR_UNLOCK;
2373 }else{
drh308c2a52010-05-14 11:30:18 +00002374 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002375 return SQLITE_OK;
2376 }
2377}
2378
2379/*
2380** Close a file.
2381*/
2382static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002383 assert( id!=0 );
2384 flockUnlock(id, NO_LOCK);
2385 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002386}
2387
2388#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2389
2390/******************* End of the flock lock implementation *********************
2391******************************************************************************/
2392
2393/******************************************************************************
2394************************ Begin Named Semaphore Locking ************************
2395**
2396** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002397**
2398** Semaphore locking is like dot-lock and flock in that it really only
2399** supports EXCLUSIVE locking. Only a single process can read or write
2400** the database file at a time. This reduces potential concurrency, but
2401** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002402*/
2403#if OS_VXWORKS
2404
drh6b9d6dd2008-12-03 19:34:47 +00002405/*
2406** This routine checks if there is a RESERVED lock held on the specified
2407** file by this or any other process. If such a lock is held, set *pResOut
2408** to a non-zero value otherwise *pResOut is set to zero. The return value
2409** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2410*/
drh8cd5b252015-03-02 22:06:43 +00002411static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002412 int rc = SQLITE_OK;
2413 int reserved = 0;
2414 unixFile *pFile = (unixFile*)id;
2415
2416 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2417
2418 assert( pFile );
2419
2420 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002421 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002422 reserved = 1;
2423 }
2424
2425 /* Otherwise see if some other process holds it. */
2426 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002427 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002428
2429 if( sem_trywait(pSem)==-1 ){
2430 int tErrno = errno;
2431 if( EAGAIN != tErrno ){
2432 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002433 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002434 } else {
2435 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002436 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002437 }
2438 }else{
2439 /* we could have it if we want it */
2440 sem_post(pSem);
2441 }
2442 }
drh308c2a52010-05-14 11:30:18 +00002443 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002444
2445 *pResOut = reserved;
2446 return rc;
2447}
2448
drh6b9d6dd2008-12-03 19:34:47 +00002449/*
drh308c2a52010-05-14 11:30:18 +00002450** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002451** of the following:
2452**
2453** (1) SHARED_LOCK
2454** (2) RESERVED_LOCK
2455** (3) PENDING_LOCK
2456** (4) EXCLUSIVE_LOCK
2457**
2458** Sometimes when requesting one lock state, additional lock states
2459** are inserted in between. The locking might fail on one of the later
2460** transitions leaving the lock state different from what it started but
2461** still short of its goal. The following chart shows the allowed
2462** transitions and the inserted intermediate states:
2463**
2464** UNLOCKED -> SHARED
2465** SHARED -> RESERVED
2466** SHARED -> (PENDING) -> EXCLUSIVE
2467** RESERVED -> (PENDING) -> EXCLUSIVE
2468** PENDING -> EXCLUSIVE
2469**
2470** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2471** lock states in the sqlite3_file structure, but all locks SHARED or
2472** above are really EXCLUSIVE locks and exclude all other processes from
2473** access the file.
2474**
2475** This routine will only increase a lock. Use the sqlite3OsUnlock()
2476** routine to lower a locking level.
2477*/
drh8cd5b252015-03-02 22:06:43 +00002478static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002479 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002480 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002481 int rc = SQLITE_OK;
2482
2483 /* if we already have a lock, it is exclusive.
2484 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002485 if (pFile->eFileLock > NO_LOCK) {
2486 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002487 rc = SQLITE_OK;
2488 goto sem_end_lock;
2489 }
2490
2491 /* lock semaphore now but bail out when already locked. */
2492 if( sem_trywait(pSem)==-1 ){
2493 rc = SQLITE_BUSY;
2494 goto sem_end_lock;
2495 }
2496
2497 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002498 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002499
2500 sem_end_lock:
2501 return rc;
2502}
2503
drh6b9d6dd2008-12-03 19:34:47 +00002504/*
drh308c2a52010-05-14 11:30:18 +00002505** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002506** must be either NO_LOCK or SHARED_LOCK.
2507**
2508** If the locking level of the file descriptor is already at or below
2509** the requested locking level, this routine is a no-op.
2510*/
drh8cd5b252015-03-02 22:06:43 +00002511static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002512 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002513 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002514
2515 assert( pFile );
2516 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002517 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002518 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002519 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002520
2521 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002522 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002523 return SQLITE_OK;
2524 }
2525
2526 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002527 if (eFileLock==SHARED_LOCK) {
2528 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002529 return SQLITE_OK;
2530 }
2531
2532 /* no, really unlock. */
2533 if ( sem_post(pSem)==-1 ) {
2534 int rc, tErrno = errno;
2535 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2536 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002537 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002538 }
2539 return rc;
2540 }
drh308c2a52010-05-14 11:30:18 +00002541 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002542 return SQLITE_OK;
2543}
2544
2545/*
2546 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002547 */
drh8cd5b252015-03-02 22:06:43 +00002548static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002549 if( id ){
2550 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002551 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002552 assert( pFile );
2553 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002554 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002555 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002556 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002557 }
2558 return SQLITE_OK;
2559}
2560
2561#endif /* OS_VXWORKS */
2562/*
2563** Named semaphore locking is only available on VxWorks.
2564**
2565*************** End of the named semaphore lock implementation ****************
2566******************************************************************************/
2567
2568
2569/******************************************************************************
2570*************************** Begin AFP Locking *********************************
2571**
2572** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2573** on Apple Macintosh computers - both OS9 and OSX.
2574**
2575** Third-party implementations of AFP are available. But this code here
2576** only works on OSX.
2577*/
2578
drhd2cb50b2009-01-09 21:41:17 +00002579#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002580/*
2581** The afpLockingContext structure contains all afp lock specific state
2582*/
drhbfe66312006-10-03 17:40:40 +00002583typedef struct afpLockingContext afpLockingContext;
2584struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002585 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002586 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002587};
2588
2589struct ByteRangeLockPB2
2590{
2591 unsigned long long offset; /* offset to first byte to lock */
2592 unsigned long long length; /* nbr of bytes to lock */
2593 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2594 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2595 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2596 int fd; /* file desc to assoc this lock with */
2597};
2598
drhfd131da2007-08-07 17:13:03 +00002599#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002600
drh6b9d6dd2008-12-03 19:34:47 +00002601/*
2602** This is a utility for setting or clearing a bit-range lock on an
2603** AFP filesystem.
2604**
2605** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2606*/
2607static int afpSetLock(
2608 const char *path, /* Name of the file to be locked or unlocked */
2609 unixFile *pFile, /* Open file descriptor on path */
2610 unsigned long long offset, /* First byte to be locked */
2611 unsigned long long length, /* Number of bytes to lock */
2612 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002613){
drh6b9d6dd2008-12-03 19:34:47 +00002614 struct ByteRangeLockPB2 pb;
2615 int err;
drhbfe66312006-10-03 17:40:40 +00002616
2617 pb.unLockFlag = setLockFlag ? 0 : 1;
2618 pb.startEndFlag = 0;
2619 pb.offset = offset;
2620 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002621 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002622
drh308c2a52010-05-14 11:30:18 +00002623 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002624 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002625 offset, length));
drhbfe66312006-10-03 17:40:40 +00002626 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2627 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002628 int rc;
2629 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002630 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2631 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002632#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2633 rc = SQLITE_BUSY;
2634#else
drh734c9862008-11-28 15:37:20 +00002635 rc = sqliteErrorFromPosixError(tErrno,
2636 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002637#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002638 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002639 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002640 }
2641 return rc;
drhbfe66312006-10-03 17:40:40 +00002642 } else {
aswift5b1a2562008-08-22 00:22:35 +00002643 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002644 }
2645}
2646
drh6b9d6dd2008-12-03 19:34:47 +00002647/*
2648** This routine checks if there is a RESERVED lock held on the specified
2649** file by this or any other process. If such a lock is held, set *pResOut
2650** to a non-zero value otherwise *pResOut is set to zero. The return value
2651** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2652*/
danielk1977e339d652008-06-28 11:23:00 +00002653static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002654 int rc = SQLITE_OK;
2655 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002656 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002657 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002658
aswift5b1a2562008-08-22 00:22:35 +00002659 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2660
2661 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002662 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002663 if( context->reserved ){
2664 *pResOut = 1;
2665 return SQLITE_OK;
2666 }
drh8af6c222010-05-14 12:43:01 +00002667 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002668
2669 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002670 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002671 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002672 }
2673
2674 /* Otherwise see if some other process holds it.
2675 */
aswift5b1a2562008-08-22 00:22:35 +00002676 if( !reserved ){
2677 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002678 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002679 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002680 /* if we succeeded in taking the reserved lock, unlock it to restore
2681 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002682 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002683 } else {
2684 /* if we failed to get the lock then someone else must have it */
2685 reserved = 1;
2686 }
2687 if( IS_LOCK_ERROR(lrc) ){
2688 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002689 }
2690 }
drhbfe66312006-10-03 17:40:40 +00002691
drh7ed97b92010-01-20 13:07:21 +00002692 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002693 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002694
2695 *pResOut = reserved;
2696 return rc;
drhbfe66312006-10-03 17:40:40 +00002697}
2698
drh6b9d6dd2008-12-03 19:34:47 +00002699/*
drh308c2a52010-05-14 11:30:18 +00002700** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002701** of the following:
2702**
2703** (1) SHARED_LOCK
2704** (2) RESERVED_LOCK
2705** (3) PENDING_LOCK
2706** (4) EXCLUSIVE_LOCK
2707**
2708** Sometimes when requesting one lock state, additional lock states
2709** are inserted in between. The locking might fail on one of the later
2710** transitions leaving the lock state different from what it started but
2711** still short of its goal. The following chart shows the allowed
2712** transitions and the inserted intermediate states:
2713**
2714** UNLOCKED -> SHARED
2715** SHARED -> RESERVED
2716** SHARED -> (PENDING) -> EXCLUSIVE
2717** RESERVED -> (PENDING) -> EXCLUSIVE
2718** PENDING -> EXCLUSIVE
2719**
2720** This routine will only increase a lock. Use the sqlite3OsUnlock()
2721** routine to lower a locking level.
2722*/
drh308c2a52010-05-14 11:30:18 +00002723static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002724 int rc = SQLITE_OK;
2725 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002726 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002727 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002728
2729 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002730 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2731 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002732 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002733
drhbfe66312006-10-03 17:40:40 +00002734 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002735 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002736 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002737 */
drh308c2a52010-05-14 11:30:18 +00002738 if( pFile->eFileLock>=eFileLock ){
2739 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2740 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002741 return SQLITE_OK;
2742 }
2743
2744 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002745 ** (1) We never move from unlocked to anything higher than shared lock.
2746 ** (2) SQLite never explicitly requests a pendig lock.
2747 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002748 */
drh308c2a52010-05-14 11:30:18 +00002749 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2750 assert( eFileLock!=PENDING_LOCK );
2751 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002752
drh8af6c222010-05-14 12:43:01 +00002753 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002754 */
drh6c7d5c52008-11-21 20:32:33 +00002755 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002756 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002757
2758 /* If some thread using this PID has a lock via a different unixFile*
2759 ** handle that precludes the requested lock, return BUSY.
2760 */
drh8af6c222010-05-14 12:43:01 +00002761 if( (pFile->eFileLock!=pInode->eFileLock &&
2762 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002763 ){
2764 rc = SQLITE_BUSY;
2765 goto afp_end_lock;
2766 }
2767
2768 /* If a SHARED lock is requested, and some thread using this PID already
2769 ** has a SHARED or RESERVED lock, then increment reference counts and
2770 ** return SQLITE_OK.
2771 */
drh308c2a52010-05-14 11:30:18 +00002772 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002773 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002774 assert( eFileLock==SHARED_LOCK );
2775 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002776 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002777 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002778 pInode->nShared++;
2779 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002780 goto afp_end_lock;
2781 }
drhbfe66312006-10-03 17:40:40 +00002782
2783 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002784 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2785 ** be released.
2786 */
drh308c2a52010-05-14 11:30:18 +00002787 if( eFileLock==SHARED_LOCK
2788 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002789 ){
2790 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002791 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002792 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002793 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002794 goto afp_end_lock;
2795 }
2796 }
2797
2798 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002799 ** operating system calls for the specified lock.
2800 */
drh308c2a52010-05-14 11:30:18 +00002801 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002802 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002803 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002804
drh8af6c222010-05-14 12:43:01 +00002805 assert( pInode->nShared==0 );
2806 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002807
2808 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002809 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002810 /* note that the quality of the randomness doesn't matter that much */
2811 lk = random();
drh8af6c222010-05-14 12:43:01 +00002812 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002813 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002814 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002815 if( IS_LOCK_ERROR(lrc1) ){
2816 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002817 }
aswift5b1a2562008-08-22 00:22:35 +00002818 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002819 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002820
aswift5b1a2562008-08-22 00:22:35 +00002821 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002822 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002823 rc = lrc1;
2824 goto afp_end_lock;
2825 } else if( IS_LOCK_ERROR(lrc2) ){
2826 rc = lrc2;
2827 goto afp_end_lock;
2828 } else if( lrc1 != SQLITE_OK ) {
2829 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002830 } else {
drh308c2a52010-05-14 11:30:18 +00002831 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002832 pInode->nLock++;
2833 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002834 }
drh8af6c222010-05-14 12:43:01 +00002835 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002836 /* We are trying for an exclusive lock but another thread in this
2837 ** same process is still holding a shared lock. */
2838 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002839 }else{
2840 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2841 ** assumed that there is a SHARED or greater lock on the file
2842 ** already.
2843 */
2844 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002845 assert( 0!=pFile->eFileLock );
2846 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002847 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002848 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002849 if( !failed ){
2850 context->reserved = 1;
2851 }
drhbfe66312006-10-03 17:40:40 +00002852 }
drh308c2a52010-05-14 11:30:18 +00002853 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002854 /* Acquire an EXCLUSIVE lock */
2855
2856 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002857 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002858 */
drh6b9d6dd2008-12-03 19:34:47 +00002859 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002860 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002861 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002862 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002863 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002864 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002865 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002866 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002867 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2868 ** a critical I/O error
2869 */
2870 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2871 SQLITE_IOERR_LOCK;
2872 goto afp_end_lock;
2873 }
2874 }else{
aswift5b1a2562008-08-22 00:22:35 +00002875 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002876 }
2877 }
aswift5b1a2562008-08-22 00:22:35 +00002878 if( failed ){
2879 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002880 }
2881 }
2882
2883 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002884 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002885 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002886 }else if( eFileLock==EXCLUSIVE_LOCK ){
2887 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002888 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002889 }
2890
2891afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002892 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002893 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2894 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002895 return rc;
2896}
2897
2898/*
drh308c2a52010-05-14 11:30:18 +00002899** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002900** must be either NO_LOCK or SHARED_LOCK.
2901**
2902** If the locking level of the file descriptor is already at or below
2903** the requested locking level, this routine is a no-op.
2904*/
drh308c2a52010-05-14 11:30:18 +00002905static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002906 int rc = SQLITE_OK;
2907 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002908 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002909 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2910 int skipShared = 0;
2911#ifdef SQLITE_TEST
2912 int h = pFile->h;
2913#endif
drhbfe66312006-10-03 17:40:40 +00002914
2915 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002916 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002917 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002918 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002919
drh308c2a52010-05-14 11:30:18 +00002920 assert( eFileLock<=SHARED_LOCK );
2921 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002922 return SQLITE_OK;
2923 }
drh6c7d5c52008-11-21 20:32:33 +00002924 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002925 pInode = pFile->pInode;
2926 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002927 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002928 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002929 SimulateIOErrorBenign(1);
2930 SimulateIOError( h=(-1) )
2931 SimulateIOErrorBenign(0);
2932
drhd3d8c042012-05-29 17:02:40 +00002933#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002934 /* When reducing a lock such that other processes can start
2935 ** reading the database file again, make sure that the
2936 ** transaction counter was updated if any part of the database
2937 ** file changed. If the transaction counter is not updated,
2938 ** other connections to the same file might not realize that
2939 ** the file has changed and hence might not know to flush their
2940 ** cache. The use of a stale cache can lead to database corruption.
2941 */
2942 assert( pFile->inNormalWrite==0
2943 || pFile->dbUpdate==0
2944 || pFile->transCntrChng==1 );
2945 pFile->inNormalWrite = 0;
2946#endif
aswiftaebf4132008-11-21 00:10:35 +00002947
drh308c2a52010-05-14 11:30:18 +00002948 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002949 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002950 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002951 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002952 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002953 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2954 } else {
2955 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002956 }
2957 }
drh308c2a52010-05-14 11:30:18 +00002958 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002959 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002960 }
drh308c2a52010-05-14 11:30:18 +00002961 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002962 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2963 if( !rc ){
2964 context->reserved = 0;
2965 }
aswiftaebf4132008-11-21 00:10:35 +00002966 }
drh8af6c222010-05-14 12:43:01 +00002967 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2968 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002969 }
aswiftaebf4132008-11-21 00:10:35 +00002970 }
drh308c2a52010-05-14 11:30:18 +00002971 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002972
drh7ed97b92010-01-20 13:07:21 +00002973 /* Decrement the shared lock counter. Release the lock using an
2974 ** OS call only when all threads in this same process have released
2975 ** the lock.
2976 */
drh8af6c222010-05-14 12:43:01 +00002977 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2978 pInode->nShared--;
2979 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002980 SimulateIOErrorBenign(1);
2981 SimulateIOError( h=(-1) )
2982 SimulateIOErrorBenign(0);
2983 if( !skipShared ){
2984 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2985 }
2986 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002987 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002988 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002989 }
2990 }
2991 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002992 pInode->nLock--;
2993 assert( pInode->nLock>=0 );
2994 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002995 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002996 }
2997 }
drhbfe66312006-10-03 17:40:40 +00002998 }
drh7ed97b92010-01-20 13:07:21 +00002999
drh6c7d5c52008-11-21 20:32:33 +00003000 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003001 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003002 return rc;
3003}
3004
3005/*
drh339eb0b2008-03-07 15:34:11 +00003006** Close a file & cleanup AFP specific locking context
3007*/
danielk1977e339d652008-06-28 11:23:00 +00003008static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003009 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003010 unixFile *pFile = (unixFile*)id;
3011 assert( id!=0 );
3012 afpUnlock(id, NO_LOCK);
3013 unixEnterMutex();
3014 if( pFile->pInode && pFile->pInode->nLock ){
3015 /* If there are outstanding locks, do not actually close the file just
3016 ** yet because that would clear those locks. Instead, add the file
3017 ** descriptor to pInode->aPending. It will be automatically closed when
3018 ** the last lock is cleared.
3019 */
3020 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003021 }
drha8de1e12015-11-30 00:05:39 +00003022 releaseInodeInfo(pFile);
3023 sqlite3_free(pFile->lockingContext);
3024 rc = closeUnixFile(id);
3025 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003026 return rc;
drhbfe66312006-10-03 17:40:40 +00003027}
3028
drhd2cb50b2009-01-09 21:41:17 +00003029#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003030/*
3031** The code above is the AFP lock implementation. The code is specific
3032** to MacOSX and does not work on other unix platforms. No alternative
3033** is available. If you don't compile for a mac, then the "unix-afp"
3034** VFS is not available.
3035**
3036********************* End of the AFP lock implementation **********************
3037******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003038
drh7ed97b92010-01-20 13:07:21 +00003039/******************************************************************************
3040*************************** Begin NFS Locking ********************************/
3041
3042#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3043/*
drh308c2a52010-05-14 11:30:18 +00003044 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003045 ** must be either NO_LOCK or SHARED_LOCK.
3046 **
3047 ** If the locking level of the file descriptor is already at or below
3048 ** the requested locking level, this routine is a no-op.
3049 */
drh308c2a52010-05-14 11:30:18 +00003050static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003051 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003052}
3053
3054#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3055/*
3056** The code above is the NFS lock implementation. The code is specific
3057** to MacOSX and does not work on other unix platforms. No alternative
3058** is available.
3059**
3060********************* End of the NFS lock implementation **********************
3061******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003062
3063/******************************************************************************
3064**************** Non-locking sqlite3_file methods *****************************
3065**
3066** The next division contains implementations for all methods of the
3067** sqlite3_file object other than the locking methods. The locking
3068** methods were defined in divisions above (one locking method per
3069** division). Those methods that are common to all locking modes
3070** are gather together into this division.
3071*/
drhbfe66312006-10-03 17:40:40 +00003072
3073/*
drh734c9862008-11-28 15:37:20 +00003074** Seek to the offset passed as the second argument, then read cnt
3075** bytes into pBuf. Return the number of bytes actually read.
3076**
3077** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3078** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3079** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003080** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003081** See tickets #2741 and #2681.
3082**
3083** To avoid stomping the errno value on a failed read the lastErrno value
3084** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003085*/
drh734c9862008-11-28 15:37:20 +00003086static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3087 int got;
drh58024642011-11-07 18:16:00 +00003088 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003089#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003090 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003091#endif
drh734c9862008-11-28 15:37:20 +00003092 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003093 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003094 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003095 do{
drh734c9862008-11-28 15:37:20 +00003096#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003097 got = osPread(id->h, pBuf, cnt, offset);
3098 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003099#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003100 got = osPread64(id->h, pBuf, cnt, offset);
3101 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003102#else
drh58024642011-11-07 18:16:00 +00003103 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003104 SimulateIOError( newOffset = -1 );
3105 if( newOffset<0 ){
3106 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003107 return -1;
drh734c9862008-11-28 15:37:20 +00003108 }
drh58024642011-11-07 18:16:00 +00003109 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003110#endif
drh58024642011-11-07 18:16:00 +00003111 if( got==cnt ) break;
3112 if( got<0 ){
3113 if( errno==EINTR ){ got = 1; continue; }
3114 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003115 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003116 break;
3117 }else if( got>0 ){
3118 cnt -= got;
3119 offset += got;
3120 prior += got;
3121 pBuf = (void*)(got + (char*)pBuf);
3122 }
3123 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003124 TIMER_END;
drh58024642011-11-07 18:16:00 +00003125 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3126 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3127 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003128}
3129
3130/*
drh734c9862008-11-28 15:37:20 +00003131** Read data from a file into a buffer. Return SQLITE_OK if all
3132** bytes were read successfully and SQLITE_IOERR if anything goes
3133** wrong.
drh339eb0b2008-03-07 15:34:11 +00003134*/
drh734c9862008-11-28 15:37:20 +00003135static int unixRead(
3136 sqlite3_file *id,
3137 void *pBuf,
3138 int amt,
3139 sqlite3_int64 offset
3140){
dan08da86a2009-08-21 17:18:03 +00003141 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003142 int got;
3143 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003144 assert( offset>=0 );
3145 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003146
dan08da86a2009-08-21 17:18:03 +00003147 /* If this is a database file (not a journal, master-journal or temp
3148 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003149#if 0
dane946c392009-08-22 11:39:46 +00003150 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003151 || offset>=PENDING_BYTE+512
3152 || offset+amt<=PENDING_BYTE
3153 );
dan7c246102010-04-12 19:00:29 +00003154#endif
drh08c6d442009-02-09 17:34:07 +00003155
drh9b4c59f2013-04-15 17:03:42 +00003156#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003157 /* Deal with as much of this read request as possible by transfering
3158 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003159 if( offset<pFile->mmapSize ){
3160 if( offset+amt <= pFile->mmapSize ){
3161 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3162 return SQLITE_OK;
3163 }else{
3164 int nCopy = pFile->mmapSize - offset;
3165 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3166 pBuf = &((u8 *)pBuf)[nCopy];
3167 amt -= nCopy;
3168 offset += nCopy;
3169 }
3170 }
drh6e0b6d52013-04-09 16:19:20 +00003171#endif
danf23da962013-03-23 21:00:41 +00003172
dan08da86a2009-08-21 17:18:03 +00003173 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003174 if( got==amt ){
3175 return SQLITE_OK;
3176 }else if( got<0 ){
3177 /* lastErrno set by seekAndRead */
3178 return SQLITE_IOERR_READ;
3179 }else{
drh4bf66fd2015-02-19 02:43:02 +00003180 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003181 /* Unread parts of the buffer must be zero-filled */
3182 memset(&((char*)pBuf)[got], 0, amt-got);
3183 return SQLITE_IOERR_SHORT_READ;
3184 }
3185}
3186
3187/*
dan47a2b4a2013-04-26 16:09:29 +00003188** Attempt to seek the file-descriptor passed as the first argument to
3189** absolute offset iOff, then attempt to write nBuf bytes of data from
3190** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3191** return the actual number of bytes written (which may be less than
3192** nBuf).
3193*/
3194static int seekAndWriteFd(
3195 int fd, /* File descriptor to write to */
3196 i64 iOff, /* File offset to begin writing at */
3197 const void *pBuf, /* Copy data from this buffer to the file */
3198 int nBuf, /* Size of buffer pBuf in bytes */
3199 int *piErrno /* OUT: Error number if error occurs */
3200){
3201 int rc = 0; /* Value returned by system call */
3202
3203 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003204 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003205 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003206 nBuf &= 0x1ffff;
3207 TIMER_START;
3208
3209#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003210 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003211#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003212 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003213#else
3214 do{
3215 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003216 SimulateIOError( iSeek = -1 );
3217 if( iSeek<0 ){
3218 rc = -1;
3219 break;
dan47a2b4a2013-04-26 16:09:29 +00003220 }
3221 rc = osWrite(fd, pBuf, nBuf);
3222 }while( rc<0 && errno==EINTR );
3223#endif
3224
3225 TIMER_END;
3226 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3227
drhe1818ec2015-12-01 16:21:35 +00003228 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003229 return rc;
3230}
3231
3232
3233/*
drh734c9862008-11-28 15:37:20 +00003234** Seek to the offset in id->offset then read cnt bytes into pBuf.
3235** Return the number of bytes actually read. Update the offset.
3236**
3237** To avoid stomping the errno value on a failed write the lastErrno value
3238** is set before returning.
3239*/
3240static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003241 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003242}
3243
3244
3245/*
3246** Write data from a buffer into a file. Return SQLITE_OK on success
3247** or some other error code on failure.
3248*/
3249static int unixWrite(
3250 sqlite3_file *id,
3251 const void *pBuf,
3252 int amt,
3253 sqlite3_int64 offset
3254){
dan08da86a2009-08-21 17:18:03 +00003255 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003256 int wrote = 0;
3257 assert( id );
3258 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003259
dan08da86a2009-08-21 17:18:03 +00003260 /* If this is a database file (not a journal, master-journal or temp
3261 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003262#if 0
dane946c392009-08-22 11:39:46 +00003263 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003264 || offset>=PENDING_BYTE+512
3265 || offset+amt<=PENDING_BYTE
3266 );
dan7c246102010-04-12 19:00:29 +00003267#endif
drh08c6d442009-02-09 17:34:07 +00003268
drhd3d8c042012-05-29 17:02:40 +00003269#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003270 /* If we are doing a normal write to a database file (as opposed to
3271 ** doing a hot-journal rollback or a write to some file other than a
3272 ** normal database file) then record the fact that the database
3273 ** has changed. If the transaction counter is modified, record that
3274 ** fact too.
3275 */
dan08da86a2009-08-21 17:18:03 +00003276 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003277 pFile->dbUpdate = 1; /* The database has been modified */
3278 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003279 int rc;
drh8f941bc2009-01-14 23:03:40 +00003280 char oldCntr[4];
3281 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003282 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003283 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003284 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003285 pFile->transCntrChng = 1; /* The transaction counter has changed */
3286 }
3287 }
3288 }
3289#endif
3290
danfe33e392015-11-17 20:56:06 +00003291#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003292 /* Deal with as much of this write request as possible by transfering
3293 ** data from the memory mapping using memcpy(). */
3294 if( offset<pFile->mmapSize ){
3295 if( offset+amt <= pFile->mmapSize ){
3296 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3297 return SQLITE_OK;
3298 }else{
3299 int nCopy = pFile->mmapSize - offset;
3300 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3301 pBuf = &((u8 *)pBuf)[nCopy];
3302 amt -= nCopy;
3303 offset += nCopy;
3304 }
3305 }
drh6e0b6d52013-04-09 16:19:20 +00003306#endif
drh02bf8b42015-09-01 23:51:53 +00003307
3308 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003309 amt -= wrote;
3310 offset += wrote;
3311 pBuf = &((char*)pBuf)[wrote];
3312 }
3313 SimulateIOError(( wrote=(-1), amt=1 ));
3314 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003315
drh02bf8b42015-09-01 23:51:53 +00003316 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003317 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003318 /* lastErrno set by seekAndWrite */
3319 return SQLITE_IOERR_WRITE;
3320 }else{
drh4bf66fd2015-02-19 02:43:02 +00003321 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003322 return SQLITE_FULL;
3323 }
3324 }
dan6e09d692010-07-27 18:34:15 +00003325
drh734c9862008-11-28 15:37:20 +00003326 return SQLITE_OK;
3327}
3328
3329#ifdef SQLITE_TEST
3330/*
3331** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003332** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003333*/
3334int sqlite3_sync_count = 0;
3335int sqlite3_fullsync_count = 0;
3336#endif
3337
3338/*
drh89240432009-03-25 01:06:01 +00003339** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003340** Others do no. To be safe, we will stick with the (slightly slower)
3341** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003342** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003343*/
drhf7a4a1b2015-01-10 18:02:45 +00003344#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003345# define fdatasync fsync
3346#endif
3347
3348/*
3349** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3350** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3351** only available on Mac OS X. But that could change.
3352*/
3353#ifdef F_FULLFSYNC
3354# define HAVE_FULLFSYNC 1
3355#else
3356# define HAVE_FULLFSYNC 0
3357#endif
3358
3359
3360/*
3361** The fsync() system call does not work as advertised on many
3362** unix systems. The following procedure is an attempt to make
3363** it work better.
3364**
3365** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3366** for testing when we want to run through the test suite quickly.
3367** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3368** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3369** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003370**
3371** SQLite sets the dataOnly flag if the size of the file is unchanged.
3372** The idea behind dataOnly is that it should only write the file content
3373** to disk, not the inode. We only set dataOnly if the file size is
3374** unchanged since the file size is part of the inode. However,
3375** Ted Ts'o tells us that fdatasync() will also write the inode if the
3376** file size has changed. The only real difference between fdatasync()
3377** and fsync(), Ted tells us, is that fdatasync() will not flush the
3378** inode if the mtime or owner or other inode attributes have changed.
3379** We only care about the file size, not the other file attributes, so
3380** as far as SQLite is concerned, an fdatasync() is always adequate.
3381** So, we always use fdatasync() if it is available, regardless of
3382** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003383*/
3384static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003385 int rc;
drh734c9862008-11-28 15:37:20 +00003386
3387 /* The following "ifdef/elif/else/" block has the same structure as
3388 ** the one below. It is replicated here solely to avoid cluttering
3389 ** up the real code with the UNUSED_PARAMETER() macros.
3390 */
3391#ifdef SQLITE_NO_SYNC
3392 UNUSED_PARAMETER(fd);
3393 UNUSED_PARAMETER(fullSync);
3394 UNUSED_PARAMETER(dataOnly);
3395#elif HAVE_FULLFSYNC
3396 UNUSED_PARAMETER(dataOnly);
3397#else
3398 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003399 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003400#endif
3401
3402 /* Record the number of times that we do a normal fsync() and
3403 ** FULLSYNC. This is used during testing to verify that this procedure
3404 ** gets called with the correct arguments.
3405 */
3406#ifdef SQLITE_TEST
3407 if( fullSync ) sqlite3_fullsync_count++;
3408 sqlite3_sync_count++;
3409#endif
3410
3411 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003412 ** no-op. But go ahead and call fstat() to validate the file
3413 ** descriptor as we need a method to provoke a failure during
3414 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003415 */
3416#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003417 {
3418 struct stat buf;
3419 rc = osFstat(fd, &buf);
3420 }
drh734c9862008-11-28 15:37:20 +00003421#elif HAVE_FULLFSYNC
3422 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003423 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003424 }else{
3425 rc = 1;
3426 }
3427 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003428 ** It shouldn't be possible for fullfsync to fail on the local
3429 ** file system (on OSX), so failure indicates that FULLFSYNC
3430 ** isn't supported for this file system. So, attempt an fsync
3431 ** and (for now) ignore the overhead of a superfluous fcntl call.
3432 ** It'd be better to detect fullfsync support once and avoid
3433 ** the fcntl call every time sync is called.
3434 */
drh734c9862008-11-28 15:37:20 +00003435 if( rc ) rc = fsync(fd);
3436
drh7ed97b92010-01-20 13:07:21 +00003437#elif defined(__APPLE__)
3438 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3439 ** so currently we default to the macro that redefines fdatasync to fsync
3440 */
3441 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003442#else
drh0b647ff2009-03-21 14:41:04 +00003443 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003444#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003445 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003446 rc = fsync(fd);
3447 }
drh0b647ff2009-03-21 14:41:04 +00003448#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003449#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3450
3451 if( OS_VXWORKS && rc!= -1 ){
3452 rc = 0;
3453 }
chw97185482008-11-17 08:05:31 +00003454 return rc;
drhbfe66312006-10-03 17:40:40 +00003455}
3456
drh734c9862008-11-28 15:37:20 +00003457/*
drh0059eae2011-08-08 23:48:40 +00003458** Open a file descriptor to the directory containing file zFilename.
3459** If successful, *pFd is set to the opened file descriptor and
3460** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3461** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3462** value.
3463**
drh90315a22011-08-10 01:52:12 +00003464** The directory file descriptor is used for only one thing - to
3465** fsync() a directory to make sure file creation and deletion events
3466** are flushed to disk. Such fsyncs are not needed on newer
3467** journaling filesystems, but are required on older filesystems.
3468**
3469** This routine can be overridden using the xSetSysCall interface.
3470** The ability to override this routine was added in support of the
3471** chromium sandbox. Opening a directory is a security risk (we are
3472** told) so making it overrideable allows the chromium sandbox to
3473** replace this routine with a harmless no-op. To make this routine
3474** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3475** *pFd set to a negative number.
3476**
drh0059eae2011-08-08 23:48:40 +00003477** If SQLITE_OK is returned, the caller is responsible for closing
3478** the file descriptor *pFd using close().
3479*/
3480static int openDirectory(const char *zFilename, int *pFd){
3481 int ii;
3482 int fd = -1;
3483 char zDirname[MAX_PATHNAME+1];
3484
3485 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003486 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3487 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003488 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003489 }else{
3490 if( zDirname[0]!='/' ) zDirname[0] = '.';
3491 zDirname[1] = 0;
3492 }
3493 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3494 if( fd>=0 ){
3495 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003496 }
3497 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003498 if( fd>=0 ) return SQLITE_OK;
3499 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003500}
3501
3502/*
drh734c9862008-11-28 15:37:20 +00003503** Make sure all writes to a particular file are committed to disk.
3504**
3505** If dataOnly==0 then both the file itself and its metadata (file
3506** size, access time, etc) are synced. If dataOnly!=0 then only the
3507** file data is synced.
3508**
3509** Under Unix, also make sure that the directory entry for the file
3510** has been created by fsync-ing the directory that contains the file.
3511** If we do not do this and we encounter a power failure, the directory
3512** entry for the journal might not exist after we reboot. The next
3513** SQLite to access the file will not know that the journal exists (because
3514** the directory entry for the journal was never created) and the transaction
3515** will not roll back - possibly leading to database corruption.
3516*/
3517static int unixSync(sqlite3_file *id, int flags){
3518 int rc;
3519 unixFile *pFile = (unixFile*)id;
3520
3521 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3522 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3523
3524 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3525 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3526 || (flags&0x0F)==SQLITE_SYNC_FULL
3527 );
3528
3529 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3530 ** line is to test that doing so does not cause any problems.
3531 */
3532 SimulateDiskfullError( return SQLITE_FULL );
3533
3534 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003535 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003536 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3537 SimulateIOError( rc=1 );
3538 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003539 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003540 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003541 }
drh0059eae2011-08-08 23:48:40 +00003542
3543 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003544 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003545 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003546 */
3547 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3548 int dirfd;
3549 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003550 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003551 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003552 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003553 full_fsync(dirfd, 0, 0);
3554 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003555 }else{
3556 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003557 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003558 }
drh0059eae2011-08-08 23:48:40 +00003559 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003560 }
3561 return rc;
3562}
3563
3564/*
3565** Truncate an open file to a specified size
3566*/
3567static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003568 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003569 int rc;
dan6e09d692010-07-27 18:34:15 +00003570 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003571 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003572
3573 /* If the user has configured a chunk-size for this file, truncate the
3574 ** file so that it consists of an integer number of chunks (i.e. the
3575 ** actual file size after the operation may be larger than the requested
3576 ** size).
3577 */
drhb8af4b72012-04-05 20:04:39 +00003578 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003579 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3580 }
3581
dan2ee53412014-09-06 16:49:40 +00003582 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003583 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003584 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003585 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003586 }else{
drhd3d8c042012-05-29 17:02:40 +00003587#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003588 /* If we are doing a normal write to a database file (as opposed to
3589 ** doing a hot-journal rollback or a write to some file other than a
3590 ** normal database file) and we truncate the file to zero length,
3591 ** that effectively updates the change counter. This might happen
3592 ** when restoring a database using the backup API from a zero-length
3593 ** source.
3594 */
dan6e09d692010-07-27 18:34:15 +00003595 if( pFile->inNormalWrite && nByte==0 ){
3596 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003597 }
danf23da962013-03-23 21:00:41 +00003598#endif
danc0003312013-03-22 17:46:11 +00003599
mistachkine98844f2013-08-24 00:59:24 +00003600#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003601 /* If the file was just truncated to a size smaller than the currently
3602 ** mapped region, reduce the effective mapping size as well. SQLite will
3603 ** use read() and write() to access data beyond this point from now on.
3604 */
3605 if( nByte<pFile->mmapSize ){
3606 pFile->mmapSize = nByte;
3607 }
mistachkine98844f2013-08-24 00:59:24 +00003608#endif
drh3313b142009-11-06 04:13:18 +00003609
drh734c9862008-11-28 15:37:20 +00003610 return SQLITE_OK;
3611 }
3612}
3613
3614/*
3615** Determine the current size of a file in bytes
3616*/
3617static int unixFileSize(sqlite3_file *id, i64 *pSize){
3618 int rc;
3619 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003620 assert( id );
3621 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003622 SimulateIOError( rc=1 );
3623 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003624 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003625 return SQLITE_IOERR_FSTAT;
3626 }
3627 *pSize = buf.st_size;
3628
drh8af6c222010-05-14 12:43:01 +00003629 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003630 ** writes a single byte into that file in order to work around a bug
3631 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3632 ** layers, we need to report this file size as zero even though it is
3633 ** really 1. Ticket #3260.
3634 */
3635 if( *pSize==1 ) *pSize = 0;
3636
3637
3638 return SQLITE_OK;
3639}
3640
drhd2cb50b2009-01-09 21:41:17 +00003641#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003642/*
3643** Handler for proxy-locking file-control verbs. Defined below in the
3644** proxying locking division.
3645*/
3646static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003647#endif
drh715ff302008-12-03 22:32:44 +00003648
dan502019c2010-07-28 14:26:17 +00003649/*
3650** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003651** file-control operation. Enlarge the database to nBytes in size
3652** (rounded up to the next chunk-size). If the database is already
3653** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003654*/
3655static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003656 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003657 i64 nSize; /* Required file size */
3658 struct stat buf; /* Used to hold return values of fstat() */
3659
drh4bf66fd2015-02-19 02:43:02 +00003660 if( osFstat(pFile->h, &buf) ){
3661 return SQLITE_IOERR_FSTAT;
3662 }
dan502019c2010-07-28 14:26:17 +00003663
3664 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3665 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003666
dan502019c2010-07-28 14:26:17 +00003667#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003668 /* The code below is handling the return value of osFallocate()
3669 ** correctly. posix_fallocate() is defined to "returns zero on success,
3670 ** or an error number on failure". See the manpage for details. */
3671 int err;
drhff812312011-02-23 13:33:46 +00003672 do{
dan661d71a2011-03-30 19:08:03 +00003673 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3674 }while( err==EINTR );
3675 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003676#else
dan592bf7f2014-12-30 19:58:31 +00003677 /* If the OS does not have posix_fallocate(), fake it. Write a
3678 ** single byte to the last byte in each block that falls entirely
3679 ** within the extended region. Then, if required, a single byte
3680 ** at offset (nSize-1), to set the size of the file correctly.
3681 ** This is a similar technique to that used by glibc on systems
3682 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003683 */
3684 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003685 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003686 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003687
drh053378d2015-12-01 22:09:42 +00003688 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003689 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003690 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003691 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3692 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003693 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003694 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003695 }
dan502019c2010-07-28 14:26:17 +00003696#endif
3697 }
3698 }
3699
mistachkine98844f2013-08-24 00:59:24 +00003700#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003701 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003702 int rc;
3703 if( pFile->szChunk<=0 ){
3704 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003705 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003706 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3707 }
3708 }
3709
3710 rc = unixMapfile(pFile, nByte);
3711 return rc;
3712 }
mistachkine98844f2013-08-24 00:59:24 +00003713#endif
danf23da962013-03-23 21:00:41 +00003714
dan502019c2010-07-28 14:26:17 +00003715 return SQLITE_OK;
3716}
danielk1977ad94b582007-08-20 06:44:22 +00003717
danielk1977e3026632004-06-22 11:29:02 +00003718/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003719** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003720** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3721**
3722** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3723*/
3724static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3725 if( *pArg<0 ){
3726 *pArg = (pFile->ctrlFlags & mask)!=0;
3727 }else if( (*pArg)==0 ){
3728 pFile->ctrlFlags &= ~mask;
3729 }else{
3730 pFile->ctrlFlags |= mask;
3731 }
3732}
3733
drh696b33e2012-12-06 19:01:42 +00003734/* Forward declaration */
3735static int unixGetTempname(int nBuf, char *zBuf);
3736
drhf12b3f62011-12-21 14:42:29 +00003737/*
drh9e33c2c2007-08-31 18:34:59 +00003738** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003739*/
drhcc6bb3e2007-08-31 16:11:35 +00003740static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003741 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003742 switch( op ){
3743 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003744 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003745 return SQLITE_OK;
3746 }
drh4bf66fd2015-02-19 02:43:02 +00003747 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003748 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003749 return SQLITE_OK;
3750 }
dan6e09d692010-07-27 18:34:15 +00003751 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003752 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003753 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003754 }
drh9ff27ec2010-05-19 19:26:05 +00003755 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003756 int rc;
3757 SimulateIOErrorBenign(1);
3758 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3759 SimulateIOErrorBenign(0);
3760 return rc;
drhf0b190d2011-07-26 16:03:07 +00003761 }
3762 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003763 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3764 return SQLITE_OK;
3765 }
drhcb15f352011-12-23 01:04:17 +00003766 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3767 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003768 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003769 }
drhde60fc22011-12-14 17:53:36 +00003770 case SQLITE_FCNTL_VFSNAME: {
3771 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3772 return SQLITE_OK;
3773 }
drh696b33e2012-12-06 19:01:42 +00003774 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003775 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003776 if( zTFile ){
3777 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3778 *(char**)pArg = zTFile;
3779 }
3780 return SQLITE_OK;
3781 }
drhb959a012013-12-07 12:29:22 +00003782 case SQLITE_FCNTL_HAS_MOVED: {
3783 *(int*)pArg = fileHasMoved(pFile);
3784 return SQLITE_OK;
3785 }
mistachkine98844f2013-08-24 00:59:24 +00003786#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003787 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003788 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003789 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003790 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3791 newLimit = sqlite3GlobalConfig.mxMmap;
3792 }
3793 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003794 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003795 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003796 if( pFile->mmapSize>0 ){
3797 unixUnmapfile(pFile);
3798 rc = unixMapfile(pFile, -1);
3799 }
danbcb8a862013-04-08 15:30:41 +00003800 }
drh34e258c2013-05-23 01:40:53 +00003801 return rc;
danb2d3de32013-03-14 18:34:37 +00003802 }
mistachkine98844f2013-08-24 00:59:24 +00003803#endif
drhd3d8c042012-05-29 17:02:40 +00003804#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003805 /* The pager calls this method to signal that it has done
3806 ** a rollback and that the database is therefore unchanged and
3807 ** it hence it is OK for the transaction change counter to be
3808 ** unchanged.
3809 */
3810 case SQLITE_FCNTL_DB_UNCHANGED: {
3811 ((unixFile*)id)->dbUpdate = 0;
3812 return SQLITE_OK;
3813 }
3814#endif
drhd2cb50b2009-01-09 21:41:17 +00003815#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003816 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3817 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003818 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003819 }
drhd2cb50b2009-01-09 21:41:17 +00003820#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003821 }
drh0b52b7d2011-01-26 19:46:22 +00003822 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003823}
3824
3825/*
danielk1977a3d4c882007-03-23 10:08:38 +00003826** Return the sector size in bytes of the underlying block device for
3827** the specified file. This is almost always 512 bytes, but may be
3828** larger for some devices.
3829**
3830** SQLite code assumes this function cannot fail. It also assumes that
3831** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003832** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003833** same for both.
3834*/
drh537dddf2012-10-26 13:46:24 +00003835#ifndef __QNXNTO__
3836static int unixSectorSize(sqlite3_file *NotUsed){
3837 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003838 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003839}
drh537dddf2012-10-26 13:46:24 +00003840#endif
3841
3842/*
3843** The following version of unixSectorSize() is optimized for QNX.
3844*/
3845#ifdef __QNXNTO__
3846#include <sys/dcmd_blk.h>
3847#include <sys/statvfs.h>
3848static int unixSectorSize(sqlite3_file *id){
3849 unixFile *pFile = (unixFile*)id;
3850 if( pFile->sectorSize == 0 ){
3851 struct statvfs fsInfo;
3852
3853 /* Set defaults for non-supported filesystems */
3854 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3855 pFile->deviceCharacteristics = 0;
3856 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3857 return pFile->sectorSize;
3858 }
3859
3860 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3861 pFile->sectorSize = fsInfo.f_bsize;
3862 pFile->deviceCharacteristics =
3863 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3864 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3865 ** the write succeeds */
3866 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3867 ** so it is ordered */
3868 0;
3869 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3870 pFile->sectorSize = fsInfo.f_bsize;
3871 pFile->deviceCharacteristics =
3872 /* etfs cluster size writes are atomic */
3873 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3874 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3875 ** the write succeeds */
3876 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3877 ** so it is ordered */
3878 0;
3879 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3880 pFile->sectorSize = fsInfo.f_bsize;
3881 pFile->deviceCharacteristics =
3882 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3883 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3884 ** the write succeeds */
3885 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3886 ** so it is ordered */
3887 0;
3888 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
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 if( strstr(fsInfo.f_basetype, "dos") ){
3897 pFile->sectorSize = fsInfo.f_bsize;
3898 pFile->deviceCharacteristics =
3899 /* full bitset of atomics from max sector size and smaller */
3900 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3901 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3902 ** so it is ordered */
3903 0;
3904 }else{
3905 pFile->deviceCharacteristics =
3906 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3907 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3908 ** the write succeeds */
3909 0;
3910 }
3911 }
3912 /* Last chance verification. If the sector size isn't a multiple of 512
3913 ** then it isn't valid.*/
3914 if( pFile->sectorSize % 512 != 0 ){
3915 pFile->deviceCharacteristics = 0;
3916 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3917 }
3918 return pFile->sectorSize;
3919}
3920#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003921
danielk197790949c22007-08-17 16:50:38 +00003922/*
drhf12b3f62011-12-21 14:42:29 +00003923** Return the device characteristics for the file.
3924**
drhcb15f352011-12-23 01:04:17 +00003925** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003926** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003927** file system does not always provide powersafe overwrites. (In other
3928** words, after a power-loss event, parts of the file that were never
3929** written might end up being altered.) However, non-PSOW behavior is very,
3930** very rare. And asserting PSOW makes a large reduction in the amount
3931** of required I/O for journaling, since a lot of padding is eliminated.
3932** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3933** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003934*/
drhf12b3f62011-12-21 14:42:29 +00003935static int unixDeviceCharacteristics(sqlite3_file *id){
3936 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003937 int rc = 0;
3938#ifdef __QNXNTO__
3939 if( p->sectorSize==0 ) unixSectorSize(id);
3940 rc = p->deviceCharacteristics;
3941#endif
drhcb15f352011-12-23 01:04:17 +00003942 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003943 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003944 }
drh537dddf2012-10-26 13:46:24 +00003945 return rc;
danielk197762079062007-08-15 17:08:46 +00003946}
3947
dan702eec12014-06-23 10:04:58 +00003948#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003949
dan702eec12014-06-23 10:04:58 +00003950/*
3951** Return the system page size.
3952**
3953** This function should not be called directly by other code in this file.
3954** Instead, it should be called via macro osGetpagesize().
3955*/
3956static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003957#if OS_VXWORKS
3958 return 1024;
3959#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003960 return getpagesize();
3961#else
3962 return (int)sysconf(_SC_PAGESIZE);
3963#endif
3964}
3965
3966#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3967
3968#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003969
3970/*
drhd91c68f2010-05-14 14:52:25 +00003971** Object used to represent an shared memory buffer.
3972**
3973** When multiple threads all reference the same wal-index, each thread
3974** has its own unixShm object, but they all point to a single instance
3975** of this unixShmNode object. In other words, each wal-index is opened
3976** only once per process.
3977**
3978** Each unixShmNode object is connected to a single unixInodeInfo object.
3979** We could coalesce this object into unixInodeInfo, but that would mean
3980** every open file that does not use shared memory (in other words, most
3981** open files) would have to carry around this extra information. So
3982** the unixInodeInfo object contains a pointer to this unixShmNode object
3983** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003984**
3985** unixMutexHeld() must be true when creating or destroying
3986** this object or while reading or writing the following fields:
3987**
3988** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003989**
3990** The following fields are read-only after the object is created:
3991**
3992** fid
3993** zFilename
3994**
drhd91c68f2010-05-14 14:52:25 +00003995** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003996** unixMutexHeld() is true when reading or writing any other field
3997** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003998*/
drhd91c68f2010-05-14 14:52:25 +00003999struct unixShmNode {
4000 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004001 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004002 char *zFilename; /* Name of the mmapped file */
4003 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004004 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004005 u16 nRegion; /* Size of array apRegion */
4006 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004007 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004008 int nRef; /* Number of unixShm objects pointing to this */
4009 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004010#ifdef SQLITE_DEBUG
4011 u8 exclMask; /* Mask of exclusive locks held */
4012 u8 sharedMask; /* Mask of shared locks held */
4013 u8 nextShmId; /* Next available unixShm.id value */
4014#endif
4015};
4016
4017/*
drhd9e5c4f2010-05-12 18:01:39 +00004018** Structure used internally by this VFS to record the state of an
4019** open shared memory connection.
4020**
drhd91c68f2010-05-14 14:52:25 +00004021** The following fields are initialized when this object is created and
4022** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004023**
drhd91c68f2010-05-14 14:52:25 +00004024** unixShm.pFile
4025** unixShm.id
4026**
4027** All other fields are read/write. The unixShm.pFile->mutex must be held
4028** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004029*/
4030struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004031 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4032 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004033 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004034 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004035 u16 sharedMask; /* Mask of shared locks held */
4036 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004037};
4038
4039/*
drhd9e5c4f2010-05-12 18:01:39 +00004040** Constants used for locking
4041*/
drhbd9676c2010-06-23 17:58:38 +00004042#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004043#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004044
drhd9e5c4f2010-05-12 18:01:39 +00004045/*
drh73b64e42010-05-30 19:55:15 +00004046** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004047**
4048** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4049** otherwise.
4050*/
4051static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004052 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004053 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004054 int ofst, /* First byte of the locking range */
4055 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004056){
drhbbf76ee2015-03-10 20:22:35 +00004057 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4058 struct flock f; /* The posix advisory locking structure */
4059 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004060
drhd91c68f2010-05-14 14:52:25 +00004061 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004062 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004063 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004064
drh73b64e42010-05-30 19:55:15 +00004065 /* Shared locks never span more than one byte */
4066 assert( n==1 || lockType!=F_RDLCK );
4067
4068 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004069 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004070
drh3cb93392011-03-12 18:10:44 +00004071 if( pShmNode->h>=0 ){
4072 /* Initialize the locking parameters */
4073 memset(&f, 0, sizeof(f));
4074 f.l_type = lockType;
4075 f.l_whence = SEEK_SET;
4076 f.l_start = ofst;
4077 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004078
drhdcfb9652015-12-02 00:05:26 +00004079 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004080 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4081 }
drhd9e5c4f2010-05-12 18:01:39 +00004082
4083 /* Update the global lock state and do debug tracing */
4084#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004085 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004086 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004087 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004088 if( rc==SQLITE_OK ){
4089 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004090 OSTRACE(("unlock %d ok", ofst));
4091 pShmNode->exclMask &= ~mask;
4092 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004093 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004094 OSTRACE(("read-lock %d ok", ofst));
4095 pShmNode->exclMask &= ~mask;
4096 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004097 }else{
4098 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004099 OSTRACE(("write-lock %d ok", ofst));
4100 pShmNode->exclMask |= mask;
4101 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004102 }
4103 }else{
4104 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004105 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004106 }else if( lockType==F_RDLCK ){
4107 OSTRACE(("read-lock failed"));
4108 }else{
4109 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004110 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004111 }
4112 }
drh20e1f082010-05-31 16:10:12 +00004113 OSTRACE((" - afterwards %03x,%03x\n",
4114 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004115 }
drhd9e5c4f2010-05-12 18:01:39 +00004116#endif
4117
4118 return rc;
4119}
4120
dan781e34c2014-03-20 08:59:47 +00004121/*
dan781e34c2014-03-20 08:59:47 +00004122** Return the minimum number of 32KB shm regions that should be mapped at
4123** a time, assuming that each mapping must be an integer multiple of the
4124** current system page-size.
4125**
4126** Usually, this is 1. The exception seems to be systems that are configured
4127** to use 64KB pages - in this case each mapping must cover at least two
4128** shm regions.
4129*/
4130static int unixShmRegionPerMap(void){
4131 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004132 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004133 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4134 if( pgsz<shmsz ) return 1;
4135 return pgsz/shmsz;
4136}
drhd9e5c4f2010-05-12 18:01:39 +00004137
4138/*
drhd91c68f2010-05-14 14:52:25 +00004139** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004140**
4141** This is not a VFS shared-memory method; it is a utility function called
4142** by VFS shared-memory methods.
4143*/
drhd91c68f2010-05-14 14:52:25 +00004144static void unixShmPurge(unixFile *pFd){
4145 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004146 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004147 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004148 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004149 int i;
drhd91c68f2010-05-14 14:52:25 +00004150 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004151 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004152 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004153 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004154 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004155 }else{
4156 sqlite3_free(p->apRegion[i]);
4157 }
dan13a3cb82010-06-11 19:04:21 +00004158 }
dan18801912010-06-14 14:07:50 +00004159 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004160 if( p->h>=0 ){
4161 robust_close(pFd, p->h, __LINE__);
4162 p->h = -1;
4163 }
drhd91c68f2010-05-14 14:52:25 +00004164 p->pInode->pShmNode = 0;
4165 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004166 }
4167}
4168
4169/*
danda9fe0c2010-07-13 18:44:03 +00004170** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004171** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004172**
drh7234c6d2010-06-19 15:10:09 +00004173** The file used to implement shared-memory is in the same directory
4174** as the open database file and has the same name as the open database
4175** file with the "-shm" suffix added. For example, if the database file
4176** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004177** for shared memory will be called "/home/user1/config.db-shm".
4178**
4179** Another approach to is to use files in /dev/shm or /dev/tmp or an
4180** some other tmpfs mount. But if a file in a different directory
4181** from the database file is used, then differing access permissions
4182** or a chroot() might cause two different processes on the same
4183** database to end up using different files for shared memory -
4184** meaning that their memory would not really be shared - resulting
4185** in database corruption. Nevertheless, this tmpfs file usage
4186** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4187** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4188** option results in an incompatible build of SQLite; builds of SQLite
4189** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4190** same database file at the same time, database corruption will likely
4191** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4192** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004193**
4194** When opening a new shared-memory file, if no other instances of that
4195** file are currently open, in this process or in other processes, then
4196** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004197**
4198** If the original database file (pDbFd) is using the "unix-excl" VFS
4199** that means that an exclusive lock is held on the database file and
4200** that no other processes are able to read or write the database. In
4201** that case, we do not really need shared memory. No shared memory
4202** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004203*/
danda9fe0c2010-07-13 18:44:03 +00004204static int unixOpenSharedMemory(unixFile *pDbFd){
4205 struct unixShm *p = 0; /* The connection to be opened */
4206 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4207 int rc; /* Result code */
4208 unixInodeInfo *pInode; /* The inode of fd */
4209 char *zShmFilename; /* Name of the file used for SHM */
4210 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004211
danda9fe0c2010-07-13 18:44:03 +00004212 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004213 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004214 if( p==0 ) return SQLITE_NOMEM;
4215 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004216 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004217
danda9fe0c2010-07-13 18:44:03 +00004218 /* Check to see if a unixShmNode object already exists. Reuse an existing
4219 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004220 */
4221 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004222 pInode = pDbFd->pInode;
4223 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004224 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004225 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004226#ifndef SQLITE_SHM_DIRECTORY
4227 const char *zBasePath = pDbFd->zPath;
4228#endif
danddb0ac42010-07-14 14:48:58 +00004229
4230 /* Call fstat() to figure out the permissions on the database file. If
4231 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004232 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004233 */
drhf3b1ed02015-12-02 13:11:03 +00004234 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004235 rc = SQLITE_IOERR_FSTAT;
4236 goto shm_open_err;
4237 }
4238
drha4ced192010-07-15 18:32:40 +00004239#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004240 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004241#else
drh4bf66fd2015-02-19 02:43:02 +00004242 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004243#endif
drhf3cdcdc2015-04-29 16:50:28 +00004244 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004245 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004246 rc = SQLITE_NOMEM;
4247 goto shm_open_err;
4248 }
drh9cb5a0d2012-01-05 21:19:54 +00004249 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004250 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004251#ifdef SQLITE_SHM_DIRECTORY
4252 sqlite3_snprintf(nShmFilename, zShmFilename,
4253 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4254 (u32)sStat.st_ino, (u32)sStat.st_dev);
4255#else
drh4bf66fd2015-02-19 02:43:02 +00004256 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004257 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004258#endif
drhd91c68f2010-05-14 14:52:25 +00004259 pShmNode->h = -1;
4260 pDbFd->pInode->pShmNode = pShmNode;
4261 pShmNode->pInode = pDbFd->pInode;
4262 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4263 if( pShmNode->mutex==0 ){
4264 rc = SQLITE_NOMEM;
4265 goto shm_open_err;
4266 }
drhd9e5c4f2010-05-12 18:01:39 +00004267
drh3cb93392011-03-12 18:10:44 +00004268 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004269 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004270 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004271 openFlags = O_RDONLY;
4272 pShmNode->isReadonly = 1;
4273 }
4274 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004275 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004276 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4277 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004278 }
drhac7c3ac2012-02-11 19:23:48 +00004279
4280 /* If this process is running as root, make sure that the SHM file
4281 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004282 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004283 */
drh6226ca22015-11-24 15:06:28 +00004284 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004285
4286 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004287 ** If not, truncate the file to zero length.
4288 */
4289 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004290 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004291 if( robust_ftruncate(pShmNode->h, 0) ){
4292 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004293 }
4294 }
drh66dfec8b2011-06-01 20:01:49 +00004295 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004296 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004297 }
4298 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004299 }
drhd9e5c4f2010-05-12 18:01:39 +00004300 }
4301
drhd91c68f2010-05-14 14:52:25 +00004302 /* Make the new connection a child of the unixShmNode */
4303 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004304#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004305 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004306#endif
drhd91c68f2010-05-14 14:52:25 +00004307 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004308 pDbFd->pShm = p;
4309 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004310
4311 /* The reference count on pShmNode has already been incremented under
4312 ** the cover of the unixEnterMutex() mutex and the pointer from the
4313 ** new (struct unixShm) object to the pShmNode has been set. All that is
4314 ** left to do is to link the new object into the linked list starting
4315 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4316 ** mutex.
4317 */
4318 sqlite3_mutex_enter(pShmNode->mutex);
4319 p->pNext = pShmNode->pFirst;
4320 pShmNode->pFirst = p;
4321 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004322 return SQLITE_OK;
4323
4324 /* Jump here on any error */
4325shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004326 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004327 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004328 unixLeaveMutex();
4329 return rc;
4330}
4331
4332/*
danda9fe0c2010-07-13 18:44:03 +00004333** This function is called to obtain a pointer to region iRegion of the
4334** shared-memory associated with the database file fd. Shared-memory regions
4335** are numbered starting from zero. Each shared-memory region is szRegion
4336** bytes in size.
4337**
4338** If an error occurs, an error code is returned and *pp is set to NULL.
4339**
4340** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4341** region has not been allocated (by any client, including one running in a
4342** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4343** bExtend is non-zero and the requested shared-memory region has not yet
4344** been allocated, it is allocated by this function.
4345**
4346** If the shared-memory region has already been allocated or is allocated by
4347** this call as described above, then it is mapped into this processes
4348** address space (if it is not already), *pp is set to point to the mapped
4349** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004350*/
danda9fe0c2010-07-13 18:44:03 +00004351static int unixShmMap(
4352 sqlite3_file *fd, /* Handle open on database file */
4353 int iRegion, /* Region to retrieve */
4354 int szRegion, /* Size of regions */
4355 int bExtend, /* True to extend file if necessary */
4356 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004357){
danda9fe0c2010-07-13 18:44:03 +00004358 unixFile *pDbFd = (unixFile*)fd;
4359 unixShm *p;
4360 unixShmNode *pShmNode;
4361 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004362 int nShmPerMap = unixShmRegionPerMap();
4363 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004364
danda9fe0c2010-07-13 18:44:03 +00004365 /* If the shared-memory file has not yet been opened, open it now. */
4366 if( pDbFd->pShm==0 ){
4367 rc = unixOpenSharedMemory(pDbFd);
4368 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004369 }
drhd9e5c4f2010-05-12 18:01:39 +00004370
danda9fe0c2010-07-13 18:44:03 +00004371 p = pDbFd->pShm;
4372 pShmNode = p->pShmNode;
4373 sqlite3_mutex_enter(pShmNode->mutex);
4374 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004375 assert( pShmNode->pInode==pDbFd->pInode );
4376 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4377 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004378
dan781e34c2014-03-20 08:59:47 +00004379 /* Minimum number of regions required to be mapped. */
4380 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4381
4382 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004383 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004384 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004385 struct stat sStat; /* Used by fstat() */
4386
4387 pShmNode->szRegion = szRegion;
4388
drh3cb93392011-03-12 18:10:44 +00004389 if( pShmNode->h>=0 ){
4390 /* The requested region is not mapped into this processes address space.
4391 ** Check to see if it has been allocated (i.e. if the wal-index file is
4392 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004393 */
drh3cb93392011-03-12 18:10:44 +00004394 if( osFstat(pShmNode->h, &sStat) ){
4395 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004396 goto shmpage_out;
4397 }
drh3cb93392011-03-12 18:10:44 +00004398
4399 if( sStat.st_size<nByte ){
4400 /* The requested memory region does not exist. If bExtend is set to
4401 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004402 */
dan47a2b4a2013-04-26 16:09:29 +00004403 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004404 goto shmpage_out;
4405 }
dan47a2b4a2013-04-26 16:09:29 +00004406
4407 /* Alternatively, if bExtend is true, extend the file. Do this by
4408 ** writing a single byte to the end of each (OS) page being
4409 ** allocated or extended. Technically, we need only write to the
4410 ** last page in order to extend the file. But writing to all new
4411 ** pages forces the OS to allocate them immediately, which reduces
4412 ** the chances of SIGBUS while accessing the mapped region later on.
4413 */
4414 else{
4415 static const int pgsz = 4096;
4416 int iPg;
4417
4418 /* Write to the last byte of each newly allocated or extended page */
4419 assert( (nByte % pgsz)==0 );
4420 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004421 int x = 0;
4422 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004423 const char *zFile = pShmNode->zFilename;
4424 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4425 goto shmpage_out;
4426 }
4427 }
drh3cb93392011-03-12 18:10:44 +00004428 }
4429 }
danda9fe0c2010-07-13 18:44:03 +00004430 }
4431
4432 /* Map the requested memory region into this processes address space. */
4433 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004434 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004435 );
4436 if( !apNew ){
4437 rc = SQLITE_IOERR_NOMEM;
4438 goto shmpage_out;
4439 }
4440 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004441 while( pShmNode->nRegion<nReqRegion ){
4442 int nMap = szRegion*nShmPerMap;
4443 int i;
drh3cb93392011-03-12 18:10:44 +00004444 void *pMem;
4445 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004446 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004447 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004448 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004449 );
4450 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004451 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004452 goto shmpage_out;
4453 }
4454 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004455 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004456 if( pMem==0 ){
4457 rc = SQLITE_NOMEM;
4458 goto shmpage_out;
4459 }
4460 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004461 }
dan781e34c2014-03-20 08:59:47 +00004462
4463 for(i=0; i<nShmPerMap; i++){
4464 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4465 }
4466 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004467 }
4468 }
4469
4470shmpage_out:
4471 if( pShmNode->nRegion>iRegion ){
4472 *pp = pShmNode->apRegion[iRegion];
4473 }else{
4474 *pp = 0;
4475 }
drh66dfec8b2011-06-01 20:01:49 +00004476 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004477 sqlite3_mutex_leave(pShmNode->mutex);
4478 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004479}
4480
4481/*
drhd9e5c4f2010-05-12 18:01:39 +00004482** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004483**
4484** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4485** different here than in posix. In xShmLock(), one can go from unlocked
4486** to shared and back or from unlocked to exclusive and back. But one may
4487** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004488*/
4489static int unixShmLock(
4490 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004491 int ofst, /* First lock to acquire or release */
4492 int n, /* Number of locks to acquire or release */
4493 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004494){
drh73b64e42010-05-30 19:55:15 +00004495 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4496 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4497 unixShm *pX; /* For looping over all siblings */
4498 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4499 int rc = SQLITE_OK; /* Result code */
4500 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004501
drhd91c68f2010-05-14 14:52:25 +00004502 assert( pShmNode==pDbFd->pInode->pShmNode );
4503 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004504 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004505 assert( n>=1 );
4506 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4507 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4508 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4509 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4510 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004511 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4512 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004513
drhc99597c2010-05-31 01:41:15 +00004514 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004515 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004516 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004517 if( flags & SQLITE_SHM_UNLOCK ){
4518 u16 allMask = 0; /* Mask of locks held by siblings */
4519
4520 /* See if any siblings hold this same lock */
4521 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4522 if( pX==p ) continue;
4523 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4524 allMask |= pX->sharedMask;
4525 }
4526
4527 /* Unlock the system-level locks */
4528 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004529 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004530 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004531 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004532 }
drh73b64e42010-05-30 19:55:15 +00004533
4534 /* Undo the local locks */
4535 if( rc==SQLITE_OK ){
4536 p->exclMask &= ~mask;
4537 p->sharedMask &= ~mask;
4538 }
4539 }else if( flags & SQLITE_SHM_SHARED ){
4540 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4541
4542 /* Find out which shared locks are already held by sibling connections.
4543 ** If any sibling already holds an exclusive lock, go ahead and return
4544 ** SQLITE_BUSY.
4545 */
4546 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004547 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004548 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004549 break;
4550 }
4551 allShared |= pX->sharedMask;
4552 }
4553
4554 /* Get shared locks at the system level, if necessary */
4555 if( rc==SQLITE_OK ){
4556 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004557 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004558 }else{
drh73b64e42010-05-30 19:55:15 +00004559 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004560 }
drhd9e5c4f2010-05-12 18:01:39 +00004561 }
drh73b64e42010-05-30 19:55:15 +00004562
4563 /* Get the local shared locks */
4564 if( rc==SQLITE_OK ){
4565 p->sharedMask |= mask;
4566 }
4567 }else{
4568 /* Make sure no sibling connections hold locks that will block this
4569 ** lock. If any do, return SQLITE_BUSY right away.
4570 */
4571 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004572 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4573 rc = SQLITE_BUSY;
4574 break;
4575 }
4576 }
4577
4578 /* Get the exclusive locks at the system level. Then if successful
4579 ** also mark the local connection as being locked.
4580 */
4581 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004582 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004583 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004584 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004585 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004586 }
drhd9e5c4f2010-05-12 18:01:39 +00004587 }
4588 }
drhd91c68f2010-05-14 14:52:25 +00004589 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004590 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004591 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004592 return rc;
4593}
4594
drh286a2882010-05-20 23:51:06 +00004595/*
4596** Implement a memory barrier or memory fence on shared memory.
4597**
4598** All loads and stores begun before the barrier must complete before
4599** any load or store begun after the barrier.
4600*/
4601static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004602 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004603){
drhff828942010-06-26 21:34:06 +00004604 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004605 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4606 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004607 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004608}
4609
dan18801912010-06-14 14:07:50 +00004610/*
danda9fe0c2010-07-13 18:44:03 +00004611** Close a connection to shared-memory. Delete the underlying
4612** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004613**
4614** If there is no shared memory associated with the connection then this
4615** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004616*/
danda9fe0c2010-07-13 18:44:03 +00004617static int unixShmUnmap(
4618 sqlite3_file *fd, /* The underlying database file */
4619 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004620){
danda9fe0c2010-07-13 18:44:03 +00004621 unixShm *p; /* The connection to be closed */
4622 unixShmNode *pShmNode; /* The underlying shared-memory file */
4623 unixShm **pp; /* For looping over sibling connections */
4624 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004625
danda9fe0c2010-07-13 18:44:03 +00004626 pDbFd = (unixFile*)fd;
4627 p = pDbFd->pShm;
4628 if( p==0 ) return SQLITE_OK;
4629 pShmNode = p->pShmNode;
4630
4631 assert( pShmNode==pDbFd->pInode->pShmNode );
4632 assert( pShmNode->pInode==pDbFd->pInode );
4633
4634 /* Remove connection p from the set of connections associated
4635 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004636 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004637 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4638 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004639
danda9fe0c2010-07-13 18:44:03 +00004640 /* Free the connection p */
4641 sqlite3_free(p);
4642 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004643 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004644
4645 /* If pShmNode->nRef has reached 0, then close the underlying
4646 ** shared-memory file, too */
4647 unixEnterMutex();
4648 assert( pShmNode->nRef>0 );
4649 pShmNode->nRef--;
4650 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004651 if( deleteFlag && pShmNode->h>=0 ){
4652 osUnlink(pShmNode->zFilename);
4653 }
danda9fe0c2010-07-13 18:44:03 +00004654 unixShmPurge(pDbFd);
4655 }
4656 unixLeaveMutex();
4657
4658 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004659}
drh286a2882010-05-20 23:51:06 +00004660
danda9fe0c2010-07-13 18:44:03 +00004661
drhd9e5c4f2010-05-12 18:01:39 +00004662#else
drh6b017cc2010-06-14 18:01:46 +00004663# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004664# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004665# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004666# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004667#endif /* #ifndef SQLITE_OMIT_WAL */
4668
mistachkine98844f2013-08-24 00:59:24 +00004669#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004670/*
danaef49d72013-03-25 16:28:54 +00004671** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004672*/
danf23da962013-03-23 21:00:41 +00004673static void unixUnmapfile(unixFile *pFd){
4674 assert( pFd->nFetchOut==0 );
4675 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004676 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004677 pFd->pMapRegion = 0;
4678 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004679 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004680 }
4681}
dan5d8a1372013-03-19 19:28:06 +00004682
danaef49d72013-03-25 16:28:54 +00004683/*
dane6ecd662013-04-01 17:56:59 +00004684** Attempt to set the size of the memory mapping maintained by file
4685** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4686**
4687** If successful, this function sets the following variables:
4688**
4689** unixFile.pMapRegion
4690** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004691** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004692**
4693** If unsuccessful, an error message is logged via sqlite3_log() and
4694** the three variables above are zeroed. In this case SQLite should
4695** continue accessing the database using the xRead() and xWrite()
4696** methods.
4697*/
4698static void unixRemapfile(
4699 unixFile *pFd, /* File descriptor object */
4700 i64 nNew /* Required mapping size */
4701){
dan4ff7bc42013-04-02 12:04:09 +00004702 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004703 int h = pFd->h; /* File descriptor open on db file */
4704 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004705 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004706 u8 *pNew = 0; /* Location of new mapping */
4707 int flags = PROT_READ; /* Flags to pass to mmap() */
4708
4709 assert( pFd->nFetchOut==0 );
4710 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004711 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004712 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004713 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004714 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004715
danfe33e392015-11-17 20:56:06 +00004716#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004717 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004718#endif
dane6ecd662013-04-01 17:56:59 +00004719
4720 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004721#if HAVE_MREMAP
4722 i64 nReuse = pFd->mmapSize;
4723#else
danbc760632014-03-20 09:42:09 +00004724 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004725 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004726#endif
dane6ecd662013-04-01 17:56:59 +00004727 u8 *pReq = &pOrig[nReuse];
4728
4729 /* Unmap any pages of the existing mapping that cannot be reused. */
4730 if( nReuse!=nOrig ){
4731 osMunmap(pReq, nOrig-nReuse);
4732 }
4733
4734#if HAVE_MREMAP
4735 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004736 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004737#else
4738 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4739 if( pNew!=MAP_FAILED ){
4740 if( pNew!=pReq ){
4741 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004742 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004743 }else{
4744 pNew = pOrig;
4745 }
4746 }
4747#endif
4748
dan48ccef82013-04-02 20:55:01 +00004749 /* The attempt to extend the existing mapping failed. Free it. */
4750 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004751 osMunmap(pOrig, nReuse);
4752 }
4753 }
4754
4755 /* If pNew is still NULL, try to create an entirely new mapping. */
4756 if( pNew==0 ){
4757 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004758 }
4759
dan4ff7bc42013-04-02 12:04:09 +00004760 if( pNew==MAP_FAILED ){
4761 pNew = 0;
4762 nNew = 0;
4763 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4764
4765 /* If the mmap() above failed, assume that all subsequent mmap() calls
4766 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4767 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004768 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004769 }
dane6ecd662013-04-01 17:56:59 +00004770 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004771 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004772}
4773
4774/*
danaef49d72013-03-25 16:28:54 +00004775** Memory map or remap the file opened by file-descriptor pFd (if the file
4776** is already mapped, the existing mapping is replaced by the new). Or, if
4777** there already exists a mapping for this file, and there are still
4778** outstanding xFetch() references to it, this function is a no-op.
4779**
4780** If parameter nByte is non-negative, then it is the requested size of
4781** the mapping to create. Otherwise, if nByte is less than zero, then the
4782** requested size is the size of the file on disk. The actual size of the
4783** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004784** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004785**
4786** SQLITE_OK is returned if no error occurs (even if the mapping is not
4787** recreated as a result of outstanding references) or an SQLite error
4788** code otherwise.
4789*/
drhf3b1ed02015-12-02 13:11:03 +00004790static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004791 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004792 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004793 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4794
4795 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004796 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004797 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004798 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004799 }
drh3044b512014-06-16 16:41:52 +00004800 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004801 }
drh9b4c59f2013-04-15 17:03:42 +00004802 if( nMap>pFd->mmapSizeMax ){
4803 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004804 }
4805
drh333e6ca2015-12-02 15:44:39 +00004806 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004807 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004808 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004809 }
4810
danf23da962013-03-23 21:00:41 +00004811 return SQLITE_OK;
4812}
mistachkine98844f2013-08-24 00:59:24 +00004813#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004814
danaef49d72013-03-25 16:28:54 +00004815/*
4816** If possible, return a pointer to a mapping of file fd starting at offset
4817** iOff. The mapping must be valid for at least nAmt bytes.
4818**
4819** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4820** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4821** Finally, if an error does occur, return an SQLite error code. The final
4822** value of *pp is undefined in this case.
4823**
4824** If this function does return a pointer, the caller must eventually
4825** release the reference by calling unixUnfetch().
4826*/
danf23da962013-03-23 21:00:41 +00004827static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004828#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004829 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004830#endif
danf23da962013-03-23 21:00:41 +00004831 *pp = 0;
4832
drh9b4c59f2013-04-15 17:03:42 +00004833#if SQLITE_MAX_MMAP_SIZE>0
4834 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004835 if( pFd->pMapRegion==0 ){
4836 int rc = unixMapfile(pFd, -1);
4837 if( rc!=SQLITE_OK ) return rc;
4838 }
4839 if( pFd->mmapSize >= iOff+nAmt ){
4840 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4841 pFd->nFetchOut++;
4842 }
4843 }
drh6e0b6d52013-04-09 16:19:20 +00004844#endif
danf23da962013-03-23 21:00:41 +00004845 return SQLITE_OK;
4846}
4847
danaef49d72013-03-25 16:28:54 +00004848/*
dandf737fe2013-03-25 17:00:24 +00004849** If the third argument is non-NULL, then this function releases a
4850** reference obtained by an earlier call to unixFetch(). The second
4851** argument passed to this function must be the same as the corresponding
4852** argument that was passed to the unixFetch() invocation.
4853**
4854** Or, if the third argument is NULL, then this function is being called
4855** to inform the VFS layer that, according to POSIX, any existing mapping
4856** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004857*/
dandf737fe2013-03-25 17:00:24 +00004858static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004859#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004860 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004861 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004862
danaef49d72013-03-25 16:28:54 +00004863 /* If p==0 (unmap the entire file) then there must be no outstanding
4864 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4865 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004866 assert( (p==0)==(pFd->nFetchOut==0) );
4867
dandf737fe2013-03-25 17:00:24 +00004868 /* If p!=0, it must match the iOff value. */
4869 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4870
danf23da962013-03-23 21:00:41 +00004871 if( p ){
4872 pFd->nFetchOut--;
4873 }else{
4874 unixUnmapfile(pFd);
4875 }
4876
4877 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004878#else
4879 UNUSED_PARAMETER(fd);
4880 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004881 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004882#endif
danf23da962013-03-23 21:00:41 +00004883 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004884}
4885
4886/*
drh734c9862008-11-28 15:37:20 +00004887** Here ends the implementation of all sqlite3_file methods.
4888**
4889********************** End sqlite3_file Methods *******************************
4890******************************************************************************/
4891
4892/*
drh6b9d6dd2008-12-03 19:34:47 +00004893** This division contains definitions of sqlite3_io_methods objects that
4894** implement various file locking strategies. It also contains definitions
4895** of "finder" functions. A finder-function is used to locate the appropriate
4896** sqlite3_io_methods object for a particular database file. The pAppData
4897** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4898** the correct finder-function for that VFS.
4899**
4900** Most finder functions return a pointer to a fixed sqlite3_io_methods
4901** object. The only interesting finder-function is autolockIoFinder, which
4902** looks at the filesystem type and tries to guess the best locking
4903** strategy from that.
4904**
peter.d.reid60ec9142014-09-06 16:39:46 +00004905** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004906**
4907** (1) The real finder-function named "FImpt()".
4908**
dane946c392009-08-22 11:39:46 +00004909** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004910**
4911**
4912** A pointer to the F pointer is used as the pAppData value for VFS
4913** objects. We have to do this instead of letting pAppData point
4914** directly at the finder-function since C90 rules prevent a void*
4915** from be cast into a function pointer.
4916**
drh6b9d6dd2008-12-03 19:34:47 +00004917**
drh7708e972008-11-29 00:56:52 +00004918** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004919**
drh7708e972008-11-29 00:56:52 +00004920** * A constant sqlite3_io_methods object call METHOD that has locking
4921** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4922**
4923** * An I/O method finder function called FINDER that returns a pointer
4924** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004925*/
drhe6d41732015-02-21 00:49:00 +00004926#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004927static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004928 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004929 CLOSE, /* xClose */ \
4930 unixRead, /* xRead */ \
4931 unixWrite, /* xWrite */ \
4932 unixTruncate, /* xTruncate */ \
4933 unixSync, /* xSync */ \
4934 unixFileSize, /* xFileSize */ \
4935 LOCK, /* xLock */ \
4936 UNLOCK, /* xUnlock */ \
4937 CKLOCK, /* xCheckReservedLock */ \
4938 unixFileControl, /* xFileControl */ \
4939 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004940 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004941 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004942 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004943 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004944 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004945 unixFetch, /* xFetch */ \
4946 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004947}; \
drh0c2694b2009-09-03 16:23:44 +00004948static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4949 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004950 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004951} \
drh0c2694b2009-09-03 16:23:44 +00004952static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004953 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004954
4955/*
4956** Here are all of the sqlite3_io_methods objects for each of the
4957** locking strategies. Functions that return pointers to these methods
4958** are also created.
4959*/
4960IOMETHODS(
4961 posixIoFinder, /* Finder function name */
4962 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004963 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004964 unixClose, /* xClose method */
4965 unixLock, /* xLock method */
4966 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004967 unixCheckReservedLock, /* xCheckReservedLock method */
4968 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004969)
drh7708e972008-11-29 00:56:52 +00004970IOMETHODS(
4971 nolockIoFinder, /* Finder function name */
4972 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004973 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004974 nolockClose, /* xClose method */
4975 nolockLock, /* xLock method */
4976 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004977 nolockCheckReservedLock, /* xCheckReservedLock method */
4978 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004979)
drh7708e972008-11-29 00:56:52 +00004980IOMETHODS(
4981 dotlockIoFinder, /* Finder function name */
4982 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004983 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004984 dotlockClose, /* xClose method */
4985 dotlockLock, /* xLock method */
4986 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004987 dotlockCheckReservedLock, /* xCheckReservedLock method */
4988 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004989)
drh7708e972008-11-29 00:56:52 +00004990
drhe89b2912015-03-03 20:42:01 +00004991#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004992IOMETHODS(
4993 flockIoFinder, /* Finder function name */
4994 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004995 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004996 flockClose, /* xClose method */
4997 flockLock, /* xLock method */
4998 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004999 flockCheckReservedLock, /* xCheckReservedLock method */
5000 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005001)
drh7708e972008-11-29 00:56:52 +00005002#endif
5003
drh6c7d5c52008-11-21 20:32:33 +00005004#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005005IOMETHODS(
5006 semIoFinder, /* Finder function name */
5007 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005008 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005009 semXClose, /* xClose method */
5010 semXLock, /* xLock method */
5011 semXUnlock, /* xUnlock method */
5012 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005013 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005014)
aswiftaebf4132008-11-21 00:10:35 +00005015#endif
drh7708e972008-11-29 00:56:52 +00005016
drhd2cb50b2009-01-09 21:41:17 +00005017#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005018IOMETHODS(
5019 afpIoFinder, /* Finder function name */
5020 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005021 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005022 afpClose, /* xClose method */
5023 afpLock, /* xLock method */
5024 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005025 afpCheckReservedLock, /* xCheckReservedLock method */
5026 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005027)
drh715ff302008-12-03 22:32:44 +00005028#endif
5029
5030/*
5031** The proxy locking method is a "super-method" in the sense that it
5032** opens secondary file descriptors for the conch and lock files and
5033** it uses proxy, dot-file, AFP, and flock() locking methods on those
5034** secondary files. For this reason, the division that implements
5035** proxy locking is located much further down in the file. But we need
5036** to go ahead and define the sqlite3_io_methods and finder function
5037** for proxy locking here. So we forward declare the I/O methods.
5038*/
drhd2cb50b2009-01-09 21:41:17 +00005039#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005040static int proxyClose(sqlite3_file*);
5041static int proxyLock(sqlite3_file*, int);
5042static int proxyUnlock(sqlite3_file*, int);
5043static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005044IOMETHODS(
5045 proxyIoFinder, /* Finder function name */
5046 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005047 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005048 proxyClose, /* xClose method */
5049 proxyLock, /* xLock method */
5050 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005051 proxyCheckReservedLock, /* xCheckReservedLock method */
5052 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005053)
aswiftaebf4132008-11-21 00:10:35 +00005054#endif
drh7708e972008-11-29 00:56:52 +00005055
drh7ed97b92010-01-20 13:07:21 +00005056/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5057#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5058IOMETHODS(
5059 nfsIoFinder, /* Finder function name */
5060 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005061 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005062 unixClose, /* xClose method */
5063 unixLock, /* xLock method */
5064 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005065 unixCheckReservedLock, /* xCheckReservedLock method */
5066 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005067)
5068#endif
drh7708e972008-11-29 00:56:52 +00005069
drhd2cb50b2009-01-09 21:41:17 +00005070#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005071/*
drh6b9d6dd2008-12-03 19:34:47 +00005072** This "finder" function attempts to determine the best locking strategy
5073** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005074** object that implements that strategy.
5075**
5076** This is for MacOSX only.
5077*/
drh1875f7a2008-12-08 18:19:17 +00005078static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005079 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005080 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005081){
5082 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005083 const char *zFilesystem; /* Filesystem type name */
5084 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005085 } aMap[] = {
5086 { "hfs", &posixIoMethods },
5087 { "ufs", &posixIoMethods },
5088 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005089 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005090 { "webdav", &nolockIoMethods },
5091 { 0, 0 }
5092 };
5093 int i;
5094 struct statfs fsInfo;
5095 struct flock lockInfo;
5096
5097 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005098 /* If filePath==NULL that means we are dealing with a transient file
5099 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005100 return &nolockIoMethods;
5101 }
5102 if( statfs(filePath, &fsInfo) != -1 ){
5103 if( fsInfo.f_flags & MNT_RDONLY ){
5104 return &nolockIoMethods;
5105 }
5106 for(i=0; aMap[i].zFilesystem; i++){
5107 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5108 return aMap[i].pMethods;
5109 }
5110 }
5111 }
5112
5113 /* Default case. Handles, amongst others, "nfs".
5114 ** Test byte-range lock using fcntl(). If the call succeeds,
5115 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005116 */
drh7708e972008-11-29 00:56:52 +00005117 lockInfo.l_len = 1;
5118 lockInfo.l_start = 0;
5119 lockInfo.l_whence = SEEK_SET;
5120 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005121 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005122 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5123 return &nfsIoMethods;
5124 } else {
5125 return &posixIoMethods;
5126 }
drh7708e972008-11-29 00:56:52 +00005127 }else{
5128 return &dotlockIoMethods;
5129 }
5130}
drh0c2694b2009-09-03 16:23:44 +00005131static const sqlite3_io_methods
5132 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005133
drhd2cb50b2009-01-09 21:41:17 +00005134#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005135
drhe89b2912015-03-03 20:42:01 +00005136#if OS_VXWORKS
5137/*
5138** This "finder" function for VxWorks checks to see if posix advisory
5139** locking works. If it does, then that is what is used. If it does not
5140** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005141*/
drhe89b2912015-03-03 20:42:01 +00005142static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005143 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005144 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005145){
5146 struct flock lockInfo;
5147
5148 if( !filePath ){
5149 /* If filePath==NULL that means we are dealing with a transient file
5150 ** that does not need to be locked. */
5151 return &nolockIoMethods;
5152 }
5153
5154 /* Test if fcntl() is supported and use POSIX style locks.
5155 ** Otherwise fall back to the named semaphore method.
5156 */
5157 lockInfo.l_len = 1;
5158 lockInfo.l_start = 0;
5159 lockInfo.l_whence = SEEK_SET;
5160 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005161 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005162 return &posixIoMethods;
5163 }else{
5164 return &semIoMethods;
5165 }
5166}
drh0c2694b2009-09-03 16:23:44 +00005167static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005168 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005169
drhe89b2912015-03-03 20:42:01 +00005170#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005171
drh7708e972008-11-29 00:56:52 +00005172/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005173** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005174*/
drh0c2694b2009-09-03 16:23:44 +00005175typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005176
aswiftaebf4132008-11-21 00:10:35 +00005177
drh734c9862008-11-28 15:37:20 +00005178/****************************************************************************
5179**************************** sqlite3_vfs methods ****************************
5180**
5181** This division contains the implementation of methods on the
5182** sqlite3_vfs object.
5183*/
5184
danielk1977a3d4c882007-03-23 10:08:38 +00005185/*
danielk1977e339d652008-06-28 11:23:00 +00005186** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005187*/
5188static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005189 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005190 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005191 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005192 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005193 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005194){
drh7708e972008-11-29 00:56:52 +00005195 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005196 unixFile *pNew = (unixFile *)pId;
5197 int rc = SQLITE_OK;
5198
drh8af6c222010-05-14 12:43:01 +00005199 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005200
dan00157392010-10-05 11:33:15 +00005201 /* Usually the path zFilename should not be a relative pathname. The
5202 ** exception is when opening the proxy "conch" file in builds that
5203 ** include the special Apple locking styles.
5204 */
dan00157392010-10-05 11:33:15 +00005205#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005206 assert( zFilename==0 || zFilename[0]=='/'
5207 || pVfs->pAppData==(void*)&autolockIoFinder );
5208#else
5209 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005210#endif
dan00157392010-10-05 11:33:15 +00005211
drhb07028f2011-10-14 21:49:18 +00005212 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005213 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005214
drh308c2a52010-05-14 11:30:18 +00005215 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005216 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005217 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005218 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005219 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005220#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005221 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005222#endif
drhc02a43a2012-01-10 23:18:38 +00005223 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5224 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005225 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005226 }
drh503a6862013-03-01 01:07:17 +00005227 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005228 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005229 }
drh339eb0b2008-03-07 15:34:11 +00005230
drh6c7d5c52008-11-21 20:32:33 +00005231#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005232 pNew->pId = vxworksFindFileId(zFilename);
5233 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005234 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005235 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005236 }
5237#endif
5238
drhc02a43a2012-01-10 23:18:38 +00005239 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005240 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005241 }else{
drh0c2694b2009-09-03 16:23:44 +00005242 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005243#if SQLITE_ENABLE_LOCKING_STYLE
5244 /* Cache zFilename in the locking context (AFP and dotlock override) for
5245 ** proxyLock activation is possible (remote proxy is based on db name)
5246 ** zFilename remains valid until file is closed, to support */
5247 pNew->lockingContext = (void*)zFilename;
5248#endif
drhda0e7682008-07-30 15:27:54 +00005249 }
danielk1977e339d652008-06-28 11:23:00 +00005250
drh7ed97b92010-01-20 13:07:21 +00005251 if( pLockingStyle == &posixIoMethods
5252#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5253 || pLockingStyle == &nfsIoMethods
5254#endif
5255 ){
drh7708e972008-11-29 00:56:52 +00005256 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005257 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005258 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005259 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005260 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005261 ** in two scenarios:
5262 **
5263 ** (a) A call to fstat() failed.
5264 ** (b) A malloc failed.
5265 **
5266 ** Scenario (b) may only occur if the process is holding no other
5267 ** file descriptors open on the same file. If there were other file
5268 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005269 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005270 ** handle h - as it is guaranteed that no posix locks will be released
5271 ** by doing so.
5272 **
5273 ** If scenario (a) caused the error then things are not so safe. The
5274 ** implicit assumption here is that if fstat() fails, things are in
5275 ** such bad shape that dropping a lock or two doesn't matter much.
5276 */
drh0e9365c2011-03-02 02:08:13 +00005277 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005278 h = -1;
5279 }
drh7708e972008-11-29 00:56:52 +00005280 unixLeaveMutex();
5281 }
danielk1977e339d652008-06-28 11:23:00 +00005282
drhd2cb50b2009-01-09 21:41:17 +00005283#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005284 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005285 /* AFP locking uses the file path so it needs to be included in
5286 ** the afpLockingContext.
5287 */
5288 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005289 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005290 if( pCtx==0 ){
5291 rc = SQLITE_NOMEM;
5292 }else{
5293 /* NB: zFilename exists and remains valid until the file is closed
5294 ** according to requirement F11141. So we do not need to make a
5295 ** copy of the filename. */
5296 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005297 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005298 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005299 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005300 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005301 if( rc!=SQLITE_OK ){
5302 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005303 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005304 h = -1;
5305 }
drh7708e972008-11-29 00:56:52 +00005306 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005307 }
drh7708e972008-11-29 00:56:52 +00005308 }
5309#endif
danielk1977e339d652008-06-28 11:23:00 +00005310
drh7708e972008-11-29 00:56:52 +00005311 else if( pLockingStyle == &dotlockIoMethods ){
5312 /* Dotfile locking uses the file path so it needs to be included in
5313 ** the dotlockLockingContext
5314 */
5315 char *zLockFile;
5316 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005317 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005318 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005319 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005320 if( zLockFile==0 ){
5321 rc = SQLITE_NOMEM;
5322 }else{
5323 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005324 }
drh7708e972008-11-29 00:56:52 +00005325 pNew->lockingContext = zLockFile;
5326 }
danielk1977e339d652008-06-28 11:23:00 +00005327
drh6c7d5c52008-11-21 20:32:33 +00005328#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005329 else if( pLockingStyle == &semIoMethods ){
5330 /* Named semaphore locking uses the file path so it needs to be
5331 ** included in the semLockingContext
5332 */
5333 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005334 rc = findInodeInfo(pNew, &pNew->pInode);
5335 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5336 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005337 int n;
drh2238dcc2009-08-27 17:56:20 +00005338 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005339 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005340 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005341 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005342 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5343 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005344 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005345 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005346 }
chw97185482008-11-17 08:05:31 +00005347 }
drh7708e972008-11-29 00:56:52 +00005348 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005349 }
drh7708e972008-11-29 00:56:52 +00005350#endif
aswift5b1a2562008-08-22 00:22:35 +00005351
drh4bf66fd2015-02-19 02:43:02 +00005352 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005353#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005354 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005355 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005356 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005357 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005358 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005359 }
chw97185482008-11-17 08:05:31 +00005360#endif
danielk1977e339d652008-06-28 11:23:00 +00005361 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005362 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005363 }else{
drh7708e972008-11-29 00:56:52 +00005364 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005365 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005366 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005367 }
danielk1977e339d652008-06-28 11:23:00 +00005368 return rc;
drh054889e2005-11-30 03:20:31 +00005369}
drh9c06c952005-11-26 00:25:00 +00005370
danielk1977ad94b582007-08-20 06:44:22 +00005371/*
drh8b3cf822010-06-01 21:02:51 +00005372** Return the name of a directory in which to put temporary files.
5373** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005374*/
drh7234c6d2010-06-19 15:10:09 +00005375static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005376 static const char *azDirs[] = {
5377 0,
aswiftaebf4132008-11-21 00:10:35 +00005378 0,
danielk197717b90b52008-06-06 11:11:25 +00005379 "/var/tmp",
5380 "/usr/tmp",
5381 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005382 "."
danielk197717b90b52008-06-06 11:11:25 +00005383 };
drh8b3cf822010-06-01 21:02:51 +00005384 unsigned int i;
5385 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005386 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005387
drhb7e50ad2015-11-28 21:49:53 +00005388 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5389 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005390 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005391 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005392 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005393 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005394 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005395 break;
5396 }
5397 return zDir;
5398}
5399
5400/*
5401** Create a temporary file name in zBuf. zBuf must be allocated
5402** by the calling process and must be big enough to hold at least
5403** pVfs->mxPathname bytes.
5404*/
5405static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005406 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005407 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005408
5409 /* It's odd to simulate an io-error here, but really this is just
5410 ** using the io-error infrastructure to test that SQLite handles this
5411 ** function failing.
5412 */
5413 SimulateIOError( return SQLITE_IOERR );
5414
drh7234c6d2010-06-19 15:10:09 +00005415 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005416 do{
drh970942e2015-11-25 23:13:14 +00005417 u64 r;
5418 sqlite3_randomness(sizeof(r), &r);
5419 assert( nBuf>2 );
5420 zBuf[nBuf-2] = 0;
5421 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5422 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005423 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005424 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005425 return SQLITE_OK;
5426}
5427
drhd2cb50b2009-01-09 21:41:17 +00005428#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005429/*
5430** Routine to transform a unixFile into a proxy-locking unixFile.
5431** Implementation in the proxy-lock division, but used by unixOpen()
5432** if SQLITE_PREFER_PROXY_LOCKING is defined.
5433*/
5434static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005435#endif
drhc66d5b62008-12-03 22:48:32 +00005436
dan08da86a2009-08-21 17:18:03 +00005437/*
5438** Search for an unused file descriptor that was opened on the database
5439** file (not a journal or master-journal file) identified by pathname
5440** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5441** argument to this function.
5442**
5443** Such a file descriptor may exist if a database connection was closed
5444** but the associated file descriptor could not be closed because some
5445** other file descriptor open on the same file is holding a file-lock.
5446** Refer to comments in the unixClose() function and the lengthy comment
5447** describing "Posix Advisory Locking" at the start of this file for
5448** further details. Also, ticket #4018.
5449**
5450** If a suitable file descriptor is found, then it is returned. If no
5451** such file descriptor is located, -1 is returned.
5452*/
dane946c392009-08-22 11:39:46 +00005453static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5454 UnixUnusedFd *pUnused = 0;
5455
5456 /* Do not search for an unused file descriptor on vxworks. Not because
5457 ** vxworks would not benefit from the change (it might, we're not sure),
5458 ** but because no way to test it is currently available. It is better
5459 ** not to risk breaking vxworks support for the sake of such an obscure
5460 ** feature. */
5461#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005462 struct stat sStat; /* Results of stat() call */
5463
5464 /* A stat() call may fail for various reasons. If this happens, it is
5465 ** almost certain that an open() call on the same path will also fail.
5466 ** For this reason, if an error occurs in the stat() call here, it is
5467 ** ignored and -1 is returned. The caller will try to open a new file
5468 ** descriptor on the same path, fail, and return an error to SQLite.
5469 **
5470 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005471 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005472 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005473 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005474
5475 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005476 pInode = inodeList;
5477 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5478 || pInode->fileId.ino!=sStat.st_ino) ){
5479 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005480 }
drh8af6c222010-05-14 12:43:01 +00005481 if( pInode ){
dane946c392009-08-22 11:39:46 +00005482 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005483 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005484 pUnused = *pp;
5485 if( pUnused ){
5486 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005487 }
5488 }
5489 unixLeaveMutex();
5490 }
dane946c392009-08-22 11:39:46 +00005491#endif /* if !OS_VXWORKS */
5492 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005493}
danielk197717b90b52008-06-06 11:11:25 +00005494
5495/*
danddb0ac42010-07-14 14:48:58 +00005496** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005497** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005498** and a value suitable for passing as the third argument to open(2) is
5499** written to *pMode. If an IO error occurs, an SQLite error code is
5500** returned and the value of *pMode is not modified.
5501**
peter.d.reid60ec9142014-09-06 16:39:46 +00005502** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005503** an indication to robust_open() to create the file using
5504** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5505** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005506** this function queries the file-system for the permissions on the
5507** corresponding database file and sets *pMode to this value. Whenever
5508** possible, WAL and journal files are created using the same permissions
5509** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005510**
5511** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5512** original filename is unavailable. But 8_3_NAMES is only used for
5513** FAT filesystems and permissions do not matter there, so just use
5514** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005515*/
5516static int findCreateFileMode(
5517 const char *zPath, /* Path of file (possibly) being created */
5518 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005519 mode_t *pMode, /* OUT: Permissions to open file with */
5520 uid_t *pUid, /* OUT: uid to set on the file */
5521 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005522){
5523 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005524 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005525 *pUid = 0;
5526 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005527 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005528 char zDb[MAX_PATHNAME+1]; /* Database file path */
5529 int nDb; /* Number of valid bytes in zDb */
5530 struct stat sStat; /* Output of stat() on database file */
5531
dana0c989d2010-11-05 18:07:37 +00005532 /* zPath is a path to a WAL or journal file. The following block derives
5533 ** the path to the associated database file from zPath. This block handles
5534 ** the following naming conventions:
5535 **
5536 ** "<path to db>-journal"
5537 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005538 ** "<path to db>-journalNN"
5539 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005540 **
drhd337c5b2011-10-20 18:23:35 +00005541 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005542 ** used by the test_multiplex.c module.
5543 */
5544 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005545 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005546#ifndef SQLITE_ENABLE_8_3_NAMES
5547 /* In the normal case (8+3 filenames disabled) the journal filename
5548 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005549 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005550 assert( sqlite3Isalnum(zPath[nDb]) );
5551#else
5552 /* If 8+3 names are possible, then the journal file might not contain
5553 ** a '-' character. So check for that case and return early. */
5554 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5555#endif
drhc47167a2011-10-05 15:26:13 +00005556 nDb--;
5557 }
danddb0ac42010-07-14 14:48:58 +00005558 memcpy(zDb, zPath, nDb);
5559 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005560
drh58384f12011-07-28 00:14:45 +00005561 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005562 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005563 *pUid = sStat.st_uid;
5564 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005565 }else{
5566 rc = SQLITE_IOERR_FSTAT;
5567 }
5568 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5569 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005570 }
5571 return rc;
5572}
5573
5574/*
danielk1977ad94b582007-08-20 06:44:22 +00005575** Open the file zPath.
5576**
danielk1977b4b47412007-08-17 15:53:36 +00005577** Previously, the SQLite OS layer used three functions in place of this
5578** one:
5579**
5580** sqlite3OsOpenReadWrite();
5581** sqlite3OsOpenReadOnly();
5582** sqlite3OsOpenExclusive();
5583**
5584** These calls correspond to the following combinations of flags:
5585**
5586** ReadWrite() -> (READWRITE | CREATE)
5587** ReadOnly() -> (READONLY)
5588** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5589**
5590** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5591** true, the file was configured to be automatically deleted when the
5592** file handle closed. To achieve the same effect using this new
5593** interface, add the DELETEONCLOSE flag to those specified above for
5594** OpenExclusive().
5595*/
5596static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005597 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5598 const char *zPath, /* Pathname of file to be opened */
5599 sqlite3_file *pFile, /* The file descriptor to be filled in */
5600 int flags, /* Input flags to control the opening */
5601 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005602){
dan08da86a2009-08-21 17:18:03 +00005603 unixFile *p = (unixFile *)pFile;
5604 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005605 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005606 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005607 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005608 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005609 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005610
5611 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5612 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5613 int isCreate = (flags & SQLITE_OPEN_CREATE);
5614 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5615 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005616#if SQLITE_ENABLE_LOCKING_STYLE
5617 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5618#endif
drh3d4435b2011-08-26 20:55:50 +00005619#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5620 struct statfs fsInfo;
5621#endif
danielk1977b4b47412007-08-17 15:53:36 +00005622
danielk1977fee2d252007-08-18 10:59:19 +00005623 /* If creating a master or main-file journal, this function will open
5624 ** a file-descriptor on the directory too. The first time unixSync()
5625 ** is called the directory file descriptor will be fsync()ed and close()d.
5626 */
drh0059eae2011-08-08 23:48:40 +00005627 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005628 eType==SQLITE_OPEN_MASTER_JOURNAL
5629 || eType==SQLITE_OPEN_MAIN_JOURNAL
5630 || eType==SQLITE_OPEN_WAL
5631 ));
danielk1977fee2d252007-08-18 10:59:19 +00005632
danielk197717b90b52008-06-06 11:11:25 +00005633 /* If argument zPath is a NULL pointer, this function is required to open
5634 ** a temporary file. Use this buffer to store the file name in.
5635 */
drhc02a43a2012-01-10 23:18:38 +00005636 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005637 const char *zName = zPath;
5638
danielk1977fee2d252007-08-18 10:59:19 +00005639 /* Check the following statements are true:
5640 **
5641 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5642 ** (b) if CREATE is set, then READWRITE must also be set, and
5643 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005644 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005645 */
danielk1977b4b47412007-08-17 15:53:36 +00005646 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005647 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005648 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005649 assert(isDelete==0 || isCreate);
5650
danddb0ac42010-07-14 14:48:58 +00005651 /* The main DB, main journal, WAL file and master journal are never
5652 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005653 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5654 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5655 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005656 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005657
danielk1977fee2d252007-08-18 10:59:19 +00005658 /* Assert that the upper layer has set one of the "file-type" flags. */
5659 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5660 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5661 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005662 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005663 );
5664
drhb00d8622014-01-01 15:18:36 +00005665 /* Detect a pid change and reset the PRNG. There is a race condition
5666 ** here such that two or more threads all trying to open databases at
5667 ** the same instant might all reset the PRNG. But multiple resets
5668 ** are harmless.
5669 */
drh5ac93652015-03-21 20:59:43 +00005670 if( randomnessPid!=osGetpid(0) ){
5671 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005672 sqlite3_randomness(0,0);
5673 }
5674
dan08da86a2009-08-21 17:18:03 +00005675 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005676
dan08da86a2009-08-21 17:18:03 +00005677 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005678 UnixUnusedFd *pUnused;
5679 pUnused = findReusableFd(zName, flags);
5680 if( pUnused ){
5681 fd = pUnused->fd;
5682 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005683 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005684 if( !pUnused ){
5685 return SQLITE_NOMEM;
5686 }
5687 }
5688 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005689
5690 /* Database filenames are double-zero terminated if they are not
5691 ** URIs with parameters. Hence, they can always be passed into
5692 ** sqlite3_uri_parameter(). */
5693 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5694
dan08da86a2009-08-21 17:18:03 +00005695 }else if( !zName ){
5696 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005697 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005698 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005699 if( rc!=SQLITE_OK ){
5700 return rc;
5701 }
5702 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005703
5704 /* Generated temporary filenames are always double-zero terminated
5705 ** for use by sqlite3_uri_parameter(). */
5706 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005707 }
5708
dan08da86a2009-08-21 17:18:03 +00005709 /* Determine the value of the flags parameter passed to POSIX function
5710 ** open(). These must be calculated even if open() is not called, as
5711 ** they may be stored as part of the file handle and used by the
5712 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005713 if( isReadonly ) openFlags |= O_RDONLY;
5714 if( isReadWrite ) openFlags |= O_RDWR;
5715 if( isCreate ) openFlags |= O_CREAT;
5716 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5717 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005718
danielk1977b4b47412007-08-17 15:53:36 +00005719 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005720 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005721 uid_t uid; /* Userid for the file */
5722 gid_t gid; /* Groupid for the file */
5723 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005724 if( rc!=SQLITE_OK ){
5725 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005726 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005727 return rc;
5728 }
drhad4f1e52011-03-04 15:43:57 +00005729 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005730 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005731 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5732 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005733 /* Failed to open the file for read/write access. Try read-only. */
5734 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005735 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005736 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005737 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005738 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005739 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005740 }
5741 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005742 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005743 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005744 }
drhac7c3ac2012-02-11 19:23:48 +00005745
5746 /* If this process is running as root and if creating a new rollback
5747 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005748 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005749 */
5750 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005751 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005752 }
danielk1977b4b47412007-08-17 15:53:36 +00005753 }
dan08da86a2009-08-21 17:18:03 +00005754 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005755 if( pOutFlags ){
5756 *pOutFlags = flags;
5757 }
5758
dane946c392009-08-22 11:39:46 +00005759 if( p->pUnused ){
5760 p->pUnused->fd = fd;
5761 p->pUnused->flags = flags;
5762 }
5763
danielk1977b4b47412007-08-17 15:53:36 +00005764 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005765#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005766 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005767#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5768 zPath = sqlite3_mprintf("%s", zName);
5769 if( zPath==0 ){
5770 robust_close(p, fd, __LINE__);
5771 return SQLITE_NOMEM;
5772 }
chw97185482008-11-17 08:05:31 +00005773#else
drh036ac7f2011-08-08 23:18:05 +00005774 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005775#endif
danielk1977b4b47412007-08-17 15:53:36 +00005776 }
drh41022642008-11-21 00:24:42 +00005777#if SQLITE_ENABLE_LOCKING_STYLE
5778 else{
dan08da86a2009-08-21 17:18:03 +00005779 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005780 }
5781#endif
5782
drhda0e7682008-07-30 15:27:54 +00005783 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005784
drh7ed97b92010-01-20 13:07:21 +00005785
5786#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005787 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005788 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005789 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005790 return SQLITE_IOERR_ACCESS;
5791 }
5792 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5793 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5794 }
drh4bf66fd2015-02-19 02:43:02 +00005795 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5796 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5797 }
drh7ed97b92010-01-20 13:07:21 +00005798#endif
drhc02a43a2012-01-10 23:18:38 +00005799
5800 /* Set up appropriate ctrlFlags */
5801 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5802 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5803 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5804 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5805 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5806
drh7ed97b92010-01-20 13:07:21 +00005807#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005808#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005809 isAutoProxy = 1;
5810#endif
5811 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005812 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5813 int useProxy = 0;
5814
dan08da86a2009-08-21 17:18:03 +00005815 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5816 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005817 if( envforce!=NULL ){
5818 useProxy = atoi(envforce)>0;
5819 }else{
aswiftaebf4132008-11-21 00:10:35 +00005820 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5821 }
5822 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005823 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005824 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005825 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005826 if( rc!=SQLITE_OK ){
5827 /* Use unixClose to clean up the resources added in fillInUnixFile
5828 ** and clear all the structure's references. Specifically,
5829 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5830 */
5831 unixClose(pFile);
5832 return rc;
5833 }
aswiftaebf4132008-11-21 00:10:35 +00005834 }
dane946c392009-08-22 11:39:46 +00005835 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005836 }
5837 }
5838#endif
5839
drhc02a43a2012-01-10 23:18:38 +00005840 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5841
dane946c392009-08-22 11:39:46 +00005842open_finished:
5843 if( rc!=SQLITE_OK ){
5844 sqlite3_free(p->pUnused);
5845 }
5846 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005847}
5848
dane946c392009-08-22 11:39:46 +00005849
danielk1977b4b47412007-08-17 15:53:36 +00005850/*
danielk1977fee2d252007-08-18 10:59:19 +00005851** Delete the file at zPath. If the dirSync argument is true, fsync()
5852** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005853*/
drh6b9d6dd2008-12-03 19:34:47 +00005854static int unixDelete(
5855 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5856 const char *zPath, /* Name of file to be deleted */
5857 int dirSync /* If true, fsync() directory after deleting file */
5858){
danielk1977fee2d252007-08-18 10:59:19 +00005859 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005860 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005861 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005862 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005863 if( errno==ENOENT
5864#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005865 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005866#endif
5867 ){
dan9fc5b4a2012-11-09 20:17:26 +00005868 rc = SQLITE_IOERR_DELETE_NOENT;
5869 }else{
drhb4308162012-11-09 21:40:02 +00005870 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005871 }
drhb4308162012-11-09 21:40:02 +00005872 return rc;
drh5d4feff2010-07-14 01:45:22 +00005873 }
danielk1977d39fa702008-10-16 13:27:40 +00005874#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005875 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005876 int fd;
drh90315a22011-08-10 01:52:12 +00005877 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005878 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005879#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005880 if( fsync(fd)==-1 )
5881#else
5882 if( fsync(fd) )
5883#endif
5884 {
dane18d4952011-02-21 11:46:24 +00005885 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005886 }
drh0e9365c2011-03-02 02:08:13 +00005887 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005888 }else{
5889 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005890 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005891 }
5892 }
danielk1977d138dd82008-10-15 16:02:48 +00005893#endif
danielk1977fee2d252007-08-18 10:59:19 +00005894 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005895}
5896
danielk197790949c22007-08-17 16:50:38 +00005897/*
mistachkin48864df2013-03-21 21:20:32 +00005898** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005899** test performed depends on the value of flags:
5900**
5901** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5902** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5903** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5904**
5905** Otherwise return 0.
5906*/
danielk1977861f7452008-06-05 11:39:11 +00005907static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005908 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5909 const char *zPath, /* Path of the file to examine */
5910 int flags, /* What do we want to learn about the zPath file? */
5911 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005912){
danielk1977397d65f2008-11-19 11:35:39 +00005913 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005914 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005915 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005916
drhd260b5b2015-11-25 18:03:33 +00005917 /* The spec says there are three possible values for flags. But only
5918 ** two of them are actually used */
5919 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5920
5921 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005922 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005923 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5924 }else{
5925 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005926 }
danielk1977861f7452008-06-05 11:39:11 +00005927 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005928}
5929
danielk1977b4b47412007-08-17 15:53:36 +00005930
5931/*
5932** Turn a relative pathname into a full pathname. The relative path
5933** is stored as a nul-terminated string in the buffer pointed to by
5934** zPath.
5935**
5936** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5937** (in this case, MAX_PATHNAME bytes). The full-path is written to
5938** this buffer before returning.
5939*/
danielk1977adfb9b02007-09-17 07:02:56 +00005940static int unixFullPathname(
5941 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5942 const char *zPath, /* Possibly relative input path */
5943 int nOut, /* Size of output buffer in bytes */
5944 char *zOut /* Output buffer */
5945){
dan245fdc62015-10-31 17:58:33 +00005946 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005947
5948 /* It's odd to simulate an io-error here, but really this is just
5949 ** using the io-error infrastructure to test that SQLite handles this
5950 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005951 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005952 */
5953 SimulateIOError( return SQLITE_ERROR );
5954
drh153c62c2007-08-24 03:51:33 +00005955 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005956 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005957
drhe2258a22016-01-12 00:37:55 +00005958#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +00005959 /* Attempt to resolve the path as if it were a symbolic link. If it is
5960 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5961 ** the identified file is not a symbolic link or does not exist, then
5962 ** zPath is copied directly into zOut. Either way, nByte is left set to
5963 ** the size of the string copied into zOut[] in bytes. */
5964 nByte = osReadlink(zPath, zOut, nOut-1);
5965 if( nByte<0 ){
5966 if( errno!=EINVAL && errno!=ENOENT ){
5967 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5968 }
drhd260b5b2015-11-25 18:03:33 +00005969 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005970 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005971 }else{
dan245fdc62015-10-31 17:58:33 +00005972 zOut[nByte] = '\0';
5973 }
drhe2258a22016-01-12 00:37:55 +00005974#endif
dan245fdc62015-10-31 17:58:33 +00005975
5976 /* If buffer zOut[] now contains an absolute path there is nothing more
5977 ** to do. If it contains a relative path, do the following:
5978 **
5979 ** * move the relative path string so that it is at the end of th
5980 ** zOut[] buffer.
5981 ** * Call getcwd() to read the path of the current working directory
5982 ** into the start of the zOut[] buffer.
5983 ** * Append a '/' character to the cwd string and move the
5984 ** relative path back within the buffer so that it immediately
5985 ** follows the '/'.
5986 **
5987 ** This code is written so that if the combination of the CWD and relative
5988 ** path are larger than the allocated size of zOut[] the CWD is silently
5989 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5990 ** file for which this function returns a full path larger than (nOut-8)
5991 ** bytes in size. */
drh025d2f72015-11-30 22:22:23 +00005992 testcase( nByte==nOut-5 );
5993 testcase( nByte==nOut-4 );
5994 if( zOut[0]!='/' && nByte<nOut-4 ){
danielk1977b4b47412007-08-17 15:53:36 +00005995 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005996 int nRem = nOut-nByte-1;
5997 memmove(&zOut[nRem], zOut, nByte+1);
5998 zOut[nRem-1] = '\0';
5999 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006000 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006001 }
dan245fdc62015-10-31 17:58:33 +00006002 nCwd = sqlite3Strlen30(zOut);
6003 assert( nCwd<=nRem-1 );
6004 zOut[nCwd] = '/';
6005 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00006006 }
dan245fdc62015-10-31 17:58:33 +00006007
danielk1977b4b47412007-08-17 15:53:36 +00006008 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006009}
6010
drh0ccebe72005-06-07 22:22:50 +00006011
drh761df872006-12-21 01:29:22 +00006012#ifndef SQLITE_OMIT_LOAD_EXTENSION
6013/*
6014** Interfaces for opening a shared library, finding entry points
6015** within the shared library, and closing the shared library.
6016*/
6017#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006018static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6019 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006020 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6021}
danielk197795c8a542007-09-01 06:51:27 +00006022
6023/*
6024** SQLite calls this function immediately after a call to unixDlSym() or
6025** unixDlOpen() fails (returns a null pointer). If a more detailed error
6026** message is available, it is written to zBufOut. If no error message
6027** is available, zBufOut is left unmodified and SQLite uses a default
6028** error message.
6029*/
danielk1977397d65f2008-11-19 11:35:39 +00006030static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006031 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006032 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006033 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006034 zErr = dlerror();
6035 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006036 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006037 }
drh6c7d5c52008-11-21 20:32:33 +00006038 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006039}
drh1875f7a2008-12-08 18:19:17 +00006040static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6041 /*
6042 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6043 ** cast into a pointer to a function. And yet the library dlsym() routine
6044 ** returns a void* which is really a pointer to a function. So how do we
6045 ** use dlsym() with -pedantic-errors?
6046 **
6047 ** Variable x below is defined to be a pointer to a function taking
6048 ** parameters void* and const char* and returning a pointer to a function.
6049 ** We initialize x by assigning it a pointer to the dlsym() function.
6050 ** (That assignment requires a cast.) Then we call the function that
6051 ** x points to.
6052 **
6053 ** This work-around is unlikely to work correctly on any system where
6054 ** you really cannot cast a function pointer into void*. But then, on the
6055 ** other hand, dlsym() will not work on such a system either, so we have
6056 ** not really lost anything.
6057 */
6058 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006059 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006060 x = (void(*(*)(void*,const char*))(void))dlsym;
6061 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006062}
danielk1977397d65f2008-11-19 11:35:39 +00006063static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6064 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006065 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006066}
danielk1977b4b47412007-08-17 15:53:36 +00006067#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6068 #define unixDlOpen 0
6069 #define unixDlError 0
6070 #define unixDlSym 0
6071 #define unixDlClose 0
6072#endif
6073
6074/*
danielk197790949c22007-08-17 16:50:38 +00006075** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006076*/
danielk1977397d65f2008-11-19 11:35:39 +00006077static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6078 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006079 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006080
drhbbd42a62004-05-22 17:41:58 +00006081 /* We have to initialize zBuf to prevent valgrind from reporting
6082 ** errors. The reports issued by valgrind are incorrect - we would
6083 ** prefer that the randomness be increased by making use of the
6084 ** uninitialized space in zBuf - but valgrind errors tend to worry
6085 ** some users. Rather than argue, it seems easier just to initialize
6086 ** the whole array and silence valgrind, even if that means less randomness
6087 ** in the random seed.
6088 **
6089 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006090 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006091 ** tests repeatable.
6092 */
danielk1977b4b47412007-08-17 15:53:36 +00006093 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006094 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006095#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006096 {
drhb00d8622014-01-01 15:18:36 +00006097 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006098 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006099 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006100 time_t t;
6101 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006102 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006103 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6104 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6105 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006106 }else{
drhc18b4042012-02-10 03:10:27 +00006107 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006108 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006109 }
drhbbd42a62004-05-22 17:41:58 +00006110 }
6111#endif
drh72cbd072008-10-14 17:58:38 +00006112 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006113}
6114
danielk1977b4b47412007-08-17 15:53:36 +00006115
drhbbd42a62004-05-22 17:41:58 +00006116/*
6117** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006118** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006119** The return value is the number of microseconds of sleep actually
6120** requested from the underlying operating system, a number which
6121** might be greater than or equal to the argument, but not less
6122** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006123*/
danielk1977397d65f2008-11-19 11:35:39 +00006124static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006125#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006126 struct timespec sp;
6127
6128 sp.tv_sec = microseconds / 1000000;
6129 sp.tv_nsec = (microseconds % 1000000) * 1000;
6130 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006131 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006132 return microseconds;
6133#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006134 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006135 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006136 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006137#else
danielk1977b4b47412007-08-17 15:53:36 +00006138 int seconds = (microseconds+999999)/1000000;
6139 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006140 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006141 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006142#endif
drh88f474a2006-01-02 20:00:12 +00006143}
6144
6145/*
drh6b9d6dd2008-12-03 19:34:47 +00006146** The following variable, if set to a non-zero value, is interpreted as
6147** the number of seconds since 1970 and is used to set the result of
6148** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006149*/
6150#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006151int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006152#endif
6153
6154/*
drhb7e8ea22010-05-03 14:32:30 +00006155** Find the current time (in Universal Coordinated Time). Write into *piNow
6156** the current time and date as a Julian Day number times 86_400_000. In
6157** other words, write into *piNow the number of milliseconds since the Julian
6158** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6159** proleptic Gregorian calendar.
6160**
drh31702252011-10-12 23:13:43 +00006161** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6162** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006163*/
6164static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6165 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006166 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006167#if defined(NO_GETTOD)
6168 time_t t;
6169 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006170 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006171#elif OS_VXWORKS
6172 struct timespec sNow;
6173 clock_gettime(CLOCK_REALTIME, &sNow);
6174 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6175#else
6176 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006177 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6178 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006179#endif
6180
6181#ifdef SQLITE_TEST
6182 if( sqlite3_current_time ){
6183 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6184 }
6185#endif
6186 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006187 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006188}
6189
drhc3dfa5e2016-01-22 19:44:03 +00006190#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006191/*
drhbbd42a62004-05-22 17:41:58 +00006192** Find the current time (in Universal Coordinated Time). Write the
6193** current time and date as a Julian Day number into *prNow and
6194** return 0. Return 1 if the time and date cannot be found.
6195*/
danielk1977397d65f2008-11-19 11:35:39 +00006196static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006197 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006198 int rc;
drhff828942010-06-26 21:34:06 +00006199 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006200 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006201 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006202 return rc;
drhbbd42a62004-05-22 17:41:58 +00006203}
drh5337dac2015-11-25 15:15:03 +00006204#else
6205# define unixCurrentTime 0
6206#endif
danielk1977b4b47412007-08-17 15:53:36 +00006207
drhc3dfa5e2016-01-22 19:44:03 +00006208#ifndef SQLITE_OMIT_DEPRECATED
drh6b9d6dd2008-12-03 19:34:47 +00006209/*
6210** We added the xGetLastError() method with the intention of providing
6211** better low-level error messages when operating-system problems come up
6212** during SQLite operation. But so far, none of that has been implemented
6213** in the core. So this routine is never called. For now, it is merely
6214** a place-holder.
6215*/
danielk1977397d65f2008-11-19 11:35:39 +00006216static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6217 UNUSED_PARAMETER(NotUsed);
6218 UNUSED_PARAMETER(NotUsed2);
6219 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006220 return 0;
6221}
drh5337dac2015-11-25 15:15:03 +00006222#else
6223# define unixGetLastError 0
6224#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006225
drhf2424c52010-04-26 00:04:55 +00006226
6227/*
drh734c9862008-11-28 15:37:20 +00006228************************ End of sqlite3_vfs methods ***************************
6229******************************************************************************/
6230
drh715ff302008-12-03 22:32:44 +00006231/******************************************************************************
6232************************** Begin Proxy Locking ********************************
6233**
6234** Proxy locking is a "uber-locking-method" in this sense: It uses the
6235** other locking methods on secondary lock files. Proxy locking is a
6236** meta-layer over top of the primitive locking implemented above. For
6237** this reason, the division that implements of proxy locking is deferred
6238** until late in the file (here) after all of the other I/O methods have
6239** been defined - so that the primitive locking methods are available
6240** as services to help with the implementation of proxy locking.
6241**
6242****
6243**
6244** The default locking schemes in SQLite use byte-range locks on the
6245** database file to coordinate safe, concurrent access by multiple readers
6246** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6247** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6248** as POSIX read & write locks over fixed set of locations (via fsctl),
6249** on AFP and SMB only exclusive byte-range locks are available via fsctl
6250** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6251** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6252** address in the shared range is taken for a SHARED lock, the entire
6253** shared range is taken for an EXCLUSIVE lock):
6254**
drhf2f105d2012-08-20 15:53:54 +00006255** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006256** RESERVED_BYTE 0x40000001
6257** SHARED_RANGE 0x40000002 -> 0x40000200
6258**
6259** This works well on the local file system, but shows a nearly 100x
6260** slowdown in read performance on AFP because the AFP client disables
6261** the read cache when byte-range locks are present. Enabling the read
6262** cache exposes a cache coherency problem that is present on all OS X
6263** supported network file systems. NFS and AFP both observe the
6264** close-to-open semantics for ensuring cache coherency
6265** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6266** address the requirements for concurrent database access by multiple
6267** readers and writers
6268** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6269**
6270** To address the performance and cache coherency issues, proxy file locking
6271** changes the way database access is controlled by limiting access to a
6272** single host at a time and moving file locks off of the database file
6273** and onto a proxy file on the local file system.
6274**
6275**
6276** Using proxy locks
6277** -----------------
6278**
6279** C APIs
6280**
drh4bf66fd2015-02-19 02:43:02 +00006281** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006282** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006283** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6284** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006285**
6286**
6287** SQL pragmas
6288**
6289** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6290** PRAGMA [database.]lock_proxy_file
6291**
6292** Specifying ":auto:" means that if there is a conch file with a matching
6293** host ID in it, the proxy path in the conch file will be used, otherwise
6294** a proxy path based on the user's temp dir
6295** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6296** actual proxy file name is generated from the name and path of the
6297** database file. For example:
6298**
6299** For database path "/Users/me/foo.db"
6300** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6301**
6302** Once a lock proxy is configured for a database connection, it can not
6303** be removed, however it may be switched to a different proxy path via
6304** the above APIs (assuming the conch file is not being held by another
6305** connection or process).
6306**
6307**
6308** How proxy locking works
6309** -----------------------
6310**
6311** Proxy file locking relies primarily on two new supporting files:
6312**
6313** * conch file to limit access to the database file to a single host
6314** at a time
6315**
6316** * proxy file to act as a proxy for the advisory locks normally
6317** taken on the database
6318**
6319** The conch file - to use a proxy file, sqlite must first "hold the conch"
6320** by taking an sqlite-style shared lock on the conch file, reading the
6321** contents and comparing the host's unique host ID (see below) and lock
6322** proxy path against the values stored in the conch. The conch file is
6323** stored in the same directory as the database file and the file name
6324** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006325** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006326** host ID and/or proxy path, then the lock is escalated to an exclusive
6327** lock and the conch file contents is updated with the host ID and proxy
6328** path and the lock is downgraded to a shared lock again. If the conch
6329** is held by another process (with a shared lock), the exclusive lock
6330** will fail and SQLITE_BUSY is returned.
6331**
6332** The proxy file - a single-byte file used for all advisory file locks
6333** normally taken on the database file. This allows for safe sharing
6334** of the database file for multiple readers and writers on the same
6335** host (the conch ensures that they all use the same local lock file).
6336**
drh715ff302008-12-03 22:32:44 +00006337** Requesting the lock proxy does not immediately take the conch, it is
6338** only taken when the first request to lock database file is made.
6339** This matches the semantics of the traditional locking behavior, where
6340** opening a connection to a database file does not take a lock on it.
6341** The shared lock and an open file descriptor are maintained until
6342** the connection to the database is closed.
6343**
6344** The proxy file and the lock file are never deleted so they only need
6345** to be created the first time they are used.
6346**
6347** Configuration options
6348** ---------------------
6349**
6350** SQLITE_PREFER_PROXY_LOCKING
6351**
6352** Database files accessed on non-local file systems are
6353** automatically configured for proxy locking, lock files are
6354** named automatically using the same logic as
6355** PRAGMA lock_proxy_file=":auto:"
6356**
6357** SQLITE_PROXY_DEBUG
6358**
6359** Enables the logging of error messages during host id file
6360** retrieval and creation
6361**
drh715ff302008-12-03 22:32:44 +00006362** LOCKPROXYDIR
6363**
6364** Overrides the default directory used for lock proxy files that
6365** are named automatically via the ":auto:" setting
6366**
6367** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6368**
6369** Permissions to use when creating a directory for storing the
6370** lock proxy files, only used when LOCKPROXYDIR is not set.
6371**
6372**
6373** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6374** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6375** force proxy locking to be used for every database file opened, and 0
6376** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006377** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006378** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6379*/
6380
6381/*
6382** Proxy locking is only available on MacOSX
6383*/
drhd2cb50b2009-01-09 21:41:17 +00006384#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006385
drh715ff302008-12-03 22:32:44 +00006386/*
6387** The proxyLockingContext has the path and file structures for the remote
6388** and local proxy files in it
6389*/
6390typedef struct proxyLockingContext proxyLockingContext;
6391struct proxyLockingContext {
6392 unixFile *conchFile; /* Open conch file */
6393 char *conchFilePath; /* Name of the conch file */
6394 unixFile *lockProxy; /* Open proxy lock file */
6395 char *lockProxyPath; /* Name of the proxy lock file */
6396 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006397 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006398 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006399 void *oldLockingContext; /* Original lockingcontext to restore on close */
6400 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6401};
6402
drh7ed97b92010-01-20 13:07:21 +00006403/*
6404** The proxy lock file path for the database at dbPath is written into lPath,
6405** which must point to valid, writable memory large enough for a maxLen length
6406** file path.
drh715ff302008-12-03 22:32:44 +00006407*/
drh715ff302008-12-03 22:32:44 +00006408static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6409 int len;
6410 int dbLen;
6411 int i;
6412
6413#ifdef LOCKPROXYDIR
6414 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6415#else
6416# ifdef _CS_DARWIN_USER_TEMP_DIR
6417 {
drh7ed97b92010-01-20 13:07:21 +00006418 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006419 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006420 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006421 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006422 }
drh7ed97b92010-01-20 13:07:21 +00006423 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006424 }
6425# else
6426 len = strlcpy(lPath, "/tmp/", maxLen);
6427# endif
6428#endif
6429
6430 if( lPath[len-1]!='/' ){
6431 len = strlcat(lPath, "/", maxLen);
6432 }
6433
6434 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006435 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006436 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006437 char c = dbPath[i];
6438 lPath[i+len] = (c=='/')?'_':c;
6439 }
6440 lPath[i+len]='\0';
6441 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006442 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006443 return SQLITE_OK;
6444}
6445
drh7ed97b92010-01-20 13:07:21 +00006446/*
6447 ** Creates the lock file and any missing directories in lockPath
6448 */
6449static int proxyCreateLockPath(const char *lockPath){
6450 int i, len;
6451 char buf[MAXPATHLEN];
6452 int start = 0;
6453
6454 assert(lockPath!=NULL);
6455 /* try to create all the intermediate directories */
6456 len = (int)strlen(lockPath);
6457 buf[0] = lockPath[0];
6458 for( i=1; i<len; i++ ){
6459 if( lockPath[i] == '/' && (i - start > 0) ){
6460 /* only mkdir if leaf dir != "." or "/" or ".." */
6461 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6462 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6463 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006464 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006465 int err=errno;
6466 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006467 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006468 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006469 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006470 return err;
6471 }
6472 }
6473 }
6474 start=i+1;
6475 }
6476 buf[i] = lockPath[i];
6477 }
drh62aaa6c2015-11-21 17:27:42 +00006478 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006479 return 0;
6480}
6481
drh715ff302008-12-03 22:32:44 +00006482/*
6483** Create a new VFS file descriptor (stored in memory obtained from
6484** sqlite3_malloc) and open the file named "path" in the file descriptor.
6485**
6486** The caller is responsible not only for closing the file descriptor
6487** but also for freeing the memory associated with the file descriptor.
6488*/
drh7ed97b92010-01-20 13:07:21 +00006489static int proxyCreateUnixFile(
6490 const char *path, /* path for the new unixFile */
6491 unixFile **ppFile, /* unixFile created and returned by ref */
6492 int islockfile /* if non zero missing dirs will be created */
6493) {
6494 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006495 unixFile *pNew;
6496 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006497 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006498 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006499 int terrno = 0;
6500 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006501
drh7ed97b92010-01-20 13:07:21 +00006502 /* 1. first try to open/create the file
6503 ** 2. if that fails, and this is a lock file (not-conch), try creating
6504 ** the parent directories and then try again.
6505 ** 3. if that fails, try to open the file read-only
6506 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6507 */
6508 pUnused = findReusableFd(path, openFlags);
6509 if( pUnused ){
6510 fd = pUnused->fd;
6511 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006512 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006513 if( !pUnused ){
6514 return SQLITE_NOMEM;
6515 }
6516 }
6517 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006518 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006519 terrno = errno;
6520 if( fd<0 && errno==ENOENT && islockfile ){
6521 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006522 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006523 }
6524 }
6525 }
6526 if( fd<0 ){
6527 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006528 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006529 terrno = errno;
6530 }
6531 if( fd<0 ){
6532 if( islockfile ){
6533 return SQLITE_BUSY;
6534 }
6535 switch (terrno) {
6536 case EACCES:
6537 return SQLITE_PERM;
6538 case EIO:
6539 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6540 default:
drh9978c972010-02-23 17:36:32 +00006541 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006542 }
6543 }
6544
drhf3cdcdc2015-04-29 16:50:28 +00006545 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006546 if( pNew==NULL ){
6547 rc = SQLITE_NOMEM;
6548 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006549 }
6550 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006551 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006552 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006553 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006554 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006555 pUnused->fd = fd;
6556 pUnused->flags = openFlags;
6557 pNew->pUnused = pUnused;
6558
drhc02a43a2012-01-10 23:18:38 +00006559 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006560 if( rc==SQLITE_OK ){
6561 *ppFile = pNew;
6562 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006563 }
drh7ed97b92010-01-20 13:07:21 +00006564end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006565 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006566 sqlite3_free(pNew);
6567 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006568 return rc;
6569}
6570
drh7ed97b92010-01-20 13:07:21 +00006571#ifdef SQLITE_TEST
6572/* simulate multiple hosts by creating unique hostid file paths */
6573int sqlite3_hostid_num = 0;
6574#endif
6575
6576#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6577
drh6bca6512015-04-13 23:05:28 +00006578#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006579/* Not always defined in the headers as it ought to be */
6580extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006581#endif
drh0ab216a2010-07-02 17:10:40 +00006582
drh7ed97b92010-01-20 13:07:21 +00006583/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6584** bytes of writable memory.
6585*/
6586static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006587 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6588 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006589#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006590 {
drh4bf66fd2015-02-19 02:43:02 +00006591 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006592 if( gethostuuid(pHostID, &timeout) ){
6593 int err = errno;
6594 if( pError ){
6595 *pError = err;
6596 }
6597 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006598 }
drh7ed97b92010-01-20 13:07:21 +00006599 }
drh3d4435b2011-08-26 20:55:50 +00006600#else
6601 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006602#endif
drh7ed97b92010-01-20 13:07:21 +00006603#ifdef SQLITE_TEST
6604 /* simulate multiple hosts by creating unique hostid file paths */
6605 if( sqlite3_hostid_num != 0){
6606 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6607 }
6608#endif
6609
6610 return SQLITE_OK;
6611}
6612
6613/* The conch file contains the header, host id and lock file path
6614 */
6615#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6616#define PROXY_HEADERLEN 1 /* conch file header length */
6617#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6618#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6619
6620/*
6621** Takes an open conch file, copies the contents to a new path and then moves
6622** it back. The newly created file's file descriptor is assigned to the
6623** conch file structure and finally the original conch file descriptor is
6624** closed. Returns zero if successful.
6625*/
6626static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6627 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6628 unixFile *conchFile = pCtx->conchFile;
6629 char tPath[MAXPATHLEN];
6630 char buf[PROXY_MAXCONCHLEN];
6631 char *cPath = pCtx->conchFilePath;
6632 size_t readLen = 0;
6633 size_t pathLen = 0;
6634 char errmsg[64] = "";
6635 int fd = -1;
6636 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006637 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006638
6639 /* create a new path by replace the trailing '-conch' with '-break' */
6640 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6641 if( pathLen>MAXPATHLEN || pathLen<6 ||
6642 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006643 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006644 goto end_breaklock;
6645 }
6646 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006647 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006648 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006649 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006650 goto end_breaklock;
6651 }
6652 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006653 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006654 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006655 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006656 goto end_breaklock;
6657 }
drhe562be52011-03-02 18:01:10 +00006658 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006659 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006660 goto end_breaklock;
6661 }
6662 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006663 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006664 goto end_breaklock;
6665 }
6666 rc = 0;
6667 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006668 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006669 conchFile->h = fd;
6670 conchFile->openFlags = O_RDWR | O_CREAT;
6671
6672end_breaklock:
6673 if( rc ){
6674 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006675 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006676 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006677 }
6678 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6679 }
6680 return rc;
6681}
6682
6683/* Take the requested lock on the conch file and break a stale lock if the
6684** host id matches.
6685*/
6686static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6687 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6688 unixFile *conchFile = pCtx->conchFile;
6689 int rc = SQLITE_OK;
6690 int nTries = 0;
6691 struct timespec conchModTime;
6692
drh3d4435b2011-08-26 20:55:50 +00006693 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006694 do {
6695 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6696 nTries ++;
6697 if( rc==SQLITE_BUSY ){
6698 /* If the lock failed (busy):
6699 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6700 * 2nd try: fail if the mod time changed or host id is different, wait
6701 * 10 sec and try again
6702 * 3rd try: break the lock unless the mod time has changed.
6703 */
6704 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006705 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006706 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006707 return SQLITE_IOERR_LOCK;
6708 }
6709
6710 if( nTries==1 ){
6711 conchModTime = buf.st_mtimespec;
6712 usleep(500000); /* wait 0.5 sec and try the lock again*/
6713 continue;
6714 }
6715
6716 assert( nTries>1 );
6717 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6718 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6719 return SQLITE_BUSY;
6720 }
6721
6722 if( nTries==2 ){
6723 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006724 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006725 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006726 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006727 return SQLITE_IOERR_LOCK;
6728 }
6729 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6730 /* don't break the lock if the host id doesn't match */
6731 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6732 return SQLITE_BUSY;
6733 }
6734 }else{
6735 /* don't break the lock on short read or a version mismatch */
6736 return SQLITE_BUSY;
6737 }
6738 usleep(10000000); /* wait 10 sec and try the lock again */
6739 continue;
6740 }
6741
6742 assert( nTries==3 );
6743 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6744 rc = SQLITE_OK;
6745 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006746 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006747 }
6748 if( !rc ){
6749 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6750 }
6751 }
6752 }
6753 } while( rc==SQLITE_BUSY && nTries<3 );
6754
6755 return rc;
6756}
6757
6758/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006759** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6760** lockPath means that the lockPath in the conch file will be used if the
6761** host IDs match, or a new lock path will be generated automatically
6762** and written to the conch file.
6763*/
6764static int proxyTakeConch(unixFile *pFile){
6765 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6766
drh7ed97b92010-01-20 13:07:21 +00006767 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006768 return SQLITE_OK;
6769 }else{
6770 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006771 uuid_t myHostID;
6772 int pError = 0;
6773 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006774 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006775 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006776 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006777 int createConch = 0;
6778 int hostIdMatch = 0;
6779 int readLen = 0;
6780 int tryOldLockPath = 0;
6781 int forceNewLockPath = 0;
6782
drh308c2a52010-05-14 11:30:18 +00006783 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006784 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006785 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006786
drh7ed97b92010-01-20 13:07:21 +00006787 rc = proxyGetHostID(myHostID, &pError);
6788 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006789 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006790 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006791 }
drh7ed97b92010-01-20 13:07:21 +00006792 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006793 if( rc!=SQLITE_OK ){
6794 goto end_takeconch;
6795 }
drh7ed97b92010-01-20 13:07:21 +00006796 /* read the existing conch file */
6797 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6798 if( readLen<0 ){
6799 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006800 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006801 rc = SQLITE_IOERR_READ;
6802 goto end_takeconch;
6803 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6804 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6805 /* a short read or version format mismatch means we need to create a new
6806 ** conch file.
6807 */
6808 createConch = 1;
6809 }
6810 /* if the host id matches and the lock path already exists in the conch
6811 ** we'll try to use the path there, if we can't open that path, we'll
6812 ** retry with a new auto-generated path
6813 */
6814 do { /* in case we need to try again for an :auto: named lock file */
6815
6816 if( !createConch && !forceNewLockPath ){
6817 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6818 PROXY_HOSTIDLEN);
6819 /* if the conch has data compare the contents */
6820 if( !pCtx->lockProxyPath ){
6821 /* for auto-named local lock file, just check the host ID and we'll
6822 ** use the local lock file path that's already in there
6823 */
6824 if( hostIdMatch ){
6825 size_t pathLen = (readLen - PROXY_PATHINDEX);
6826
6827 if( pathLen>=MAXPATHLEN ){
6828 pathLen=MAXPATHLEN-1;
6829 }
6830 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6831 lockPath[pathLen] = 0;
6832 tempLockPath = lockPath;
6833 tryOldLockPath = 1;
6834 /* create a copy of the lock path if the conch is taken */
6835 goto end_takeconch;
6836 }
6837 }else if( hostIdMatch
6838 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6839 readLen-PROXY_PATHINDEX)
6840 ){
6841 /* conch host and lock path match */
6842 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006843 }
drh7ed97b92010-01-20 13:07:21 +00006844 }
6845
6846 /* if the conch isn't writable and doesn't match, we can't take it */
6847 if( (conchFile->openFlags&O_RDWR) == 0 ){
6848 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006849 goto end_takeconch;
6850 }
drh7ed97b92010-01-20 13:07:21 +00006851
6852 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006853 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006854 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6855 tempLockPath = lockPath;
6856 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006857 }
drh7ed97b92010-01-20 13:07:21 +00006858
6859 /* update conch with host and path (this will fail if other process
6860 ** has a shared lock already), if the host id matches, use the big
6861 ** stick.
drh715ff302008-12-03 22:32:44 +00006862 */
drh7ed97b92010-01-20 13:07:21 +00006863 futimes(conchFile->h, NULL);
6864 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006865 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006866 /* We are trying for an exclusive lock but another thread in this
6867 ** same process is still holding a shared lock. */
6868 rc = SQLITE_BUSY;
6869 } else {
6870 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006871 }
drh715ff302008-12-03 22:32:44 +00006872 }else{
drh4bf66fd2015-02-19 02:43:02 +00006873 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006874 }
drh7ed97b92010-01-20 13:07:21 +00006875 if( rc==SQLITE_OK ){
6876 char writeBuffer[PROXY_MAXCONCHLEN];
6877 int writeSize = 0;
6878
6879 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6880 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6881 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006882 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6883 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006884 }else{
6885 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6886 }
6887 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006888 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006889 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6890 fsync(conchFile->h);
6891 /* If we created a new conch file (not just updated the contents of a
6892 ** valid conch file), try to match the permissions of the database
6893 */
6894 if( rc==SQLITE_OK && createConch ){
6895 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006896 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006897 if( err==0 ){
6898 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6899 S_IROTH|S_IWOTH);
6900 /* try to match the database file R/W permissions, ignore failure */
6901#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006902 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006903#else
drhff812312011-02-23 13:33:46 +00006904 do{
drhe562be52011-03-02 18:01:10 +00006905 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006906 }while( rc==(-1) && errno==EINTR );
6907 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006908 int code = errno;
6909 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6910 cmode, code, strerror(code));
6911 } else {
6912 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6913 }
6914 }else{
6915 int code = errno;
6916 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6917 err, code, strerror(code));
6918#endif
6919 }
drh715ff302008-12-03 22:32:44 +00006920 }
6921 }
drh7ed97b92010-01-20 13:07:21 +00006922 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6923
6924 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006925 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006926 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006927 int fd;
drh7ed97b92010-01-20 13:07:21 +00006928 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006929 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006930 }
6931 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006932 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006933 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006934 if( fd>=0 ){
6935 pFile->h = fd;
6936 }else{
drh9978c972010-02-23 17:36:32 +00006937 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006938 during locking */
6939 }
6940 }
6941 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6942 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6943 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6944 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6945 /* we couldn't create the proxy lock file with the old lock file path
6946 ** so try again via auto-naming
6947 */
6948 forceNewLockPath = 1;
6949 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006950 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006951 }
6952 }
6953 if( rc==SQLITE_OK ){
6954 /* Need to make a copy of path if we extracted the value
6955 ** from the conch file or the path was allocated on the stack
6956 */
6957 if( tempLockPath ){
6958 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6959 if( !pCtx->lockProxyPath ){
6960 rc = SQLITE_NOMEM;
6961 }
6962 }
6963 }
6964 if( rc==SQLITE_OK ){
6965 pCtx->conchHeld = 1;
6966
6967 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6968 afpLockingContext *afpCtx;
6969 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6970 afpCtx->dbPath = pCtx->lockProxyPath;
6971 }
6972 } else {
6973 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6974 }
drh308c2a52010-05-14 11:30:18 +00006975 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6976 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006977 return rc;
drh308c2a52010-05-14 11:30:18 +00006978 } while (1); /* in case we need to retry the :auto: lock file -
6979 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006980 }
6981}
6982
6983/*
6984** If pFile holds a lock on a conch file, then release that lock.
6985*/
6986static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006987 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006988 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6989 unixFile *conchFile; /* Name of the conch file */
6990
6991 pCtx = (proxyLockingContext *)pFile->lockingContext;
6992 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006993 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006994 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006995 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006996 if( pCtx->conchHeld>0 ){
6997 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6998 }
drh715ff302008-12-03 22:32:44 +00006999 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007000 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7001 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007002 return rc;
7003}
7004
7005/*
7006** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007007** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007008** Make *pConchPath point to the new name. Return SQLITE_OK on success
7009** or SQLITE_NOMEM if unable to obtain memory.
7010**
7011** The caller is responsible for ensuring that the allocated memory
7012** space is eventually freed.
7013**
7014** *pConchPath is set to NULL if a memory allocation error occurs.
7015*/
7016static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7017 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007018 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007019 char *conchPath; /* buffer in which to construct conch name */
7020
7021 /* Allocate space for the conch filename and initialize the name to
7022 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007023 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007024 if( conchPath==0 ){
7025 return SQLITE_NOMEM;
7026 }
7027 memcpy(conchPath, dbPath, len+1);
7028
7029 /* now insert a "." before the last / character */
7030 for( i=(len-1); i>=0; i-- ){
7031 if( conchPath[i]=='/' ){
7032 i++;
7033 break;
7034 }
7035 }
7036 conchPath[i]='.';
7037 while ( i<len ){
7038 conchPath[i+1]=dbPath[i];
7039 i++;
7040 }
7041
7042 /* append the "-conch" suffix to the file */
7043 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007044 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007045
7046 return SQLITE_OK;
7047}
7048
7049
7050/* Takes a fully configured proxy locking-style unix file and switches
7051** the local lock file path
7052*/
7053static int switchLockProxyPath(unixFile *pFile, const char *path) {
7054 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7055 char *oldPath = pCtx->lockProxyPath;
7056 int rc = SQLITE_OK;
7057
drh308c2a52010-05-14 11:30:18 +00007058 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007059 return SQLITE_BUSY;
7060 }
7061
7062 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7063 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7064 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7065 return SQLITE_OK;
7066 }else{
7067 unixFile *lockProxy = pCtx->lockProxy;
7068 pCtx->lockProxy=NULL;
7069 pCtx->conchHeld = 0;
7070 if( lockProxy!=NULL ){
7071 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7072 if( rc ) return rc;
7073 sqlite3_free(lockProxy);
7074 }
7075 sqlite3_free(oldPath);
7076 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7077 }
7078
7079 return rc;
7080}
7081
7082/*
7083** pFile is a file that has been opened by a prior xOpen call. dbPath
7084** is a string buffer at least MAXPATHLEN+1 characters in size.
7085**
7086** This routine find the filename associated with pFile and writes it
7087** int dbPath.
7088*/
7089static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007090#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007091 if( pFile->pMethod == &afpIoMethods ){
7092 /* afp style keeps a reference to the db path in the filePath field
7093 ** of the struct */
drhea678832008-12-10 19:26:22 +00007094 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007095 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7096 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007097 } else
drh715ff302008-12-03 22:32:44 +00007098#endif
7099 if( pFile->pMethod == &dotlockIoMethods ){
7100 /* dot lock style uses the locking context to store the dot lock
7101 ** file path */
7102 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7103 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7104 }else{
7105 /* all other styles use the locking context to store the db file path */
7106 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007107 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007108 }
7109 return SQLITE_OK;
7110}
7111
7112/*
7113** Takes an already filled in unix file and alters it so all file locking
7114** will be performed on the local proxy lock file. The following fields
7115** are preserved in the locking context so that they can be restored and
7116** the unix structure properly cleaned up at close time:
7117** ->lockingContext
7118** ->pMethod
7119*/
7120static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7121 proxyLockingContext *pCtx;
7122 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7123 char *lockPath=NULL;
7124 int rc = SQLITE_OK;
7125
drh308c2a52010-05-14 11:30:18 +00007126 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007127 return SQLITE_BUSY;
7128 }
7129 proxyGetDbPathForUnixFile(pFile, dbPath);
7130 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7131 lockPath=NULL;
7132 }else{
7133 lockPath=(char *)path;
7134 }
7135
drh308c2a52010-05-14 11:30:18 +00007136 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007137 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007138
drhf3cdcdc2015-04-29 16:50:28 +00007139 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007140 if( pCtx==0 ){
7141 return SQLITE_NOMEM;
7142 }
7143 memset(pCtx, 0, sizeof(*pCtx));
7144
7145 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7146 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007147 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7148 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7149 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7150 ** (c) the file system is read-only, then enable no-locking access.
7151 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7152 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7153 */
7154 struct statfs fsInfo;
7155 struct stat conchInfo;
7156 int goLockless = 0;
7157
drh99ab3b12011-03-02 15:09:07 +00007158 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007159 int err = errno;
7160 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7161 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7162 }
7163 }
7164 if( goLockless ){
7165 pCtx->conchHeld = -1; /* read only FS/ lockless */
7166 rc = SQLITE_OK;
7167 }
7168 }
drh715ff302008-12-03 22:32:44 +00007169 }
7170 if( rc==SQLITE_OK && lockPath ){
7171 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7172 }
7173
7174 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007175 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7176 if( pCtx->dbPath==NULL ){
7177 rc = SQLITE_NOMEM;
7178 }
7179 }
7180 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007181 /* all memory is allocated, proxys are created and assigned,
7182 ** switch the locking context and pMethod then return.
7183 */
drh715ff302008-12-03 22:32:44 +00007184 pCtx->oldLockingContext = pFile->lockingContext;
7185 pFile->lockingContext = pCtx;
7186 pCtx->pOldMethod = pFile->pMethod;
7187 pFile->pMethod = &proxyIoMethods;
7188 }else{
7189 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007190 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007191 sqlite3_free(pCtx->conchFile);
7192 }
drhd56b1212010-08-11 06:14:15 +00007193 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007194 sqlite3_free(pCtx->conchFilePath);
7195 sqlite3_free(pCtx);
7196 }
drh308c2a52010-05-14 11:30:18 +00007197 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7198 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007199 return rc;
7200}
7201
7202
7203/*
7204** This routine handles sqlite3_file_control() calls that are specific
7205** to proxy locking.
7206*/
7207static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7208 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007209 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007210 unixFile *pFile = (unixFile*)id;
7211 if( pFile->pMethod == &proxyIoMethods ){
7212 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7213 proxyTakeConch(pFile);
7214 if( pCtx->lockProxyPath ){
7215 *(const char **)pArg = pCtx->lockProxyPath;
7216 }else{
7217 *(const char **)pArg = ":auto: (not held)";
7218 }
7219 } else {
7220 *(const char **)pArg = NULL;
7221 }
7222 return SQLITE_OK;
7223 }
drh4bf66fd2015-02-19 02:43:02 +00007224 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007225 unixFile *pFile = (unixFile*)id;
7226 int rc = SQLITE_OK;
7227 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7228 if( pArg==NULL || (const char *)pArg==0 ){
7229 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007230 /* turn off proxy locking - not supported. If support is added for
7231 ** switching proxy locking mode off then it will need to fail if
7232 ** the journal mode is WAL mode.
7233 */
drh715ff302008-12-03 22:32:44 +00007234 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7235 }else{
7236 /* turn off proxy locking - already off - NOOP */
7237 rc = SQLITE_OK;
7238 }
7239 }else{
7240 const char *proxyPath = (const char *)pArg;
7241 if( isProxyStyle ){
7242 proxyLockingContext *pCtx =
7243 (proxyLockingContext*)pFile->lockingContext;
7244 if( !strcmp(pArg, ":auto:")
7245 || (pCtx->lockProxyPath &&
7246 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7247 ){
7248 rc = SQLITE_OK;
7249 }else{
7250 rc = switchLockProxyPath(pFile, proxyPath);
7251 }
7252 }else{
7253 /* turn on proxy file locking */
7254 rc = proxyTransformUnixFile(pFile, proxyPath);
7255 }
7256 }
7257 return rc;
7258 }
7259 default: {
7260 assert( 0 ); /* The call assures that only valid opcodes are sent */
7261 }
7262 }
7263 /*NOTREACHED*/
7264 return SQLITE_ERROR;
7265}
7266
7267/*
7268** Within this division (the proxying locking implementation) the procedures
7269** above this point are all utilities. The lock-related methods of the
7270** proxy-locking sqlite3_io_method object follow.
7271*/
7272
7273
7274/*
7275** This routine checks if there is a RESERVED lock held on the specified
7276** file by this or any other process. If such a lock is held, set *pResOut
7277** to a non-zero value otherwise *pResOut is set to zero. The return value
7278** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7279*/
7280static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7281 unixFile *pFile = (unixFile*)id;
7282 int rc = proxyTakeConch(pFile);
7283 if( rc==SQLITE_OK ){
7284 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007285 if( pCtx->conchHeld>0 ){
7286 unixFile *proxy = pCtx->lockProxy;
7287 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7288 }else{ /* conchHeld < 0 is lockless */
7289 pResOut=0;
7290 }
drh715ff302008-12-03 22:32:44 +00007291 }
7292 return rc;
7293}
7294
7295/*
drh308c2a52010-05-14 11:30:18 +00007296** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007297** of the following:
7298**
7299** (1) SHARED_LOCK
7300** (2) RESERVED_LOCK
7301** (3) PENDING_LOCK
7302** (4) EXCLUSIVE_LOCK
7303**
7304** Sometimes when requesting one lock state, additional lock states
7305** are inserted in between. The locking might fail on one of the later
7306** transitions leaving the lock state different from what it started but
7307** still short of its goal. The following chart shows the allowed
7308** transitions and the inserted intermediate states:
7309**
7310** UNLOCKED -> SHARED
7311** SHARED -> RESERVED
7312** SHARED -> (PENDING) -> EXCLUSIVE
7313** RESERVED -> (PENDING) -> EXCLUSIVE
7314** PENDING -> EXCLUSIVE
7315**
7316** This routine will only increase a lock. Use the sqlite3OsUnlock()
7317** routine to lower a locking level.
7318*/
drh308c2a52010-05-14 11:30:18 +00007319static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007320 unixFile *pFile = (unixFile*)id;
7321 int rc = proxyTakeConch(pFile);
7322 if( rc==SQLITE_OK ){
7323 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007324 if( pCtx->conchHeld>0 ){
7325 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007326 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7327 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007328 }else{
7329 /* conchHeld < 0 is lockless */
7330 }
drh715ff302008-12-03 22:32:44 +00007331 }
7332 return rc;
7333}
7334
7335
7336/*
drh308c2a52010-05-14 11:30:18 +00007337** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007338** must be either NO_LOCK or SHARED_LOCK.
7339**
7340** If the locking level of the file descriptor is already at or below
7341** the requested locking level, this routine is a no-op.
7342*/
drh308c2a52010-05-14 11:30:18 +00007343static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007344 unixFile *pFile = (unixFile*)id;
7345 int rc = proxyTakeConch(pFile);
7346 if( rc==SQLITE_OK ){
7347 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007348 if( pCtx->conchHeld>0 ){
7349 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007350 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7351 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007352 }else{
7353 /* conchHeld < 0 is lockless */
7354 }
drh715ff302008-12-03 22:32:44 +00007355 }
7356 return rc;
7357}
7358
7359/*
7360** Close a file that uses proxy locks.
7361*/
7362static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007363 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007364 unixFile *pFile = (unixFile*)id;
7365 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7366 unixFile *lockProxy = pCtx->lockProxy;
7367 unixFile *conchFile = pCtx->conchFile;
7368 int rc = SQLITE_OK;
7369
7370 if( lockProxy ){
7371 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7372 if( rc ) return rc;
7373 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7374 if( rc ) return rc;
7375 sqlite3_free(lockProxy);
7376 pCtx->lockProxy = 0;
7377 }
7378 if( conchFile ){
7379 if( pCtx->conchHeld ){
7380 rc = proxyReleaseConch(pFile);
7381 if( rc ) return rc;
7382 }
7383 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7384 if( rc ) return rc;
7385 sqlite3_free(conchFile);
7386 }
drhd56b1212010-08-11 06:14:15 +00007387 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007388 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007389 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007390 /* restore the original locking context and pMethod then close it */
7391 pFile->lockingContext = pCtx->oldLockingContext;
7392 pFile->pMethod = pCtx->pOldMethod;
7393 sqlite3_free(pCtx);
7394 return pFile->pMethod->xClose(id);
7395 }
7396 return SQLITE_OK;
7397}
7398
7399
7400
drhd2cb50b2009-01-09 21:41:17 +00007401#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007402/*
7403** The proxy locking style is intended for use with AFP filesystems.
7404** And since AFP is only supported on MacOSX, the proxy locking is also
7405** restricted to MacOSX.
7406**
7407**
7408******************* End of the proxy lock implementation **********************
7409******************************************************************************/
7410
drh734c9862008-11-28 15:37:20 +00007411/*
danielk1977e339d652008-06-28 11:23:00 +00007412** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007413**
7414** This routine registers all VFS implementations for unix-like operating
7415** systems. This routine, and the sqlite3_os_end() routine that follows,
7416** should be the only routines in this file that are visible from other
7417** files.
drh6b9d6dd2008-12-03 19:34:47 +00007418**
7419** This routine is called once during SQLite initialization and by a
7420** single thread. The memory allocation and mutex subsystems have not
7421** necessarily been initialized when this routine is called, and so they
7422** should not be used.
drh153c62c2007-08-24 03:51:33 +00007423*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007424int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007425 /*
7426 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007427 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7428 ** to the "finder" function. (pAppData is a pointer to a pointer because
7429 ** silly C90 rules prohibit a void* from being cast to a function pointer
7430 ** and so we have to go through the intermediate pointer to avoid problems
7431 ** when compiling with -pedantic-errors on GCC.)
7432 **
7433 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007434 ** finder-function. The finder-function returns a pointer to the
7435 ** sqlite_io_methods object that implements the desired locking
7436 ** behaviors. See the division above that contains the IOMETHODS
7437 ** macro for addition information on finder-functions.
7438 **
7439 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7440 ** object. But the "autolockIoFinder" available on MacOSX does a little
7441 ** more than that; it looks at the filesystem type that hosts the
7442 ** database file and tries to choose an locking method appropriate for
7443 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007444 */
drh7708e972008-11-29 00:56:52 +00007445 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007446 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007447 sizeof(unixFile), /* szOsFile */ \
7448 MAX_PATHNAME, /* mxPathname */ \
7449 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007450 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007451 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007452 unixOpen, /* xOpen */ \
7453 unixDelete, /* xDelete */ \
7454 unixAccess, /* xAccess */ \
7455 unixFullPathname, /* xFullPathname */ \
7456 unixDlOpen, /* xDlOpen */ \
7457 unixDlError, /* xDlError */ \
7458 unixDlSym, /* xDlSym */ \
7459 unixDlClose, /* xDlClose */ \
7460 unixRandomness, /* xRandomness */ \
7461 unixSleep, /* xSleep */ \
7462 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007463 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007464 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007465 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007466 unixGetSystemCall, /* xGetSystemCall */ \
7467 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007468 }
7469
drh6b9d6dd2008-12-03 19:34:47 +00007470 /*
7471 ** All default VFSes for unix are contained in the following array.
7472 **
7473 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7474 ** by the SQLite core when the VFS is registered. So the following
7475 ** array cannot be const.
7476 */
danielk1977e339d652008-06-28 11:23:00 +00007477 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007478#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007479 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007480#elif OS_VXWORKS
7481 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007482#else
7483 UNIXVFS("unix", posixIoFinder ),
7484#endif
7485 UNIXVFS("unix-none", nolockIoFinder ),
7486 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007487 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007488#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007489 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007490#endif
drhe89b2912015-03-03 20:42:01 +00007491#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007492 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007493#endif
drhe89b2912015-03-03 20:42:01 +00007494#if SQLITE_ENABLE_LOCKING_STYLE
7495 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007496#endif
drhd2cb50b2009-01-09 21:41:17 +00007497#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007498 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007499 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007500 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007501#endif
drh153c62c2007-08-24 03:51:33 +00007502 };
drh6b9d6dd2008-12-03 19:34:47 +00007503 unsigned int i; /* Loop counter */
7504
drh2aa5a002011-04-13 13:42:25 +00007505 /* Double-check that the aSyscall[] array has been constructed
7506 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007507 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007508
drh6b9d6dd2008-12-03 19:34:47 +00007509 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007510 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007511 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007512 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007513 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007514}
danielk1977e339d652008-06-28 11:23:00 +00007515
7516/*
drh6b9d6dd2008-12-03 19:34:47 +00007517** Shutdown the operating system interface.
7518**
7519** Some operating systems might need to do some cleanup in this routine,
7520** to release dynamically allocated objects. But not on unix.
7521** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007522*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007523int sqlite3_os_end(void){
7524 return SQLITE_OK;
7525}
drhdce8bdb2007-08-16 13:01:44 +00007526
danielk197729bafea2008-06-26 10:41:19 +00007527#endif /* SQLITE_OS_UNIX */