blob: 475beed28b070d8ff007d5e10cfe5aa9fd400938 [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 */
drh5a8d1902015-11-24 16:40:23 +0000261#define UNIXFILE_BLOCK 0x0100 /* Next SHM lock might block */
drha7e61d82011-03-12 17:02:57 +0000262
263/*
drh198bf392006-01-06 21:52:49 +0000264** Include code that is common to all os_*.c files
265*/
266#include "os_common.h"
267
268/*
drh0ccebe72005-06-07 22:22:50 +0000269** Define various macros that are missing from some systems.
270*/
drhbbd42a62004-05-22 17:41:58 +0000271#ifndef O_LARGEFILE
272# define O_LARGEFILE 0
273#endif
274#ifdef SQLITE_DISABLE_LFS
275# undef O_LARGEFILE
276# define O_LARGEFILE 0
277#endif
278#ifndef O_NOFOLLOW
279# define O_NOFOLLOW 0
280#endif
281#ifndef O_BINARY
282# define O_BINARY 0
283#endif
284
285/*
drh2b4b5962005-06-15 17:47:55 +0000286** The threadid macro resolves to the thread-id or to 0. Used for
287** testing and debugging only.
288*/
drhd677b3d2007-08-20 22:48:41 +0000289#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000290#define threadid pthread_self()
291#else
292#define threadid 0
293#endif
294
drh99ab3b12011-03-02 15:09:07 +0000295/*
dane6ecd662013-04-01 17:56:59 +0000296** HAVE_MREMAP defaults to true on Linux and false everywhere else.
297*/
298#if !defined(HAVE_MREMAP)
299# if defined(__linux__) && defined(_GNU_SOURCE)
300# define HAVE_MREMAP 1
301# else
302# define HAVE_MREMAP 0
303# endif
304#endif
305
306/*
dan2ee53412014-09-06 16:49:40 +0000307** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
308** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
309*/
310#ifdef __ANDROID__
311# define lseek lseek64
312#endif
313
314/*
drh9a3baf12011-04-25 18:01:27 +0000315** Different Unix systems declare open() in different ways. Same use
316** open(const char*,int,mode_t). Others use open(const char*,int,...).
317** The difference is important when using a pointer to the function.
318**
319** The safest way to deal with the problem is to always use this wrapper
320** which always has the same well-defined interface.
321*/
322static int posixOpen(const char *zFile, int flags, int mode){
323 return open(zFile, flags, mode);
324}
325
drh90315a22011-08-10 01:52:12 +0000326/* Forward reference */
327static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000328static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000329
drh9a3baf12011-04-25 18:01:27 +0000330/*
drh99ab3b12011-03-02 15:09:07 +0000331** Many system calls are accessed through pointer-to-functions so that
332** they may be overridden at runtime to facilitate fault injection during
333** testing and sandboxing. The following array holds the names and pointers
334** to all overrideable system calls.
335*/
336static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000337 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000338 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
339 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000340} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000341 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
342#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000343
drh58ad5802011-03-23 22:02:23 +0000344 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osClose ((int(*)(int))aSyscall[1].pCurrent)
346
drh58ad5802011-03-23 22:02:23 +0000347 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
349
drh58ad5802011-03-23 22:02:23 +0000350 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
352
drh58ad5802011-03-23 22:02:23 +0000353 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000354#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
355
356/*
357** The DJGPP compiler environment looks mostly like Unix, but it
358** lacks the fcntl() system call. So redefine fcntl() to be something
359** that always succeeds. This means that locking does not occur under
360** DJGPP. But it is DOS - what did you expect?
361*/
362#ifdef __DJGPP__
363 { "fstat", 0, 0 },
364#define osFstat(a,b,c) 0
365#else
drh58ad5802011-03-23 22:02:23 +0000366 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000367#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
368#endif
369
drh58ad5802011-03-23 22:02:23 +0000370 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
372
drh58ad5802011-03-23 22:02:23 +0000373 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000374#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000375
drh58ad5802011-03-23 22:02:23 +0000376 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000377#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
378
drhe89b2912015-03-03 20:42:01 +0000379#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000380 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000381#else
drh58ad5802011-03-23 22:02:23 +0000382 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000383#endif
384#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
385
386#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000387 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000388#else
drh58ad5802011-03-23 22:02:23 +0000389 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000390#endif
391#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
392
drh58ad5802011-03-23 22:02:23 +0000393 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000394#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
395
drhe89b2912015-03-03 20:42:01 +0000396#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000400#endif
401#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
402 aSyscall[12].pCurrent)
403
404#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000405 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000406#else
drh58ad5802011-03-23 22:02:23 +0000407 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000408#endif
409#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
410 aSyscall[13].pCurrent)
411
drh6226ca22015-11-24 15:06:28 +0000412 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000413#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000414
415#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000416 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000417#else
drh58ad5802011-03-23 22:02:23 +0000418 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000419#endif
dan0fd7d862011-03-29 10:04:23 +0000420#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000421
drh036ac7f2011-08-08 23:18:05 +0000422 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
423#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
424
drh90315a22011-08-10 01:52:12 +0000425 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
426#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
427
drh9ef6bc42011-11-04 02:24:02 +0000428 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
429#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
430
431 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
432#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
433
drh6226ca22015-11-24 15:06:28 +0000434 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000435#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000436
drh6226ca22015-11-24 15:06:28 +0000437 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
438#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
439
dan4dd51442013-08-26 14:30:25 +0000440#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000441 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000442#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000443
drhd1ab8062013-03-25 20:50:25 +0000444 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drh6226ca22015-11-24 15:06:28 +0000445#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000446
dane6ecd662013-04-01 17:56:59 +0000447#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000448 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
449#else
450 { "mremap", (sqlite3_syscall_ptr)0, 0 },
451#endif
drh6226ca22015-11-24 15:06:28 +0000452#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
453
danbc760632014-03-20 09:42:09 +0000454 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh6226ca22015-11-24 15:06:28 +0000455#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000456
dan245fdc62015-10-31 17:58:33 +0000457 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drh6226ca22015-11-24 15:06:28 +0000458#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000459
dan702eec12014-06-23 10:04:58 +0000460#endif
461
drhe562be52011-03-02 18:01:10 +0000462}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000463
drh6226ca22015-11-24 15:06:28 +0000464
465/*
466** On some systems, calls to fchown() will trigger a message in a security
467** log if they come from non-root processes. So avoid calling fchown() if
468** we are not running as root.
469*/
470static int robustFchown(int fd, uid_t uid, gid_t gid){
471#if OS_VXWORKS
472 return 0;
473#else
474 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
475#endif
476}
477
drh99ab3b12011-03-02 15:09:07 +0000478/*
479** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000480** "unix" VFSes. Return SQLITE_OK opon successfully updating the
481** system call pointer, or SQLITE_NOTFOUND if there is no configurable
482** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000483*/
484static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000485 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
486 const char *zName, /* Name of system call to override */
487 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000488){
drh58ad5802011-03-23 22:02:23 +0000489 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000490 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000491
492 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000493 if( zName==0 ){
494 /* If no zName is given, restore all system calls to their default
495 ** settings and return NULL
496 */
dan51438a72011-04-02 17:00:47 +0000497 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000498 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
499 if( aSyscall[i].pDefault ){
500 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000501 }
502 }
503 }else{
504 /* If zName is specified, operate on only the one system call
505 ** specified.
506 */
507 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
508 if( strcmp(zName, aSyscall[i].zName)==0 ){
509 if( aSyscall[i].pDefault==0 ){
510 aSyscall[i].pDefault = aSyscall[i].pCurrent;
511 }
drh1df30962011-03-02 19:06:42 +0000512 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000513 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
514 aSyscall[i].pCurrent = pNewFunc;
515 break;
516 }
517 }
518 }
519 return rc;
520}
521
drh1df30962011-03-02 19:06:42 +0000522/*
523** Return the value of a system call. Return NULL if zName is not a
524** recognized system call name. NULL is also returned if the system call
525** is currently undefined.
526*/
drh58ad5802011-03-23 22:02:23 +0000527static sqlite3_syscall_ptr unixGetSystemCall(
528 sqlite3_vfs *pNotUsed,
529 const char *zName
530){
531 unsigned int i;
532
533 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000534 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
535 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
536 }
537 return 0;
538}
539
540/*
541** Return the name of the first system call after zName. If zName==NULL
542** then return the name of the first system call. Return NULL if zName
543** is the last system call or if zName is not the name of a valid
544** system call.
545*/
546static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000547 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000548
549 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000550 if( zName ){
551 for(i=0; i<ArraySize(aSyscall)-1; i++){
552 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000553 }
554 }
dan0fd7d862011-03-29 10:04:23 +0000555 for(i++; i<ArraySize(aSyscall); i++){
556 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000557 }
558 return 0;
559}
560
drhad4f1e52011-03-04 15:43:57 +0000561/*
drh77a3fdc2013-08-30 14:24:12 +0000562** Do not accept any file descriptor less than this value, in order to avoid
563** opening database file using file descriptors that are commonly used for
564** standard input, output, and error.
565*/
566#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
567# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
568#endif
569
570/*
drh8c815d12012-02-13 20:16:37 +0000571** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000572** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000573**
574** If the file creation mode "m" is 0 then set it to the default for
575** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
576** 0644) as modified by the system umask. If m is not 0, then
577** make the file creation mode be exactly m ignoring the umask.
578**
579** The m parameter will be non-zero only when creating -wal, -journal,
580** and -shm files. We want those files to have *exactly* the same
581** permissions as their original database, unadulterated by the umask.
582** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
583** transaction crashes and leaves behind hot journals, then any
584** process that is able to write to the database will also be able to
585** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000586*/
drh8c815d12012-02-13 20:16:37 +0000587static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000588 int fd;
drhe1186ab2013-01-04 20:45:13 +0000589 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000590 while(1){
drh5adc60b2012-04-14 13:25:11 +0000591#if defined(O_CLOEXEC)
592 fd = osOpen(z,f|O_CLOEXEC,m2);
593#else
594 fd = osOpen(z,f,m2);
595#endif
drh5128d002013-08-30 06:20:23 +0000596 if( fd<0 ){
597 if( errno==EINTR ) continue;
598 break;
599 }
drh77a3fdc2013-08-30 14:24:12 +0000600 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000601 osClose(fd);
602 sqlite3_log(SQLITE_WARNING,
603 "attempt to open \"%s\" as file descriptor %d", z, fd);
604 fd = -1;
605 if( osOpen("/dev/null", f, m)<0 ) break;
606 }
drhe1186ab2013-01-04 20:45:13 +0000607 if( fd>=0 ){
608 if( m!=0 ){
609 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000610 if( osFstat(fd, &statbuf)==0
611 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000612 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000613 ){
drhe1186ab2013-01-04 20:45:13 +0000614 osFchmod(fd, m);
615 }
616 }
drh5adc60b2012-04-14 13:25:11 +0000617#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000618 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000619#endif
drhe1186ab2013-01-04 20:45:13 +0000620 }
drh5adc60b2012-04-14 13:25:11 +0000621 return fd;
drhad4f1e52011-03-04 15:43:57 +0000622}
danielk197713adf8a2004-06-03 16:08:41 +0000623
drh107886a2008-11-21 22:21:50 +0000624/*
dan9359c7b2009-08-21 08:29:10 +0000625** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000626** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000627** vxworksFileId objects used by this file, all of which may be
628** shared by multiple threads.
629**
630** Function unixMutexHeld() is used to assert() that the global mutex
631** is held when required. This function is only used as part of assert()
632** statements. e.g.
633**
634** unixEnterMutex()
635** assert( unixMutexHeld() );
636** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000637*/
638static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000639 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000640}
641static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000642 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000643}
dan9359c7b2009-08-21 08:29:10 +0000644#ifdef SQLITE_DEBUG
645static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000646 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000647}
648#endif
drh107886a2008-11-21 22:21:50 +0000649
drh734c9862008-11-28 15:37:20 +0000650
mistachkinfb383e92015-04-16 03:24:38 +0000651#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000652/*
653** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000654** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000655** integer lock-type.
656*/
drh308c2a52010-05-14 11:30:18 +0000657static const char *azFileLock(int eFileLock){
658 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000659 case NO_LOCK: return "NONE";
660 case SHARED_LOCK: return "SHARED";
661 case RESERVED_LOCK: return "RESERVED";
662 case PENDING_LOCK: return "PENDING";
663 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000664 }
665 return "ERROR";
666}
667#endif
668
669#ifdef SQLITE_LOCK_TRACE
670/*
671** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000672**
drh734c9862008-11-28 15:37:20 +0000673** This routine is used for troubleshooting locks on multithreaded
674** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
675** command-line option on the compiler. This code is normally
676** turned off.
677*/
678static int lockTrace(int fd, int op, struct flock *p){
679 char *zOpName, *zType;
680 int s;
681 int savedErrno;
682 if( op==F_GETLK ){
683 zOpName = "GETLK";
684 }else if( op==F_SETLK ){
685 zOpName = "SETLK";
686 }else{
drh99ab3b12011-03-02 15:09:07 +0000687 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000688 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
689 return s;
690 }
691 if( p->l_type==F_RDLCK ){
692 zType = "RDLCK";
693 }else if( p->l_type==F_WRLCK ){
694 zType = "WRLCK";
695 }else if( p->l_type==F_UNLCK ){
696 zType = "UNLCK";
697 }else{
698 assert( 0 );
699 }
700 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000701 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000702 savedErrno = errno;
703 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
704 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
705 (int)p->l_pid, s);
706 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
707 struct flock l2;
708 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000709 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000710 if( l2.l_type==F_RDLCK ){
711 zType = "RDLCK";
712 }else if( l2.l_type==F_WRLCK ){
713 zType = "WRLCK";
714 }else if( l2.l_type==F_UNLCK ){
715 zType = "UNLCK";
716 }else{
717 assert( 0 );
718 }
719 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
720 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
721 }
722 errno = savedErrno;
723 return s;
724}
drh99ab3b12011-03-02 15:09:07 +0000725#undef osFcntl
726#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000727#endif /* SQLITE_LOCK_TRACE */
728
drhff812312011-02-23 13:33:46 +0000729/*
730** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000731**
drhe6d41732015-02-21 00:49:00 +0000732** All calls to ftruncate() within this file should be made through
733** this wrapper. On the Android platform, bypassing the logic below
734** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000735*/
drhff812312011-02-23 13:33:46 +0000736static int robust_ftruncate(int h, sqlite3_int64 sz){
737 int rc;
dan2ee53412014-09-06 16:49:40 +0000738#ifdef __ANDROID__
739 /* On Android, ftruncate() always uses 32-bit offsets, even if
740 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000741 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000742 ** such attempts. */
743 if( sz>(sqlite3_int64)0x7FFFFFFF ){
744 rc = SQLITE_OK;
745 }else
746#endif
drh99ab3b12011-03-02 15:09:07 +0000747 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000748 return rc;
749}
drh734c9862008-11-28 15:37:20 +0000750
751/*
752** This routine translates a standard POSIX errno code into something
753** useful to the clients of the sqlite3 functions. Specifically, it is
754** intended to translate a variety of "try again" errors into SQLITE_BUSY
755** and a variety of "please close the file descriptor NOW" errors into
756** SQLITE_IOERR
757**
758** Errors during initialization of locks, or file system support for locks,
759** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
760*/
761static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000762 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
763 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
764 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
765 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000766 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000767 case EACCES:
drh734c9862008-11-28 15:37:20 +0000768 case EAGAIN:
769 case ETIMEDOUT:
770 case EBUSY:
771 case EINTR:
772 case ENOLCK:
773 /* random NFS retry error, unless during file system support
774 * introspection, in which it actually means what it says */
775 return SQLITE_BUSY;
776
drh734c9862008-11-28 15:37:20 +0000777 case EPERM:
778 return SQLITE_PERM;
779
drh734c9862008-11-28 15:37:20 +0000780 default:
781 return sqliteIOErr;
782 }
783}
784
785
drh734c9862008-11-28 15:37:20 +0000786/******************************************************************************
787****************** Begin Unique File ID Utility Used By VxWorks ***************
788**
789** On most versions of unix, we can get a unique ID for a file by concatenating
790** the device number and the inode number. But this does not work on VxWorks.
791** On VxWorks, a unique file id must be based on the canonical filename.
792**
793** A pointer to an instance of the following structure can be used as a
794** unique file ID in VxWorks. Each instance of this structure contains
795** a copy of the canonical filename. There is also a reference count.
796** The structure is reclaimed when the number of pointers to it drops to
797** zero.
798**
799** There are never very many files open at one time and lookups are not
800** a performance-critical path, so it is sufficient to put these
801** structures on a linked list.
802*/
803struct vxworksFileId {
804 struct vxworksFileId *pNext; /* Next in a list of them all */
805 int nRef; /* Number of references to this one */
806 int nName; /* Length of the zCanonicalName[] string */
807 char *zCanonicalName; /* Canonical filename */
808};
809
810#if OS_VXWORKS
811/*
drh9b35ea62008-11-29 02:20:26 +0000812** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000813** variable:
814*/
815static struct vxworksFileId *vxworksFileList = 0;
816
817/*
818** Simplify a filename into its canonical form
819** by making the following changes:
820**
821** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000822** * convert /./ into just /
823** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000824**
825** Changes are made in-place. Return the new name length.
826**
827** The original filename is in z[0..n-1]. Return the number of
828** characters in the simplified name.
829*/
830static int vxworksSimplifyName(char *z, int n){
831 int i, j;
832 while( n>1 && z[n-1]=='/' ){ n--; }
833 for(i=j=0; i<n; i++){
834 if( z[i]=='/' ){
835 if( z[i+1]=='/' ) continue;
836 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
837 i += 1;
838 continue;
839 }
840 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
841 while( j>0 && z[j-1]!='/' ){ j--; }
842 if( j>0 ){ j--; }
843 i += 2;
844 continue;
845 }
846 }
847 z[j++] = z[i];
848 }
849 z[j] = 0;
850 return j;
851}
852
853/*
854** Find a unique file ID for the given absolute pathname. Return
855** a pointer to the vxworksFileId object. This pointer is the unique
856** file ID.
857**
858** The nRef field of the vxworksFileId object is incremented before
859** the object is returned. A new vxworksFileId object is created
860** and added to the global list if necessary.
861**
862** If a memory allocation error occurs, return NULL.
863*/
864static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
865 struct vxworksFileId *pNew; /* search key and new file ID */
866 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
867 int n; /* Length of zAbsoluteName string */
868
869 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000870 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000871 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000872 if( pNew==0 ) return 0;
873 pNew->zCanonicalName = (char*)&pNew[1];
874 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
875 n = vxworksSimplifyName(pNew->zCanonicalName, n);
876
877 /* Search for an existing entry that matching the canonical name.
878 ** If found, increment the reference count and return a pointer to
879 ** the existing file ID.
880 */
881 unixEnterMutex();
882 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
883 if( pCandidate->nName==n
884 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
885 ){
886 sqlite3_free(pNew);
887 pCandidate->nRef++;
888 unixLeaveMutex();
889 return pCandidate;
890 }
891 }
892
893 /* No match was found. We will make a new file ID */
894 pNew->nRef = 1;
895 pNew->nName = n;
896 pNew->pNext = vxworksFileList;
897 vxworksFileList = pNew;
898 unixLeaveMutex();
899 return pNew;
900}
901
902/*
903** Decrement the reference count on a vxworksFileId object. Free
904** the object when the reference count reaches zero.
905*/
906static void vxworksReleaseFileId(struct vxworksFileId *pId){
907 unixEnterMutex();
908 assert( pId->nRef>0 );
909 pId->nRef--;
910 if( pId->nRef==0 ){
911 struct vxworksFileId **pp;
912 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
913 assert( *pp==pId );
914 *pp = pId->pNext;
915 sqlite3_free(pId);
916 }
917 unixLeaveMutex();
918}
919#endif /* OS_VXWORKS */
920/*************** End of Unique File ID Utility Used By VxWorks ****************
921******************************************************************************/
922
923
924/******************************************************************************
925*************************** Posix Advisory Locking ****************************
926**
drh9b35ea62008-11-29 02:20:26 +0000927** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000928** section 6.5.2.2 lines 483 through 490 specify that when a process
929** sets or clears a lock, that operation overrides any prior locks set
930** by the same process. It does not explicitly say so, but this implies
931** that it overrides locks set by the same process using a different
932** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000933**
934** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000935** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
936**
937** Suppose ./file1 and ./file2 are really the same file (because
938** one is a hard or symbolic link to the other) then if you set
939** an exclusive lock on fd1, then try to get an exclusive lock
940** on fd2, it works. I would have expected the second lock to
941** fail since there was already a lock on the file due to fd1.
942** But not so. Since both locks came from the same process, the
943** second overrides the first, even though they were on different
944** file descriptors opened on different file names.
945**
drh734c9862008-11-28 15:37:20 +0000946** This means that we cannot use POSIX locks to synchronize file access
947** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000948** to synchronize access for threads in separate processes, but not
949** threads within the same process.
950**
951** To work around the problem, SQLite has to manage file locks internally
952** on its own. Whenever a new database is opened, we have to find the
953** specific inode of the database file (the inode is determined by the
954** st_dev and st_ino fields of the stat structure that fstat() fills in)
955** and check for locks already existing on that inode. When locks are
956** created or removed, we have to look at our own internal record of the
957** locks to see if another thread has previously set a lock on that same
958** inode.
959**
drh9b35ea62008-11-29 02:20:26 +0000960** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
961** For VxWorks, we have to use the alternative unique ID system based on
962** canonical filename and implemented in the previous division.)
963**
danielk1977ad94b582007-08-20 06:44:22 +0000964** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000965** descriptor. It is now a structure that holds the integer file
966** descriptor and a pointer to a structure that describes the internal
967** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000968** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000969** point to the same locking structure. The locking structure keeps
970** a reference count (so we will know when to delete it) and a "cnt"
971** field that tells us its internal lock status. cnt==0 means the
972** file is unlocked. cnt==-1 means the file has an exclusive lock.
973** cnt>0 means there are cnt shared locks on the file.
974**
975** Any attempt to lock or unlock a file first checks the locking
976** structure. The fcntl() system call is only invoked to set a
977** POSIX lock if the internal lock structure transitions between
978** a locked and an unlocked state.
979**
drh734c9862008-11-28 15:37:20 +0000980** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000981**
982** If you close a file descriptor that points to a file that has locks,
983** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000984** released. To work around this problem, each unixInodeInfo object
985** maintains a count of the number of pending locks on tha inode.
986** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000987** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000988** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000989** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000990** be closed and that list is walked (and cleared) when the last lock
991** clears.
992**
drh9b35ea62008-11-29 02:20:26 +0000993** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000994**
drh9b35ea62008-11-29 02:20:26 +0000995** Many older versions of linux use the LinuxThreads library which is
996** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000997** A cannot be modified or overridden by a different thread B.
998** Only thread A can modify the lock. Locking behavior is correct
999** if the appliation uses the newer Native Posix Thread Library (NPTL)
1000** on linux - with NPTL a lock created by thread A can override locks
1001** in thread B. But there is no way to know at compile-time which
1002** threading library is being used. So there is no way to know at
1003** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001004** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001005** current process.
drh5fdae772004-06-29 03:29:00 +00001006**
drh8af6c222010-05-14 12:43:01 +00001007** SQLite used to support LinuxThreads. But support for LinuxThreads
1008** was dropped beginning with version 3.7.0. SQLite will still work with
1009** LinuxThreads provided that (1) there is no more than one connection
1010** per database file in the same process and (2) database connections
1011** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001012*/
1013
1014/*
1015** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001016** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001017*/
1018struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001019 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001020#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001021 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001022#else
drh107886a2008-11-21 22:21:50 +00001023 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001024#endif
1025};
1026
1027/*
drhbbd42a62004-05-22 17:41:58 +00001028** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001029** inode. Or, on LinuxThreads, there is one of these structures for
1030** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001031**
danielk1977ad94b582007-08-20 06:44:22 +00001032** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001033** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001034** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001035*/
drh8af6c222010-05-14 12:43:01 +00001036struct unixInodeInfo {
1037 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001038 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001039 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1040 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001041 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001042 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1043 int nLock; /* Number of outstanding file locks */
1044 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1045 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1046 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001047#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001048 unsigned long long sharedByte; /* for AFP simulated shared lock */
1049#endif
drh6c7d5c52008-11-21 20:32:33 +00001050#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001051 sem_t *pSem; /* Named POSIX semaphore */
1052 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001053#endif
drhbbd42a62004-05-22 17:41:58 +00001054};
1055
drhda0e7682008-07-30 15:27:54 +00001056/*
drh8af6c222010-05-14 12:43:01 +00001057** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001058*/
drhd91c68f2010-05-14 14:52:25 +00001059static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001060
drh5fdae772004-06-29 03:29:00 +00001061/*
dane18d4952011-02-21 11:46:24 +00001062**
drhaaeaa182015-11-24 15:12:47 +00001063** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001064** unixLogError().
1065**
1066** It is invoked after an error occurs in an OS function and errno has been
1067** set. It logs a message using sqlite3_log() containing the current value of
1068** errno and, if possible, the human-readable equivalent from strerror() or
1069** strerror_r().
1070**
1071** The first argument passed to the macro should be the error code that
1072** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1073** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001074** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001075** if any.
1076*/
drh0e9365c2011-03-02 02:08:13 +00001077#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1078static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001079 int errcode, /* SQLite error code */
1080 const char *zFunc, /* Name of OS function that failed */
1081 const char *zPath, /* File path associated with error */
1082 int iLine /* Source line number where error occurred */
1083){
1084 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001085 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001086
1087 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1088 ** the strerror() function to obtain the human-readable error message
1089 ** equivalent to errno. Otherwise, use strerror_r().
1090 */
1091#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1092 char aErr[80];
1093 memset(aErr, 0, sizeof(aErr));
1094 zErr = aErr;
1095
1096 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001097 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001098 ** returns a pointer to a buffer containing the error message. That pointer
1099 ** may point to aErr[], or it may point to some static storage somewhere.
1100 ** Otherwise, assume that the system provides the POSIX version of
1101 ** strerror_r(), which always writes an error message into aErr[].
1102 **
1103 ** If the code incorrectly assumes that it is the POSIX version that is
1104 ** available, the error message will often be an empty string. Not a
1105 ** huge problem. Incorrectly concluding that the GNU version is available
1106 ** could lead to a segfault though.
1107 */
1108#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1109 zErr =
1110# endif
drh0e9365c2011-03-02 02:08:13 +00001111 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001112
1113#elif SQLITE_THREADSAFE
1114 /* This is a threadsafe build, but strerror_r() is not available. */
1115 zErr = "";
1116#else
1117 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001118 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001119#endif
1120
drh0e9365c2011-03-02 02:08:13 +00001121 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001122 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001123 "os_unix.c:%d: (%d) %s(%s) - %s",
1124 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001125 );
1126
1127 return errcode;
1128}
1129
drh0e9365c2011-03-02 02:08:13 +00001130/*
1131** Close a file descriptor.
1132**
1133** We assume that close() almost always works, since it is only in a
1134** very sick application or on a very sick platform that it might fail.
1135** If it does fail, simply leak the file descriptor, but do log the
1136** error.
1137**
1138** Note that it is not safe to retry close() after EINTR since the
1139** file descriptor might have already been reused by another thread.
1140** So we don't even try to recover from an EINTR. Just log the error
1141** and move on.
1142*/
1143static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001144 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001145 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1146 pFile ? pFile->zPath : 0, lineno);
1147 }
1148}
dane18d4952011-02-21 11:46:24 +00001149
1150/*
drhe6d41732015-02-21 00:49:00 +00001151** Set the pFile->lastErrno. Do this in a subroutine as that provides
1152** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001153*/
1154static void storeLastErrno(unixFile *pFile, int error){
1155 pFile->lastErrno = error;
1156}
1157
1158/*
danb0ac3e32010-06-16 10:55:42 +00001159** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001160*/
drh0e9365c2011-03-02 02:08:13 +00001161static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001162 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001163 UnixUnusedFd *p;
1164 UnixUnusedFd *pNext;
1165 for(p=pInode->pUnused; p; p=pNext){
1166 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001167 robust_close(pFile, p->fd, __LINE__);
1168 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001169 }
drh0e9365c2011-03-02 02:08:13 +00001170 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001171}
1172
1173/*
drh8af6c222010-05-14 12:43:01 +00001174** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001175**
1176** The mutex entered using the unixEnterMutex() function must be held
1177** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001178*/
danb0ac3e32010-06-16 10:55:42 +00001179static void releaseInodeInfo(unixFile *pFile){
1180 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001181 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001182 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001183 pInode->nRef--;
1184 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001185 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001186 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001187 if( pInode->pPrev ){
1188 assert( pInode->pPrev->pNext==pInode );
1189 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001190 }else{
drh8af6c222010-05-14 12:43:01 +00001191 assert( inodeList==pInode );
1192 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001193 }
drh8af6c222010-05-14 12:43:01 +00001194 if( pInode->pNext ){
1195 assert( pInode->pNext->pPrev==pInode );
1196 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001197 }
drh8af6c222010-05-14 12:43:01 +00001198 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001199 }
drhbbd42a62004-05-22 17:41:58 +00001200 }
1201}
1202
1203/*
drh8af6c222010-05-14 12:43:01 +00001204** Given a file descriptor, locate the unixInodeInfo object that
1205** describes that file descriptor. Create a new one if necessary. The
1206** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001207**
dan9359c7b2009-08-21 08:29:10 +00001208** The mutex entered using the unixEnterMutex() function must be held
1209** when this function is called.
1210**
drh6c7d5c52008-11-21 20:32:33 +00001211** Return an appropriate error code.
1212*/
drh8af6c222010-05-14 12:43:01 +00001213static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001214 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001215 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001216){
1217 int rc; /* System call return code */
1218 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001219 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1220 struct stat statbuf; /* Low-level file information */
1221 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001222
dan9359c7b2009-08-21 08:29:10 +00001223 assert( unixMutexHeld() );
1224
drh6c7d5c52008-11-21 20:32:33 +00001225 /* Get low-level information about the file that we can used to
1226 ** create a unique name for the file.
1227 */
1228 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001229 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001230 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001231 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001232#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001233 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1234#endif
1235 return SQLITE_IOERR;
1236 }
1237
drheb0d74f2009-02-03 15:27:02 +00001238#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001239 /* On OS X on an msdos filesystem, the inode number is reported
1240 ** incorrectly for zero-size files. See ticket #3260. To work
1241 ** around this problem (we consider it a bug in OS X, not SQLite)
1242 ** we always increase the file size to 1 by writing a single byte
1243 ** prior to accessing the inode number. The one byte written is
1244 ** an ASCII 'S' character which also happens to be the first byte
1245 ** in the header of every SQLite database. In this way, if there
1246 ** is a race condition such that another thread has already populated
1247 ** the first page of the database, no damage is done.
1248 */
drh7ed97b92010-01-20 13:07:21 +00001249 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001250 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001251 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001252 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001253 return SQLITE_IOERR;
1254 }
drh99ab3b12011-03-02 15:09:07 +00001255 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001256 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001257 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001258 return SQLITE_IOERR;
1259 }
1260 }
drheb0d74f2009-02-03 15:27:02 +00001261#endif
drh6c7d5c52008-11-21 20:32:33 +00001262
drh8af6c222010-05-14 12:43:01 +00001263 memset(&fileId, 0, sizeof(fileId));
1264 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001265#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001266 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001267#else
drh8af6c222010-05-14 12:43:01 +00001268 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001269#endif
drh8af6c222010-05-14 12:43:01 +00001270 pInode = inodeList;
1271 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1272 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001273 }
drh8af6c222010-05-14 12:43:01 +00001274 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001275 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001276 if( pInode==0 ){
1277 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001278 }
drh8af6c222010-05-14 12:43:01 +00001279 memset(pInode, 0, sizeof(*pInode));
1280 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1281 pInode->nRef = 1;
1282 pInode->pNext = inodeList;
1283 pInode->pPrev = 0;
1284 if( inodeList ) inodeList->pPrev = pInode;
1285 inodeList = pInode;
1286 }else{
1287 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001288 }
drh8af6c222010-05-14 12:43:01 +00001289 *ppInode = pInode;
1290 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001291}
drh6c7d5c52008-11-21 20:32:33 +00001292
drhb959a012013-12-07 12:29:22 +00001293/*
1294** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1295*/
1296static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001297#if OS_VXWORKS
1298 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1299#else
drhb959a012013-12-07 12:29:22 +00001300 struct stat buf;
1301 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001302 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001303#endif
drhb959a012013-12-07 12:29:22 +00001304}
1305
aswift5b1a2562008-08-22 00:22:35 +00001306
1307/*
drhfbc7e882013-04-11 01:16:15 +00001308** Check a unixFile that is a database. Verify the following:
1309**
1310** (1) There is exactly one hard link on the file
1311** (2) The file is not a symbolic link
1312** (3) The file has not been renamed or unlinked
1313**
1314** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1315*/
1316static void verifyDbFile(unixFile *pFile){
1317 struct stat buf;
1318 int rc;
drhfbc7e882013-04-11 01:16:15 +00001319 rc = osFstat(pFile->h, &buf);
1320 if( rc!=0 ){
1321 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001322 return;
1323 }
drh3044b512014-06-16 16:41:52 +00001324 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001325 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001326 return;
1327 }
1328 if( buf.st_nlink>1 ){
1329 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001330 return;
1331 }
drhb959a012013-12-07 12:29:22 +00001332 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001333 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001334 return;
1335 }
1336}
1337
1338
1339/*
danielk197713adf8a2004-06-03 16:08:41 +00001340** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001341** file by this or any other process. If such a lock is held, set *pResOut
1342** to a non-zero value otherwise *pResOut is set to zero. The return value
1343** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001344*/
danielk1977861f7452008-06-05 11:39:11 +00001345static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001346 int rc = SQLITE_OK;
1347 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001348 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001349
danielk1977861f7452008-06-05 11:39:11 +00001350 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1351
drh054889e2005-11-30 03:20:31 +00001352 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001353 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001354 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001355
1356 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001357 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001358 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001359 }
1360
drh2ac3ee92004-06-07 16:27:46 +00001361 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001362 */
danielk197709480a92009-02-09 05:32:32 +00001363#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001364 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001365 struct flock lock;
1366 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001367 lock.l_start = RESERVED_BYTE;
1368 lock.l_len = 1;
1369 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001370 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1371 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001372 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001373 } else if( lock.l_type!=F_UNLCK ){
1374 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001375 }
1376 }
danielk197709480a92009-02-09 05:32:32 +00001377#endif
danielk197713adf8a2004-06-03 16:08:41 +00001378
drh6c7d5c52008-11-21 20:32:33 +00001379 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001380 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001381
aswift5b1a2562008-08-22 00:22:35 +00001382 *pResOut = reserved;
1383 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001384}
1385
1386/*
drha7e61d82011-03-12 17:02:57 +00001387** Attempt to set a system-lock on the file pFile. The lock is
1388** described by pLock.
1389**
drh77197112011-03-15 19:08:48 +00001390** If the pFile was opened read/write from unix-excl, then the only lock
1391** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001392** the first time any lock is attempted. All subsequent system locking
1393** operations become no-ops. Locking operations still happen internally,
1394** in order to coordinate access between separate database connections
1395** within this process, but all of that is handled in memory and the
1396** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001397**
1398** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1399** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1400** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001401**
1402** Zero is returned if the call completes successfully, or -1 if a call
1403** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001404*/
1405static int unixFileLock(unixFile *pFile, struct flock *pLock){
1406 int rc;
drh3cb93392011-03-12 18:10:44 +00001407 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001408 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001409 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001410 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1411 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1412 ){
drh3cb93392011-03-12 18:10:44 +00001413 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001414 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001415 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001416 lock.l_whence = SEEK_SET;
1417 lock.l_start = SHARED_FIRST;
1418 lock.l_len = SHARED_SIZE;
1419 lock.l_type = F_WRLCK;
1420 rc = osFcntl(pFile->h, F_SETLK, &lock);
1421 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001422 pInode->bProcessLock = 1;
1423 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001424 }else{
1425 rc = 0;
1426 }
1427 }else{
1428 rc = osFcntl(pFile->h, F_SETLK, pLock);
1429 }
1430 return rc;
1431}
1432
1433/*
drh308c2a52010-05-14 11:30:18 +00001434** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001435** of the following:
1436**
drh2ac3ee92004-06-07 16:27:46 +00001437** (1) SHARED_LOCK
1438** (2) RESERVED_LOCK
1439** (3) PENDING_LOCK
1440** (4) EXCLUSIVE_LOCK
1441**
drhb3e04342004-06-08 00:47:47 +00001442** Sometimes when requesting one lock state, additional lock states
1443** are inserted in between. The locking might fail on one of the later
1444** transitions leaving the lock state different from what it started but
1445** still short of its goal. The following chart shows the allowed
1446** transitions and the inserted intermediate states:
1447**
1448** UNLOCKED -> SHARED
1449** SHARED -> RESERVED
1450** SHARED -> (PENDING) -> EXCLUSIVE
1451** RESERVED -> (PENDING) -> EXCLUSIVE
1452** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001453**
drha6abd042004-06-09 17:37:22 +00001454** This routine will only increase a lock. Use the sqlite3OsUnlock()
1455** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001456*/
drh308c2a52010-05-14 11:30:18 +00001457static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001458 /* The following describes the implementation of the various locks and
1459 ** lock transitions in terms of the POSIX advisory shared and exclusive
1460 ** lock primitives (called read-locks and write-locks below, to avoid
1461 ** confusion with SQLite lock names). The algorithms are complicated
1462 ** slightly in order to be compatible with windows systems simultaneously
1463 ** accessing the same database file, in case that is ever required.
1464 **
1465 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1466 ** byte', each single bytes at well known offsets, and the 'shared byte
1467 ** range', a range of 510 bytes at a well known offset.
1468 **
1469 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1470 ** byte'. If this is successful, a random byte from the 'shared byte
1471 ** range' is read-locked and the lock on the 'pending byte' released.
1472 **
danielk197790ba3bd2004-06-25 08:32:25 +00001473 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1474 ** A RESERVED lock is implemented by grabbing a write-lock on the
1475 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001476 **
1477 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001478 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1479 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1480 ** obtained, but existing SHARED locks are allowed to persist. A process
1481 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1482 ** This property is used by the algorithm for rolling back a journal file
1483 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001484 **
danielk197790ba3bd2004-06-25 08:32:25 +00001485 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1486 ** implemented by obtaining a write-lock on the entire 'shared byte
1487 ** range'. Since all other locks require a read-lock on one of the bytes
1488 ** within this range, this ensures that no other locks are held on the
1489 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001490 **
1491 ** The reason a single byte cannot be used instead of the 'shared byte
1492 ** range' is that some versions of windows do not support read-locks. By
1493 ** locking a random byte from a range, concurrent SHARED locks may exist
1494 ** even if the locking primitive used is always a write-lock.
1495 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001496 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001497 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001498 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001499 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001500 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001501
drh054889e2005-11-30 03:20:31 +00001502 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001503 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1504 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001505 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001506 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001507
1508 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001509 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001510 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001511 */
drh308c2a52010-05-14 11:30:18 +00001512 if( pFile->eFileLock>=eFileLock ){
1513 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1514 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001515 return SQLITE_OK;
1516 }
1517
drh0c2694b2009-09-03 16:23:44 +00001518 /* Make sure the locking sequence is correct.
1519 ** (1) We never move from unlocked to anything higher than shared lock.
1520 ** (2) SQLite never explicitly requests a pendig lock.
1521 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001522 */
drh308c2a52010-05-14 11:30:18 +00001523 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1524 assert( eFileLock!=PENDING_LOCK );
1525 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001526
drh8af6c222010-05-14 12:43:01 +00001527 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001528 */
drh6c7d5c52008-11-21 20:32:33 +00001529 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001530 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001531
danielk1977ad94b582007-08-20 06:44:22 +00001532 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001533 ** handle that precludes the requested lock, return BUSY.
1534 */
drh8af6c222010-05-14 12:43:01 +00001535 if( (pFile->eFileLock!=pInode->eFileLock &&
1536 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 ){
1538 rc = SQLITE_BUSY;
1539 goto end_lock;
1540 }
1541
1542 /* If a SHARED lock is requested, and some thread using this PID already
1543 ** has a SHARED or RESERVED lock, then increment reference counts and
1544 ** return SQLITE_OK.
1545 */
drh308c2a52010-05-14 11:30:18 +00001546 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001547 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001548 assert( eFileLock==SHARED_LOCK );
1549 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001550 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001551 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001552 pInode->nShared++;
1553 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001554 goto end_lock;
1555 }
1556
danielk19779a1d0ab2004-06-01 14:09:28 +00001557
drh3cde3bb2004-06-12 02:17:14 +00001558 /* A PENDING lock is needed before acquiring a SHARED lock and before
1559 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1560 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001561 */
drh0c2694b2009-09-03 16:23:44 +00001562 lock.l_len = 1L;
1563 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001564 if( eFileLock==SHARED_LOCK
1565 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001566 ){
drh308c2a52010-05-14 11:30:18 +00001567 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001568 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001569 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001570 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001571 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001572 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001573 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001574 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001575 goto end_lock;
1576 }
drh3cde3bb2004-06-12 02:17:14 +00001577 }
1578
1579
1580 /* If control gets to this point, then actually go ahead and make
1581 ** operating system calls for the specified lock.
1582 */
drh308c2a52010-05-14 11:30:18 +00001583 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001584 assert( pInode->nShared==0 );
1585 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001586 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001587
drh2ac3ee92004-06-07 16:27:46 +00001588 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001589 lock.l_start = SHARED_FIRST;
1590 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001591 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001592 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001593 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001594 }
dan661d71a2011-03-30 19:08:03 +00001595
drh2ac3ee92004-06-07 16:27:46 +00001596 /* Drop the temporary PENDING lock */
1597 lock.l_start = PENDING_BYTE;
1598 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001599 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001600 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1601 /* This could happen with a network mount */
1602 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001603 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001604 }
dan661d71a2011-03-30 19:08:03 +00001605
1606 if( rc ){
1607 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001608 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001609 }
dan661d71a2011-03-30 19:08:03 +00001610 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001611 }else{
drh308c2a52010-05-14 11:30:18 +00001612 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001613 pInode->nLock++;
1614 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001615 }
drh8af6c222010-05-14 12:43:01 +00001616 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001617 /* We are trying for an exclusive lock but another thread in this
1618 ** same process is still holding a shared lock. */
1619 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001620 }else{
drh3cde3bb2004-06-12 02:17:14 +00001621 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001622 ** assumed that there is a SHARED or greater lock on the file
1623 ** already.
1624 */
drh308c2a52010-05-14 11:30:18 +00001625 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001626 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001627
1628 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1629 if( eFileLock==RESERVED_LOCK ){
1630 lock.l_start = RESERVED_BYTE;
1631 lock.l_len = 1L;
1632 }else{
1633 lock.l_start = SHARED_FIRST;
1634 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001635 }
dan661d71a2011-03-30 19:08:03 +00001636
1637 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001638 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001639 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001640 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001641 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001642 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001643 }
drhbbd42a62004-05-22 17:41:58 +00001644 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001645
drh8f941bc2009-01-14 23:03:40 +00001646
drhd3d8c042012-05-29 17:02:40 +00001647#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001648 /* Set up the transaction-counter change checking flags when
1649 ** transitioning from a SHARED to a RESERVED lock. The change
1650 ** from SHARED to RESERVED marks the beginning of a normal
1651 ** write operation (not a hot journal rollback).
1652 */
1653 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001654 && pFile->eFileLock<=SHARED_LOCK
1655 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001656 ){
1657 pFile->transCntrChng = 0;
1658 pFile->dbUpdate = 0;
1659 pFile->inNormalWrite = 1;
1660 }
1661#endif
1662
1663
danielk1977ecb2a962004-06-02 06:30:16 +00001664 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001665 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001666 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001667 }else if( eFileLock==EXCLUSIVE_LOCK ){
1668 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001669 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001670 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001671
1672end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001673 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001674 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1675 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001676 return rc;
1677}
1678
1679/*
dan08da86a2009-08-21 17:18:03 +00001680** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001681** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001682*/
1683static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001684 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001685 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001686 p->pNext = pInode->pUnused;
1687 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001688 pFile->h = -1;
1689 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001690}
1691
1692/*
drh308c2a52010-05-14 11:30:18 +00001693** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001694** must be either NO_LOCK or SHARED_LOCK.
1695**
1696** If the locking level of the file descriptor is already at or below
1697** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001698**
1699** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1700** the byte range is divided into 2 parts and the first part is unlocked then
1701** set to a read lock, then the other part is simply unlocked. This works
1702** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1703** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001704*/
drha7e61d82011-03-12 17:02:57 +00001705static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001706 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001707 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001708 struct flock lock;
1709 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001710
drh054889e2005-11-30 03:20:31 +00001711 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001712 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001713 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001714 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001715
drh308c2a52010-05-14 11:30:18 +00001716 assert( eFileLock<=SHARED_LOCK );
1717 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001718 return SQLITE_OK;
1719 }
drh6c7d5c52008-11-21 20:32:33 +00001720 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001721 pInode = pFile->pInode;
1722 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001723 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001724 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001725
drhd3d8c042012-05-29 17:02:40 +00001726#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001727 /* When reducing a lock such that other processes can start
1728 ** reading the database file again, make sure that the
1729 ** transaction counter was updated if any part of the database
1730 ** file changed. If the transaction counter is not updated,
1731 ** other connections to the same file might not realize that
1732 ** the file has changed and hence might not know to flush their
1733 ** cache. The use of a stale cache can lead to database corruption.
1734 */
drh8f941bc2009-01-14 23:03:40 +00001735 pFile->inNormalWrite = 0;
1736#endif
1737
drh7ed97b92010-01-20 13:07:21 +00001738 /* downgrading to a shared lock on NFS involves clearing the write lock
1739 ** before establishing the readlock - to avoid a race condition we downgrade
1740 ** the lock in 2 blocks, so that part of the range will be covered by a
1741 ** write lock until the rest is covered by a read lock:
1742 ** 1: [WWWWW]
1743 ** 2: [....W]
1744 ** 3: [RRRRW]
1745 ** 4: [RRRR.]
1746 */
drh308c2a52010-05-14 11:30:18 +00001747 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001748#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001749 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001750 assert( handleNFSUnlock==0 );
1751#endif
1752#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001753 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001754 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001755 off_t divSize = SHARED_SIZE - 1;
1756
1757 lock.l_type = F_UNLCK;
1758 lock.l_whence = SEEK_SET;
1759 lock.l_start = SHARED_FIRST;
1760 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001761 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001762 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001763 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001764 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001765 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001766 }
drh7ed97b92010-01-20 13:07:21 +00001767 lock.l_type = F_RDLCK;
1768 lock.l_whence = SEEK_SET;
1769 lock.l_start = SHARED_FIRST;
1770 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001771 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001772 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001773 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1774 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001775 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001776 }
1777 goto end_unlock;
1778 }
1779 lock.l_type = F_UNLCK;
1780 lock.l_whence = SEEK_SET;
1781 lock.l_start = SHARED_FIRST+divSize;
1782 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001783 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001784 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001785 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001786 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001787 goto end_unlock;
1788 }
drh30f776f2011-02-25 03:25:07 +00001789 }else
1790#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1791 {
drh7ed97b92010-01-20 13:07:21 +00001792 lock.l_type = F_RDLCK;
1793 lock.l_whence = SEEK_SET;
1794 lock.l_start = SHARED_FIRST;
1795 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001796 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001797 /* In theory, the call to unixFileLock() cannot fail because another
1798 ** process is holding an incompatible lock. If it does, this
1799 ** indicates that the other process is not following the locking
1800 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1801 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1802 ** an assert to fail). */
1803 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001804 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001805 goto end_unlock;
1806 }
drh9c105bb2004-10-02 20:38:28 +00001807 }
1808 }
drhbbd42a62004-05-22 17:41:58 +00001809 lock.l_type = F_UNLCK;
1810 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001811 lock.l_start = PENDING_BYTE;
1812 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001813 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001814 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001815 }else{
danea83bc62011-04-01 11:56:32 +00001816 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001817 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001818 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001819 }
drhbbd42a62004-05-22 17:41:58 +00001820 }
drh308c2a52010-05-14 11:30:18 +00001821 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001822 /* Decrement the shared lock counter. Release the lock using an
1823 ** OS call only when all threads in this same process have released
1824 ** the lock.
1825 */
drh8af6c222010-05-14 12:43:01 +00001826 pInode->nShared--;
1827 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001828 lock.l_type = F_UNLCK;
1829 lock.l_whence = SEEK_SET;
1830 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001831 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001832 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001833 }else{
danea83bc62011-04-01 11:56:32 +00001834 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001835 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001836 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001837 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001838 }
drha6abd042004-06-09 17:37:22 +00001839 }
1840
drhbbd42a62004-05-22 17:41:58 +00001841 /* Decrement the count of locks against this same file. When the
1842 ** count reaches zero, close any other file descriptors whose close
1843 ** was deferred because of outstanding locks.
1844 */
drh8af6c222010-05-14 12:43:01 +00001845 pInode->nLock--;
1846 assert( pInode->nLock>=0 );
1847 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001848 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001849 }
1850 }
drhf2f105d2012-08-20 15:53:54 +00001851
aswift5b1a2562008-08-22 00:22:35 +00001852end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001853 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001854 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001855 return rc;
drhbbd42a62004-05-22 17:41:58 +00001856}
1857
1858/*
drh308c2a52010-05-14 11:30:18 +00001859** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001860** must be either NO_LOCK or SHARED_LOCK.
1861**
1862** If the locking level of the file descriptor is already at or below
1863** the requested locking level, this routine is a no-op.
1864*/
drh308c2a52010-05-14 11:30:18 +00001865static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001866#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001867 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001868#endif
drha7e61d82011-03-12 17:02:57 +00001869 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001870}
1871
mistachkine98844f2013-08-24 00:59:24 +00001872#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001873static int unixMapfile(unixFile *pFd, i64 nByte);
1874static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001875#endif
danf23da962013-03-23 21:00:41 +00001876
drh7ed97b92010-01-20 13:07:21 +00001877/*
danielk1977e339d652008-06-28 11:23:00 +00001878** This function performs the parts of the "close file" operation
1879** common to all locking schemes. It closes the directory and file
1880** handles, if they are valid, and sets all fields of the unixFile
1881** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001882**
1883** It is *not* necessary to hold the mutex when this routine is called,
1884** even on VxWorks. A mutex will be acquired on VxWorks by the
1885** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001886*/
1887static int closeUnixFile(sqlite3_file *id){
1888 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001889#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001890 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001891#endif
dan661d71a2011-03-30 19:08:03 +00001892 if( pFile->h>=0 ){
1893 robust_close(pFile, pFile->h, __LINE__);
1894 pFile->h = -1;
1895 }
1896#if OS_VXWORKS
1897 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001898 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001899 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001900 }
1901 vxworksReleaseFileId(pFile->pId);
1902 pFile->pId = 0;
1903 }
1904#endif
drh0bdbc902014-06-16 18:35:06 +00001905#ifdef SQLITE_UNLINK_AFTER_CLOSE
1906 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1907 osUnlink(pFile->zPath);
1908 sqlite3_free(*(char**)&pFile->zPath);
1909 pFile->zPath = 0;
1910 }
1911#endif
dan661d71a2011-03-30 19:08:03 +00001912 OSTRACE(("CLOSE %-3d\n", pFile->h));
1913 OpenCounter(-1);
1914 sqlite3_free(pFile->pUnused);
1915 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001916 return SQLITE_OK;
1917}
1918
1919/*
danielk1977e3026632004-06-22 11:29:02 +00001920** Close a file.
1921*/
danielk197762079062007-08-15 17:08:46 +00001922static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001923 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001924 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001925 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001926 unixUnlock(id, NO_LOCK);
1927 unixEnterMutex();
1928
1929 /* unixFile.pInode is always valid here. Otherwise, a different close
1930 ** routine (e.g. nolockClose()) would be called instead.
1931 */
1932 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1933 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1934 /* If there are outstanding locks, do not actually close the file just
1935 ** yet because that would clear those locks. Instead, add the file
1936 ** descriptor to pInode->pUnused list. It will be automatically closed
1937 ** when the last lock is cleared.
1938 */
1939 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001940 }
dan661d71a2011-03-30 19:08:03 +00001941 releaseInodeInfo(pFile);
1942 rc = closeUnixFile(id);
1943 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001944 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001945}
1946
drh734c9862008-11-28 15:37:20 +00001947/************** End of the posix advisory lock implementation *****************
1948******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001949
drh734c9862008-11-28 15:37:20 +00001950/******************************************************************************
1951****************************** No-op Locking **********************************
1952**
1953** Of the various locking implementations available, this is by far the
1954** simplest: locking is ignored. No attempt is made to lock the database
1955** file for reading or writing.
1956**
1957** This locking mode is appropriate for use on read-only databases
1958** (ex: databases that are burned into CD-ROM, for example.) It can
1959** also be used if the application employs some external mechanism to
1960** prevent simultaneous access of the same database by two or more
1961** database connections. But there is a serious risk of database
1962** corruption if this locking mode is used in situations where multiple
1963** database connections are accessing the same database file at the same
1964** time and one or more of those connections are writing.
1965*/
drhbfe66312006-10-03 17:40:40 +00001966
drh734c9862008-11-28 15:37:20 +00001967static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1968 UNUSED_PARAMETER(NotUsed);
1969 *pResOut = 0;
1970 return SQLITE_OK;
1971}
drh734c9862008-11-28 15:37:20 +00001972static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1973 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1974 return SQLITE_OK;
1975}
drh734c9862008-11-28 15:37:20 +00001976static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1977 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1978 return SQLITE_OK;
1979}
1980
1981/*
drh9b35ea62008-11-29 02:20:26 +00001982** Close the file.
drh734c9862008-11-28 15:37:20 +00001983*/
1984static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001985 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001986}
1987
1988/******************* End of the no-op lock implementation *********************
1989******************************************************************************/
1990
1991/******************************************************************************
1992************************* Begin dot-file Locking ******************************
1993**
mistachkin48864df2013-03-21 21:20:32 +00001994** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001995** files (really a directory) to control access to the database. This works
1996** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001997**
1998** (1) There is zero concurrency. A single reader blocks all other
1999** connections from reading or writing the database.
2000**
2001** (2) An application crash or power loss can leave stale lock files
2002** sitting around that need to be cleared manually.
2003**
2004** Nevertheless, a dotlock is an appropriate locking mode for use if no
2005** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002006**
drh9ef6bc42011-11-04 02:24:02 +00002007** Dotfile locking works by creating a subdirectory in the same directory as
2008** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002009** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002010** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002011*/
2012
2013/*
2014** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002015** lock directory.
drh734c9862008-11-28 15:37:20 +00002016*/
2017#define DOTLOCK_SUFFIX ".lock"
2018
drh7708e972008-11-29 00:56:52 +00002019/*
2020** This routine checks if there is a RESERVED lock held on the specified
2021** file by this or any other process. If such a lock is held, set *pResOut
2022** to a non-zero value otherwise *pResOut is set to zero. The return value
2023** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2024**
2025** In dotfile locking, either a lock exists or it does not. So in this
2026** variation of CheckReservedLock(), *pResOut is set to true if any lock
2027** is held on the file and false if the file is unlocked.
2028*/
drh734c9862008-11-28 15:37:20 +00002029static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2030 int rc = SQLITE_OK;
2031 int reserved = 0;
2032 unixFile *pFile = (unixFile*)id;
2033
2034 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2035
2036 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002037 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002038 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002039 *pResOut = reserved;
2040 return rc;
2041}
2042
drh7708e972008-11-29 00:56:52 +00002043/*
drh308c2a52010-05-14 11:30:18 +00002044** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002045** of the following:
2046**
2047** (1) SHARED_LOCK
2048** (2) RESERVED_LOCK
2049** (3) PENDING_LOCK
2050** (4) EXCLUSIVE_LOCK
2051**
2052** Sometimes when requesting one lock state, additional lock states
2053** are inserted in between. The locking might fail on one of the later
2054** transitions leaving the lock state different from what it started but
2055** still short of its goal. The following chart shows the allowed
2056** transitions and the inserted intermediate states:
2057**
2058** UNLOCKED -> SHARED
2059** SHARED -> RESERVED
2060** SHARED -> (PENDING) -> EXCLUSIVE
2061** RESERVED -> (PENDING) -> EXCLUSIVE
2062** PENDING -> EXCLUSIVE
2063**
2064** This routine will only increase a lock. Use the sqlite3OsUnlock()
2065** routine to lower a locking level.
2066**
2067** With dotfile locking, we really only support state (4): EXCLUSIVE.
2068** But we track the other locking levels internally.
2069*/
drh308c2a52010-05-14 11:30:18 +00002070static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002071 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002072 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002073 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002074
drh7708e972008-11-29 00:56:52 +00002075
2076 /* If we have any lock, then the lock file already exists. All we have
2077 ** to do is adjust our internal record of the lock level.
2078 */
drh308c2a52010-05-14 11:30:18 +00002079 if( pFile->eFileLock > NO_LOCK ){
2080 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002081 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002082#ifdef HAVE_UTIME
2083 utime(zLockFile, NULL);
2084#else
drh734c9862008-11-28 15:37:20 +00002085 utimes(zLockFile, NULL);
2086#endif
drh7708e972008-11-29 00:56:52 +00002087 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002088 }
2089
2090 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002091 rc = osMkdir(zLockFile, 0777);
2092 if( rc<0 ){
2093 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002094 int tErrno = errno;
2095 if( EEXIST == tErrno ){
2096 rc = SQLITE_BUSY;
2097 } else {
2098 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002099 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002100 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002101 }
2102 }
drh7708e972008-11-29 00:56:52 +00002103 return rc;
drh734c9862008-11-28 15:37:20 +00002104 }
drh734c9862008-11-28 15:37:20 +00002105
2106 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002107 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002108 return rc;
2109}
2110
drh7708e972008-11-29 00:56:52 +00002111/*
drh308c2a52010-05-14 11:30:18 +00002112** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002113** must be either NO_LOCK or SHARED_LOCK.
2114**
2115** If the locking level of the file descriptor is already at or below
2116** the requested locking level, this routine is a no-op.
2117**
2118** When the locking level reaches NO_LOCK, delete the lock file.
2119*/
drh308c2a52010-05-14 11:30:18 +00002120static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002121 unixFile *pFile = (unixFile*)id;
2122 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002123 int rc;
drh734c9862008-11-28 15:37:20 +00002124
2125 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002126 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002127 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002128 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002129
2130 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002131 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002132 return SQLITE_OK;
2133 }
drh7708e972008-11-29 00:56:52 +00002134
2135 /* To downgrade to shared, simply update our internal notion of the
2136 ** lock state. No need to mess with the file on disk.
2137 */
drh308c2a52010-05-14 11:30:18 +00002138 if( eFileLock==SHARED_LOCK ){
2139 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002140 return SQLITE_OK;
2141 }
2142
drh7708e972008-11-29 00:56:52 +00002143 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002144 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002145 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002146 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002147 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002148 if( tErrno==ENOENT ){
2149 rc = SQLITE_OK;
2150 }else{
danea83bc62011-04-01 11:56:32 +00002151 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002152 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002153 }
2154 return rc;
2155 }
drh308c2a52010-05-14 11:30:18 +00002156 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002157 return SQLITE_OK;
2158}
2159
2160/*
drh9b35ea62008-11-29 02:20:26 +00002161** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002162*/
2163static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002164 unixFile *pFile = (unixFile*)id;
2165 assert( id!=0 );
2166 dotlockUnlock(id, NO_LOCK);
2167 sqlite3_free(pFile->lockingContext);
2168 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002169}
2170/****************** End of the dot-file lock implementation *******************
2171******************************************************************************/
2172
2173/******************************************************************************
2174************************** Begin flock Locking ********************************
2175**
2176** Use the flock() system call to do file locking.
2177**
drh6b9d6dd2008-12-03 19:34:47 +00002178** flock() locking is like dot-file locking in that the various
2179** fine-grain locking levels supported by SQLite are collapsed into
2180** a single exclusive lock. In other words, SHARED, RESERVED, and
2181** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2182** still works when you do this, but concurrency is reduced since
2183** only a single process can be reading the database at a time.
2184**
drhe89b2912015-03-03 20:42:01 +00002185** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002186*/
drhe89b2912015-03-03 20:42:01 +00002187#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002188
drh6b9d6dd2008-12-03 19:34:47 +00002189/*
drhff812312011-02-23 13:33:46 +00002190** Retry flock() calls that fail with EINTR
2191*/
2192#ifdef EINTR
2193static int robust_flock(int fd, int op){
2194 int rc;
2195 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2196 return rc;
2197}
2198#else
drh5c819272011-02-23 14:00:12 +00002199# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002200#endif
2201
2202
2203/*
drh6b9d6dd2008-12-03 19:34:47 +00002204** This routine checks if there is a RESERVED lock held on the specified
2205** file by this or any other process. If such a lock is held, set *pResOut
2206** to a non-zero value otherwise *pResOut is set to zero. The return value
2207** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2208*/
drh734c9862008-11-28 15:37:20 +00002209static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2210 int rc = SQLITE_OK;
2211 int reserved = 0;
2212 unixFile *pFile = (unixFile*)id;
2213
2214 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2215
2216 assert( pFile );
2217
2218 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002219 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002220 reserved = 1;
2221 }
2222
2223 /* Otherwise see if some other process holds it. */
2224 if( !reserved ){
2225 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002226 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002227 if( !lrc ){
2228 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002229 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002230 if ( lrc ) {
2231 int tErrno = errno;
2232 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002233 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002234 storeLastErrno(pFile, tErrno);
2235 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002236 }
2237 } else {
2238 int tErrno = errno;
2239 reserved = 1;
2240 /* someone else might have it reserved */
2241 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2242 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002243 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002244 rc = lrc;
2245 }
2246 }
2247 }
drh308c2a52010-05-14 11:30:18 +00002248 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002249
2250#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2251 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2252 rc = SQLITE_OK;
2253 reserved=1;
2254 }
2255#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2256 *pResOut = reserved;
2257 return rc;
2258}
2259
drh6b9d6dd2008-12-03 19:34:47 +00002260/*
drh308c2a52010-05-14 11:30:18 +00002261** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002262** of the following:
2263**
2264** (1) SHARED_LOCK
2265** (2) RESERVED_LOCK
2266** (3) PENDING_LOCK
2267** (4) EXCLUSIVE_LOCK
2268**
2269** Sometimes when requesting one lock state, additional lock states
2270** are inserted in between. The locking might fail on one of the later
2271** transitions leaving the lock state different from what it started but
2272** still short of its goal. The following chart shows the allowed
2273** transitions and the inserted intermediate states:
2274**
2275** UNLOCKED -> SHARED
2276** SHARED -> RESERVED
2277** SHARED -> (PENDING) -> EXCLUSIVE
2278** RESERVED -> (PENDING) -> EXCLUSIVE
2279** PENDING -> EXCLUSIVE
2280**
2281** flock() only really support EXCLUSIVE locks. We track intermediate
2282** lock states in the sqlite3_file structure, but all locks SHARED or
2283** above are really EXCLUSIVE locks and exclude all other processes from
2284** access the file.
2285**
2286** This routine will only increase a lock. Use the sqlite3OsUnlock()
2287** routine to lower a locking level.
2288*/
drh308c2a52010-05-14 11:30:18 +00002289static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002290 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002291 unixFile *pFile = (unixFile*)id;
2292
2293 assert( pFile );
2294
2295 /* if we already have a lock, it is exclusive.
2296 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002297 if (pFile->eFileLock > NO_LOCK) {
2298 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002299 return SQLITE_OK;
2300 }
2301
2302 /* grab an exclusive lock */
2303
drhff812312011-02-23 13:33:46 +00002304 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002305 int tErrno = errno;
2306 /* didn't get, must be busy */
2307 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2308 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002309 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002310 }
2311 } else {
2312 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002313 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002314 }
drh308c2a52010-05-14 11:30:18 +00002315 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2316 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002317#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2318 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2319 rc = SQLITE_BUSY;
2320 }
2321#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2322 return rc;
2323}
2324
drh6b9d6dd2008-12-03 19:34:47 +00002325
2326/*
drh308c2a52010-05-14 11:30:18 +00002327** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002328** must be either NO_LOCK or SHARED_LOCK.
2329**
2330** If the locking level of the file descriptor is already at or below
2331** the requested locking level, this routine is a no-op.
2332*/
drh308c2a52010-05-14 11:30:18 +00002333static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002334 unixFile *pFile = (unixFile*)id;
2335
2336 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002337 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002338 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002339 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002340
2341 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002342 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002343 return SQLITE_OK;
2344 }
2345
2346 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002347 if (eFileLock==SHARED_LOCK) {
2348 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002349 return SQLITE_OK;
2350 }
2351
2352 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002353 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002354#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002355 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002356#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002357 return SQLITE_IOERR_UNLOCK;
2358 }else{
drh308c2a52010-05-14 11:30:18 +00002359 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002360 return SQLITE_OK;
2361 }
2362}
2363
2364/*
2365** Close a file.
2366*/
2367static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002368 assert( id!=0 );
2369 flockUnlock(id, NO_LOCK);
2370 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002371}
2372
2373#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2374
2375/******************* End of the flock lock implementation *********************
2376******************************************************************************/
2377
2378/******************************************************************************
2379************************ Begin Named Semaphore Locking ************************
2380**
2381** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002382**
2383** Semaphore locking is like dot-lock and flock in that it really only
2384** supports EXCLUSIVE locking. Only a single process can read or write
2385** the database file at a time. This reduces potential concurrency, but
2386** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002387*/
2388#if OS_VXWORKS
2389
drh6b9d6dd2008-12-03 19:34:47 +00002390/*
2391** This routine checks if there is a RESERVED lock held on the specified
2392** file by this or any other process. If such a lock is held, set *pResOut
2393** to a non-zero value otherwise *pResOut is set to zero. The return value
2394** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2395*/
drh8cd5b252015-03-02 22:06:43 +00002396static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002397 int rc = SQLITE_OK;
2398 int reserved = 0;
2399 unixFile *pFile = (unixFile*)id;
2400
2401 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2402
2403 assert( pFile );
2404
2405 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002406 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002407 reserved = 1;
2408 }
2409
2410 /* Otherwise see if some other process holds it. */
2411 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002412 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002413
2414 if( sem_trywait(pSem)==-1 ){
2415 int tErrno = errno;
2416 if( EAGAIN != tErrno ){
2417 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002418 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002419 } else {
2420 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002421 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002422 }
2423 }else{
2424 /* we could have it if we want it */
2425 sem_post(pSem);
2426 }
2427 }
drh308c2a52010-05-14 11:30:18 +00002428 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002429
2430 *pResOut = reserved;
2431 return rc;
2432}
2433
drh6b9d6dd2008-12-03 19:34:47 +00002434/*
drh308c2a52010-05-14 11:30:18 +00002435** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002436** of the following:
2437**
2438** (1) SHARED_LOCK
2439** (2) RESERVED_LOCK
2440** (3) PENDING_LOCK
2441** (4) EXCLUSIVE_LOCK
2442**
2443** Sometimes when requesting one lock state, additional lock states
2444** are inserted in between. The locking might fail on one of the later
2445** transitions leaving the lock state different from what it started but
2446** still short of its goal. The following chart shows the allowed
2447** transitions and the inserted intermediate states:
2448**
2449** UNLOCKED -> SHARED
2450** SHARED -> RESERVED
2451** SHARED -> (PENDING) -> EXCLUSIVE
2452** RESERVED -> (PENDING) -> EXCLUSIVE
2453** PENDING -> EXCLUSIVE
2454**
2455** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2456** lock states in the sqlite3_file structure, but all locks SHARED or
2457** above are really EXCLUSIVE locks and exclude all other processes from
2458** access the file.
2459**
2460** This routine will only increase a lock. Use the sqlite3OsUnlock()
2461** routine to lower a locking level.
2462*/
drh8cd5b252015-03-02 22:06:43 +00002463static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002464 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002465 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002466 int rc = SQLITE_OK;
2467
2468 /* if we already have a lock, it is exclusive.
2469 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002470 if (pFile->eFileLock > NO_LOCK) {
2471 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002472 rc = SQLITE_OK;
2473 goto sem_end_lock;
2474 }
2475
2476 /* lock semaphore now but bail out when already locked. */
2477 if( sem_trywait(pSem)==-1 ){
2478 rc = SQLITE_BUSY;
2479 goto sem_end_lock;
2480 }
2481
2482 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002483 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002484
2485 sem_end_lock:
2486 return rc;
2487}
2488
drh6b9d6dd2008-12-03 19:34:47 +00002489/*
drh308c2a52010-05-14 11:30:18 +00002490** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002491** must be either NO_LOCK or SHARED_LOCK.
2492**
2493** If the locking level of the file descriptor is already at or below
2494** the requested locking level, this routine is a no-op.
2495*/
drh8cd5b252015-03-02 22:06:43 +00002496static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002497 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002498 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002499
2500 assert( pFile );
2501 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002502 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002503 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002504 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002505
2506 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002507 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002508 return SQLITE_OK;
2509 }
2510
2511 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002512 if (eFileLock==SHARED_LOCK) {
2513 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002514 return SQLITE_OK;
2515 }
2516
2517 /* no, really unlock. */
2518 if ( sem_post(pSem)==-1 ) {
2519 int rc, tErrno = errno;
2520 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2521 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002522 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002523 }
2524 return rc;
2525 }
drh308c2a52010-05-14 11:30:18 +00002526 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002527 return SQLITE_OK;
2528}
2529
2530/*
2531 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002532 */
drh8cd5b252015-03-02 22:06:43 +00002533static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002534 if( id ){
2535 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002536 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002537 assert( pFile );
2538 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002539 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002540 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002541 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002542 }
2543 return SQLITE_OK;
2544}
2545
2546#endif /* OS_VXWORKS */
2547/*
2548** Named semaphore locking is only available on VxWorks.
2549**
2550*************** End of the named semaphore lock implementation ****************
2551******************************************************************************/
2552
2553
2554/******************************************************************************
2555*************************** Begin AFP Locking *********************************
2556**
2557** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2558** on Apple Macintosh computers - both OS9 and OSX.
2559**
2560** Third-party implementations of AFP are available. But this code here
2561** only works on OSX.
2562*/
2563
drhd2cb50b2009-01-09 21:41:17 +00002564#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002565/*
2566** The afpLockingContext structure contains all afp lock specific state
2567*/
drhbfe66312006-10-03 17:40:40 +00002568typedef struct afpLockingContext afpLockingContext;
2569struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002570 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002571 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002572};
2573
2574struct ByteRangeLockPB2
2575{
2576 unsigned long long offset; /* offset to first byte to lock */
2577 unsigned long long length; /* nbr of bytes to lock */
2578 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2579 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2580 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2581 int fd; /* file desc to assoc this lock with */
2582};
2583
drhfd131da2007-08-07 17:13:03 +00002584#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002585
drh6b9d6dd2008-12-03 19:34:47 +00002586/*
2587** This is a utility for setting or clearing a bit-range lock on an
2588** AFP filesystem.
2589**
2590** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2591*/
2592static int afpSetLock(
2593 const char *path, /* Name of the file to be locked or unlocked */
2594 unixFile *pFile, /* Open file descriptor on path */
2595 unsigned long long offset, /* First byte to be locked */
2596 unsigned long long length, /* Number of bytes to lock */
2597 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002598){
drh6b9d6dd2008-12-03 19:34:47 +00002599 struct ByteRangeLockPB2 pb;
2600 int err;
drhbfe66312006-10-03 17:40:40 +00002601
2602 pb.unLockFlag = setLockFlag ? 0 : 1;
2603 pb.startEndFlag = 0;
2604 pb.offset = offset;
2605 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002606 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002607
drh308c2a52010-05-14 11:30:18 +00002608 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002609 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002610 offset, length));
drhbfe66312006-10-03 17:40:40 +00002611 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2612 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002613 int rc;
2614 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002615 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2616 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002617#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2618 rc = SQLITE_BUSY;
2619#else
drh734c9862008-11-28 15:37:20 +00002620 rc = sqliteErrorFromPosixError(tErrno,
2621 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002622#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002623 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002624 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002625 }
2626 return rc;
drhbfe66312006-10-03 17:40:40 +00002627 } else {
aswift5b1a2562008-08-22 00:22:35 +00002628 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002629 }
2630}
2631
drh6b9d6dd2008-12-03 19:34:47 +00002632/*
2633** This routine checks if there is a RESERVED lock held on the specified
2634** file by this or any other process. If such a lock is held, set *pResOut
2635** to a non-zero value otherwise *pResOut is set to zero. The return value
2636** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2637*/
danielk1977e339d652008-06-28 11:23:00 +00002638static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002639 int rc = SQLITE_OK;
2640 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002641 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002642 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002643
aswift5b1a2562008-08-22 00:22:35 +00002644 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2645
2646 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002647 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002648 if( context->reserved ){
2649 *pResOut = 1;
2650 return SQLITE_OK;
2651 }
drh8af6c222010-05-14 12:43:01 +00002652 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002653
2654 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002655 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002656 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002657 }
2658
2659 /* Otherwise see if some other process holds it.
2660 */
aswift5b1a2562008-08-22 00:22:35 +00002661 if( !reserved ){
2662 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002663 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002664 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002665 /* if we succeeded in taking the reserved lock, unlock it to restore
2666 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002667 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002668 } else {
2669 /* if we failed to get the lock then someone else must have it */
2670 reserved = 1;
2671 }
2672 if( IS_LOCK_ERROR(lrc) ){
2673 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002674 }
2675 }
drhbfe66312006-10-03 17:40:40 +00002676
drh7ed97b92010-01-20 13:07:21 +00002677 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002678 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002679
2680 *pResOut = reserved;
2681 return rc;
drhbfe66312006-10-03 17:40:40 +00002682}
2683
drh6b9d6dd2008-12-03 19:34:47 +00002684/*
drh308c2a52010-05-14 11:30:18 +00002685** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002686** of the following:
2687**
2688** (1) SHARED_LOCK
2689** (2) RESERVED_LOCK
2690** (3) PENDING_LOCK
2691** (4) EXCLUSIVE_LOCK
2692**
2693** Sometimes when requesting one lock state, additional lock states
2694** are inserted in between. The locking might fail on one of the later
2695** transitions leaving the lock state different from what it started but
2696** still short of its goal. The following chart shows the allowed
2697** transitions and the inserted intermediate states:
2698**
2699** UNLOCKED -> SHARED
2700** SHARED -> RESERVED
2701** SHARED -> (PENDING) -> EXCLUSIVE
2702** RESERVED -> (PENDING) -> EXCLUSIVE
2703** PENDING -> EXCLUSIVE
2704**
2705** This routine will only increase a lock. Use the sqlite3OsUnlock()
2706** routine to lower a locking level.
2707*/
drh308c2a52010-05-14 11:30:18 +00002708static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002709 int rc = SQLITE_OK;
2710 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002711 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002712 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002713
2714 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002715 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2716 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002717 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002718
drhbfe66312006-10-03 17:40:40 +00002719 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002720 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002721 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002722 */
drh308c2a52010-05-14 11:30:18 +00002723 if( pFile->eFileLock>=eFileLock ){
2724 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2725 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002726 return SQLITE_OK;
2727 }
2728
2729 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002730 ** (1) We never move from unlocked to anything higher than shared lock.
2731 ** (2) SQLite never explicitly requests a pendig lock.
2732 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002733 */
drh308c2a52010-05-14 11:30:18 +00002734 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2735 assert( eFileLock!=PENDING_LOCK );
2736 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002737
drh8af6c222010-05-14 12:43:01 +00002738 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002739 */
drh6c7d5c52008-11-21 20:32:33 +00002740 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002741 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002742
2743 /* If some thread using this PID has a lock via a different unixFile*
2744 ** handle that precludes the requested lock, return BUSY.
2745 */
drh8af6c222010-05-14 12:43:01 +00002746 if( (pFile->eFileLock!=pInode->eFileLock &&
2747 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002748 ){
2749 rc = SQLITE_BUSY;
2750 goto afp_end_lock;
2751 }
2752
2753 /* If a SHARED lock is requested, and some thread using this PID already
2754 ** has a SHARED or RESERVED lock, then increment reference counts and
2755 ** return SQLITE_OK.
2756 */
drh308c2a52010-05-14 11:30:18 +00002757 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002758 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002759 assert( eFileLock==SHARED_LOCK );
2760 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002761 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002762 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002763 pInode->nShared++;
2764 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002765 goto afp_end_lock;
2766 }
drhbfe66312006-10-03 17:40:40 +00002767
2768 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002769 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2770 ** be released.
2771 */
drh308c2a52010-05-14 11:30:18 +00002772 if( eFileLock==SHARED_LOCK
2773 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002774 ){
2775 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002776 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002777 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002778 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002779 goto afp_end_lock;
2780 }
2781 }
2782
2783 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002784 ** operating system calls for the specified lock.
2785 */
drh308c2a52010-05-14 11:30:18 +00002786 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002787 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002788 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002789
drh8af6c222010-05-14 12:43:01 +00002790 assert( pInode->nShared==0 );
2791 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002792
2793 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002794 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002795 /* note that the quality of the randomness doesn't matter that much */
2796 lk = random();
drh8af6c222010-05-14 12:43:01 +00002797 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002798 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002799 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002800 if( IS_LOCK_ERROR(lrc1) ){
2801 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002802 }
aswift5b1a2562008-08-22 00:22:35 +00002803 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002804 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002805
aswift5b1a2562008-08-22 00:22:35 +00002806 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002807 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002808 rc = lrc1;
2809 goto afp_end_lock;
2810 } else if( IS_LOCK_ERROR(lrc2) ){
2811 rc = lrc2;
2812 goto afp_end_lock;
2813 } else if( lrc1 != SQLITE_OK ) {
2814 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002815 } else {
drh308c2a52010-05-14 11:30:18 +00002816 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002817 pInode->nLock++;
2818 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002819 }
drh8af6c222010-05-14 12:43:01 +00002820 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002821 /* We are trying for an exclusive lock but another thread in this
2822 ** same process is still holding a shared lock. */
2823 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002824 }else{
2825 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2826 ** assumed that there is a SHARED or greater lock on the file
2827 ** already.
2828 */
2829 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002830 assert( 0!=pFile->eFileLock );
2831 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002832 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002833 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002834 if( !failed ){
2835 context->reserved = 1;
2836 }
drhbfe66312006-10-03 17:40:40 +00002837 }
drh308c2a52010-05-14 11:30:18 +00002838 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002839 /* Acquire an EXCLUSIVE lock */
2840
2841 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002842 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002843 */
drh6b9d6dd2008-12-03 19:34:47 +00002844 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002845 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002846 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002847 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002848 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002849 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002850 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002851 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002852 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2853 ** a critical I/O error
2854 */
2855 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2856 SQLITE_IOERR_LOCK;
2857 goto afp_end_lock;
2858 }
2859 }else{
aswift5b1a2562008-08-22 00:22:35 +00002860 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002861 }
2862 }
aswift5b1a2562008-08-22 00:22:35 +00002863 if( failed ){
2864 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002865 }
2866 }
2867
2868 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002869 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002870 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002871 }else if( eFileLock==EXCLUSIVE_LOCK ){
2872 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002873 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002874 }
2875
2876afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002877 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002878 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2879 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002880 return rc;
2881}
2882
2883/*
drh308c2a52010-05-14 11:30:18 +00002884** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002885** must be either NO_LOCK or SHARED_LOCK.
2886**
2887** If the locking level of the file descriptor is already at or below
2888** the requested locking level, this routine is a no-op.
2889*/
drh308c2a52010-05-14 11:30:18 +00002890static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002891 int rc = SQLITE_OK;
2892 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002893 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002894 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2895 int skipShared = 0;
2896#ifdef SQLITE_TEST
2897 int h = pFile->h;
2898#endif
drhbfe66312006-10-03 17:40:40 +00002899
2900 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002901 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002902 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002903 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002904
drh308c2a52010-05-14 11:30:18 +00002905 assert( eFileLock<=SHARED_LOCK );
2906 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002907 return SQLITE_OK;
2908 }
drh6c7d5c52008-11-21 20:32:33 +00002909 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002910 pInode = pFile->pInode;
2911 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002912 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002913 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002914 SimulateIOErrorBenign(1);
2915 SimulateIOError( h=(-1) )
2916 SimulateIOErrorBenign(0);
2917
drhd3d8c042012-05-29 17:02:40 +00002918#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002919 /* When reducing a lock such that other processes can start
2920 ** reading the database file again, make sure that the
2921 ** transaction counter was updated if any part of the database
2922 ** file changed. If the transaction counter is not updated,
2923 ** other connections to the same file might not realize that
2924 ** the file has changed and hence might not know to flush their
2925 ** cache. The use of a stale cache can lead to database corruption.
2926 */
2927 assert( pFile->inNormalWrite==0
2928 || pFile->dbUpdate==0
2929 || pFile->transCntrChng==1 );
2930 pFile->inNormalWrite = 0;
2931#endif
aswiftaebf4132008-11-21 00:10:35 +00002932
drh308c2a52010-05-14 11:30:18 +00002933 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002934 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002935 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002936 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002937 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002938 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2939 } else {
2940 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002941 }
2942 }
drh308c2a52010-05-14 11:30:18 +00002943 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002944 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002945 }
drh308c2a52010-05-14 11:30:18 +00002946 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002947 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2948 if( !rc ){
2949 context->reserved = 0;
2950 }
aswiftaebf4132008-11-21 00:10:35 +00002951 }
drh8af6c222010-05-14 12:43:01 +00002952 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2953 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002954 }
aswiftaebf4132008-11-21 00:10:35 +00002955 }
drh308c2a52010-05-14 11:30:18 +00002956 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002957
drh7ed97b92010-01-20 13:07:21 +00002958 /* Decrement the shared lock counter. Release the lock using an
2959 ** OS call only when all threads in this same process have released
2960 ** the lock.
2961 */
drh8af6c222010-05-14 12:43:01 +00002962 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2963 pInode->nShared--;
2964 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002965 SimulateIOErrorBenign(1);
2966 SimulateIOError( h=(-1) )
2967 SimulateIOErrorBenign(0);
2968 if( !skipShared ){
2969 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2970 }
2971 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002972 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002973 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002974 }
2975 }
2976 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002977 pInode->nLock--;
2978 assert( pInode->nLock>=0 );
2979 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002980 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002981 }
2982 }
drhbfe66312006-10-03 17:40:40 +00002983 }
drh7ed97b92010-01-20 13:07:21 +00002984
drh6c7d5c52008-11-21 20:32:33 +00002985 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002986 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002987 return rc;
2988}
2989
2990/*
drh339eb0b2008-03-07 15:34:11 +00002991** Close a file & cleanup AFP specific locking context
2992*/
danielk1977e339d652008-06-28 11:23:00 +00002993static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002994 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00002995 unixFile *pFile = (unixFile*)id;
2996 assert( id!=0 );
2997 afpUnlock(id, NO_LOCK);
2998 unixEnterMutex();
2999 if( pFile->pInode && pFile->pInode->nLock ){
3000 /* If there are outstanding locks, do not actually close the file just
3001 ** yet because that would clear those locks. Instead, add the file
3002 ** descriptor to pInode->aPending. It will be automatically closed when
3003 ** the last lock is cleared.
3004 */
3005 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003006 }
drha8de1e12015-11-30 00:05:39 +00003007 releaseInodeInfo(pFile);
3008 sqlite3_free(pFile->lockingContext);
3009 rc = closeUnixFile(id);
3010 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003011 return rc;
drhbfe66312006-10-03 17:40:40 +00003012}
3013
drhd2cb50b2009-01-09 21:41:17 +00003014#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003015/*
3016** The code above is the AFP lock implementation. The code is specific
3017** to MacOSX and does not work on other unix platforms. No alternative
3018** is available. If you don't compile for a mac, then the "unix-afp"
3019** VFS is not available.
3020**
3021********************* End of the AFP lock implementation **********************
3022******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003023
drh7ed97b92010-01-20 13:07:21 +00003024/******************************************************************************
3025*************************** Begin NFS Locking ********************************/
3026
3027#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3028/*
drh308c2a52010-05-14 11:30:18 +00003029 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003030 ** must be either NO_LOCK or SHARED_LOCK.
3031 **
3032 ** If the locking level of the file descriptor is already at or below
3033 ** the requested locking level, this routine is a no-op.
3034 */
drh308c2a52010-05-14 11:30:18 +00003035static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003036 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003037}
3038
3039#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3040/*
3041** The code above is the NFS lock implementation. The code is specific
3042** to MacOSX and does not work on other unix platforms. No alternative
3043** is available.
3044**
3045********************* End of the NFS lock implementation **********************
3046******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003047
3048/******************************************************************************
3049**************** Non-locking sqlite3_file methods *****************************
3050**
3051** The next division contains implementations for all methods of the
3052** sqlite3_file object other than the locking methods. The locking
3053** methods were defined in divisions above (one locking method per
3054** division). Those methods that are common to all locking modes
3055** are gather together into this division.
3056*/
drhbfe66312006-10-03 17:40:40 +00003057
3058/*
drh734c9862008-11-28 15:37:20 +00003059** Seek to the offset passed as the second argument, then read cnt
3060** bytes into pBuf. Return the number of bytes actually read.
3061**
3062** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3063** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3064** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003065** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003066** See tickets #2741 and #2681.
3067**
3068** To avoid stomping the errno value on a failed read the lastErrno value
3069** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003070*/
drh734c9862008-11-28 15:37:20 +00003071static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3072 int got;
drh58024642011-11-07 18:16:00 +00003073 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003074#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003075 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003076#endif
drh734c9862008-11-28 15:37:20 +00003077 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003078 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003079 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003080 do{
drh734c9862008-11-28 15:37:20 +00003081#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003082 got = osPread(id->h, pBuf, cnt, offset);
3083 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003084#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003085 got = osPread64(id->h, pBuf, cnt, offset);
3086 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003087#else
drh58024642011-11-07 18:16:00 +00003088 newOffset = lseek(id->h, offset, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003089 SimulateIOError( newOffset = -1 );
3090 if( newOffset<0 ){
3091 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003092 return -1;
drh734c9862008-11-28 15:37:20 +00003093 }
drh58024642011-11-07 18:16:00 +00003094 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003095#endif
drh58024642011-11-07 18:16:00 +00003096 if( got==cnt ) break;
3097 if( got<0 ){
3098 if( errno==EINTR ){ got = 1; continue; }
3099 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003100 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003101 break;
3102 }else if( got>0 ){
3103 cnt -= got;
3104 offset += got;
3105 prior += got;
3106 pBuf = (void*)(got + (char*)pBuf);
3107 }
3108 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003109 TIMER_END;
drh58024642011-11-07 18:16:00 +00003110 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3111 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3112 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003113}
3114
3115/*
drh734c9862008-11-28 15:37:20 +00003116** Read data from a file into a buffer. Return SQLITE_OK if all
3117** bytes were read successfully and SQLITE_IOERR if anything goes
3118** wrong.
drh339eb0b2008-03-07 15:34:11 +00003119*/
drh734c9862008-11-28 15:37:20 +00003120static int unixRead(
3121 sqlite3_file *id,
3122 void *pBuf,
3123 int amt,
3124 sqlite3_int64 offset
3125){
dan08da86a2009-08-21 17:18:03 +00003126 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003127 int got;
3128 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003129 assert( offset>=0 );
3130 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003131
dan08da86a2009-08-21 17:18:03 +00003132 /* If this is a database file (not a journal, master-journal or temp
3133 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003134#if 0
dane946c392009-08-22 11:39:46 +00003135 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003136 || offset>=PENDING_BYTE+512
3137 || offset+amt<=PENDING_BYTE
3138 );
dan7c246102010-04-12 19:00:29 +00003139#endif
drh08c6d442009-02-09 17:34:07 +00003140
drh9b4c59f2013-04-15 17:03:42 +00003141#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003142 /* Deal with as much of this read request as possible by transfering
3143 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003144 if( offset<pFile->mmapSize ){
3145 if( offset+amt <= pFile->mmapSize ){
3146 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3147 return SQLITE_OK;
3148 }else{
3149 int nCopy = pFile->mmapSize - offset;
3150 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3151 pBuf = &((u8 *)pBuf)[nCopy];
3152 amt -= nCopy;
3153 offset += nCopy;
3154 }
3155 }
drh6e0b6d52013-04-09 16:19:20 +00003156#endif
danf23da962013-03-23 21:00:41 +00003157
dan08da86a2009-08-21 17:18:03 +00003158 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003159 if( got==amt ){
3160 return SQLITE_OK;
3161 }else if( got<0 ){
3162 /* lastErrno set by seekAndRead */
3163 return SQLITE_IOERR_READ;
3164 }else{
drh4bf66fd2015-02-19 02:43:02 +00003165 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003166 /* Unread parts of the buffer must be zero-filled */
3167 memset(&((char*)pBuf)[got], 0, amt-got);
3168 return SQLITE_IOERR_SHORT_READ;
3169 }
3170}
3171
3172/*
dan47a2b4a2013-04-26 16:09:29 +00003173** Attempt to seek the file-descriptor passed as the first argument to
3174** absolute offset iOff, then attempt to write nBuf bytes of data from
3175** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3176** return the actual number of bytes written (which may be less than
3177** nBuf).
3178*/
3179static int seekAndWriteFd(
3180 int fd, /* File descriptor to write to */
3181 i64 iOff, /* File offset to begin writing at */
3182 const void *pBuf, /* Copy data from this buffer to the file */
3183 int nBuf, /* Size of buffer pBuf in bytes */
3184 int *piErrno /* OUT: Error number if error occurs */
3185){
3186 int rc = 0; /* Value returned by system call */
3187
3188 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003189 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003190 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003191 nBuf &= 0x1ffff;
3192 TIMER_START;
3193
3194#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003195 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003196#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003197 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003198#else
3199 do{
3200 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003201 SimulateIOError( iSeek = -1 );
3202 if( iSeek<0 ){
3203 rc = -1;
3204 break;
dan47a2b4a2013-04-26 16:09:29 +00003205 }
3206 rc = osWrite(fd, pBuf, nBuf);
3207 }while( rc<0 && errno==EINTR );
3208#endif
3209
3210 TIMER_END;
3211 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3212
drhe1818ec2015-12-01 16:21:35 +00003213 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003214 return rc;
3215}
3216
3217
3218/*
drh734c9862008-11-28 15:37:20 +00003219** Seek to the offset in id->offset then read cnt bytes into pBuf.
3220** Return the number of bytes actually read. Update the offset.
3221**
3222** To avoid stomping the errno value on a failed write the lastErrno value
3223** is set before returning.
3224*/
3225static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003226 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003227}
3228
3229
3230/*
3231** Write data from a buffer into a file. Return SQLITE_OK on success
3232** or some other error code on failure.
3233*/
3234static int unixWrite(
3235 sqlite3_file *id,
3236 const void *pBuf,
3237 int amt,
3238 sqlite3_int64 offset
3239){
dan08da86a2009-08-21 17:18:03 +00003240 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003241 int wrote = 0;
3242 assert( id );
3243 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003244
dan08da86a2009-08-21 17:18:03 +00003245 /* If this is a database file (not a journal, master-journal or temp
3246 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003247#if 0
dane946c392009-08-22 11:39:46 +00003248 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003249 || offset>=PENDING_BYTE+512
3250 || offset+amt<=PENDING_BYTE
3251 );
dan7c246102010-04-12 19:00:29 +00003252#endif
drh08c6d442009-02-09 17:34:07 +00003253
drhd3d8c042012-05-29 17:02:40 +00003254#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003255 /* If we are doing a normal write to a database file (as opposed to
3256 ** doing a hot-journal rollback or a write to some file other than a
3257 ** normal database file) then record the fact that the database
3258 ** has changed. If the transaction counter is modified, record that
3259 ** fact too.
3260 */
dan08da86a2009-08-21 17:18:03 +00003261 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003262 pFile->dbUpdate = 1; /* The database has been modified */
3263 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003264 int rc;
drh8f941bc2009-01-14 23:03:40 +00003265 char oldCntr[4];
3266 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003267 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003268 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003269 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003270 pFile->transCntrChng = 1; /* The transaction counter has changed */
3271 }
3272 }
3273 }
3274#endif
3275
danfe33e392015-11-17 20:56:06 +00003276#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003277 /* Deal with as much of this write request as possible by transfering
3278 ** data from the memory mapping using memcpy(). */
3279 if( offset<pFile->mmapSize ){
3280 if( offset+amt <= pFile->mmapSize ){
3281 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3282 return SQLITE_OK;
3283 }else{
3284 int nCopy = pFile->mmapSize - offset;
3285 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3286 pBuf = &((u8 *)pBuf)[nCopy];
3287 amt -= nCopy;
3288 offset += nCopy;
3289 }
3290 }
drh6e0b6d52013-04-09 16:19:20 +00003291#endif
drh02bf8b42015-09-01 23:51:53 +00003292
3293 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003294 amt -= wrote;
3295 offset += wrote;
3296 pBuf = &((char*)pBuf)[wrote];
3297 }
3298 SimulateIOError(( wrote=(-1), amt=1 ));
3299 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003300
drh02bf8b42015-09-01 23:51:53 +00003301 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003302 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003303 /* lastErrno set by seekAndWrite */
3304 return SQLITE_IOERR_WRITE;
3305 }else{
drh4bf66fd2015-02-19 02:43:02 +00003306 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003307 return SQLITE_FULL;
3308 }
3309 }
dan6e09d692010-07-27 18:34:15 +00003310
drh734c9862008-11-28 15:37:20 +00003311 return SQLITE_OK;
3312}
3313
3314#ifdef SQLITE_TEST
3315/*
3316** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003317** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003318*/
3319int sqlite3_sync_count = 0;
3320int sqlite3_fullsync_count = 0;
3321#endif
3322
3323/*
drh89240432009-03-25 01:06:01 +00003324** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003325** Others do no. To be safe, we will stick with the (slightly slower)
3326** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003327** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003328*/
drhf7a4a1b2015-01-10 18:02:45 +00003329#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003330# define fdatasync fsync
3331#endif
3332
3333/*
3334** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3335** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3336** only available on Mac OS X. But that could change.
3337*/
3338#ifdef F_FULLFSYNC
3339# define HAVE_FULLFSYNC 1
3340#else
3341# define HAVE_FULLFSYNC 0
3342#endif
3343
3344
3345/*
3346** The fsync() system call does not work as advertised on many
3347** unix systems. The following procedure is an attempt to make
3348** it work better.
3349**
3350** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3351** for testing when we want to run through the test suite quickly.
3352** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3353** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3354** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003355**
3356** SQLite sets the dataOnly flag if the size of the file is unchanged.
3357** The idea behind dataOnly is that it should only write the file content
3358** to disk, not the inode. We only set dataOnly if the file size is
3359** unchanged since the file size is part of the inode. However,
3360** Ted Ts'o tells us that fdatasync() will also write the inode if the
3361** file size has changed. The only real difference between fdatasync()
3362** and fsync(), Ted tells us, is that fdatasync() will not flush the
3363** inode if the mtime or owner or other inode attributes have changed.
3364** We only care about the file size, not the other file attributes, so
3365** as far as SQLite is concerned, an fdatasync() is always adequate.
3366** So, we always use fdatasync() if it is available, regardless of
3367** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003368*/
3369static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003370 int rc;
drh734c9862008-11-28 15:37:20 +00003371
3372 /* The following "ifdef/elif/else/" block has the same structure as
3373 ** the one below. It is replicated here solely to avoid cluttering
3374 ** up the real code with the UNUSED_PARAMETER() macros.
3375 */
3376#ifdef SQLITE_NO_SYNC
3377 UNUSED_PARAMETER(fd);
3378 UNUSED_PARAMETER(fullSync);
3379 UNUSED_PARAMETER(dataOnly);
3380#elif HAVE_FULLFSYNC
3381 UNUSED_PARAMETER(dataOnly);
3382#else
3383 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003384 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003385#endif
3386
3387 /* Record the number of times that we do a normal fsync() and
3388 ** FULLSYNC. This is used during testing to verify that this procedure
3389 ** gets called with the correct arguments.
3390 */
3391#ifdef SQLITE_TEST
3392 if( fullSync ) sqlite3_fullsync_count++;
3393 sqlite3_sync_count++;
3394#endif
3395
3396 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3397 ** no-op
3398 */
3399#ifdef SQLITE_NO_SYNC
3400 rc = SQLITE_OK;
3401#elif HAVE_FULLFSYNC
3402 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003403 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003404 }else{
3405 rc = 1;
3406 }
3407 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003408 ** It shouldn't be possible for fullfsync to fail on the local
3409 ** file system (on OSX), so failure indicates that FULLFSYNC
3410 ** isn't supported for this file system. So, attempt an fsync
3411 ** and (for now) ignore the overhead of a superfluous fcntl call.
3412 ** It'd be better to detect fullfsync support once and avoid
3413 ** the fcntl call every time sync is called.
3414 */
drh734c9862008-11-28 15:37:20 +00003415 if( rc ) rc = fsync(fd);
3416
drh7ed97b92010-01-20 13:07:21 +00003417#elif defined(__APPLE__)
3418 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3419 ** so currently we default to the macro that redefines fdatasync to fsync
3420 */
3421 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003422#else
drh0b647ff2009-03-21 14:41:04 +00003423 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003424#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003425 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003426 rc = fsync(fd);
3427 }
drh0b647ff2009-03-21 14:41:04 +00003428#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003429#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3430
3431 if( OS_VXWORKS && rc!= -1 ){
3432 rc = 0;
3433 }
chw97185482008-11-17 08:05:31 +00003434 return rc;
drhbfe66312006-10-03 17:40:40 +00003435}
3436
drh734c9862008-11-28 15:37:20 +00003437/*
drh0059eae2011-08-08 23:48:40 +00003438** Open a file descriptor to the directory containing file zFilename.
3439** If successful, *pFd is set to the opened file descriptor and
3440** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3441** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3442** value.
3443**
drh90315a22011-08-10 01:52:12 +00003444** The directory file descriptor is used for only one thing - to
3445** fsync() a directory to make sure file creation and deletion events
3446** are flushed to disk. Such fsyncs are not needed on newer
3447** journaling filesystems, but are required on older filesystems.
3448**
3449** This routine can be overridden using the xSetSysCall interface.
3450** The ability to override this routine was added in support of the
3451** chromium sandbox. Opening a directory is a security risk (we are
3452** told) so making it overrideable allows the chromium sandbox to
3453** replace this routine with a harmless no-op. To make this routine
3454** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3455** *pFd set to a negative number.
3456**
drh0059eae2011-08-08 23:48:40 +00003457** If SQLITE_OK is returned, the caller is responsible for closing
3458** the file descriptor *pFd using close().
3459*/
3460static int openDirectory(const char *zFilename, int *pFd){
3461 int ii;
3462 int fd = -1;
3463 char zDirname[MAX_PATHNAME+1];
3464
3465 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3466 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3467 if( ii>0 ){
3468 zDirname[ii] = '\0';
3469 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3470 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003471 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3472 }
3473 }
3474 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003475 if( fd>=0 ) return SQLITE_OK;
3476 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003477}
3478
3479/*
drh734c9862008-11-28 15:37:20 +00003480** Make sure all writes to a particular file are committed to disk.
3481**
3482** If dataOnly==0 then both the file itself and its metadata (file
3483** size, access time, etc) are synced. If dataOnly!=0 then only the
3484** file data is synced.
3485**
3486** Under Unix, also make sure that the directory entry for the file
3487** has been created by fsync-ing the directory that contains the file.
3488** If we do not do this and we encounter a power failure, the directory
3489** entry for the journal might not exist after we reboot. The next
3490** SQLite to access the file will not know that the journal exists (because
3491** the directory entry for the journal was never created) and the transaction
3492** will not roll back - possibly leading to database corruption.
3493*/
3494static int unixSync(sqlite3_file *id, int flags){
3495 int rc;
3496 unixFile *pFile = (unixFile*)id;
3497
3498 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3499 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3500
3501 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3502 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3503 || (flags&0x0F)==SQLITE_SYNC_FULL
3504 );
3505
3506 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3507 ** line is to test that doing so does not cause any problems.
3508 */
3509 SimulateDiskfullError( return SQLITE_FULL );
3510
3511 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003512 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003513 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3514 SimulateIOError( rc=1 );
3515 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003516 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003517 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003518 }
drh0059eae2011-08-08 23:48:40 +00003519
3520 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003521 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003522 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003523 */
3524 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3525 int dirfd;
3526 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003527 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003528 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003529 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003530 full_fsync(dirfd, 0, 0);
3531 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003532 }else{
3533 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003534 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003535 }
drh0059eae2011-08-08 23:48:40 +00003536 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003537 }
3538 return rc;
3539}
3540
3541/*
3542** Truncate an open file to a specified size
3543*/
3544static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003545 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003546 int rc;
dan6e09d692010-07-27 18:34:15 +00003547 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003548 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003549
3550 /* If the user has configured a chunk-size for this file, truncate the
3551 ** file so that it consists of an integer number of chunks (i.e. the
3552 ** actual file size after the operation may be larger than the requested
3553 ** size).
3554 */
drhb8af4b72012-04-05 20:04:39 +00003555 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003556 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3557 }
3558
dan2ee53412014-09-06 16:49:40 +00003559 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003560 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003561 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003562 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003563 }else{
drhd3d8c042012-05-29 17:02:40 +00003564#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003565 /* If we are doing a normal write to a database file (as opposed to
3566 ** doing a hot-journal rollback or a write to some file other than a
3567 ** normal database file) and we truncate the file to zero length,
3568 ** that effectively updates the change counter. This might happen
3569 ** when restoring a database using the backup API from a zero-length
3570 ** source.
3571 */
dan6e09d692010-07-27 18:34:15 +00003572 if( pFile->inNormalWrite && nByte==0 ){
3573 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003574 }
danf23da962013-03-23 21:00:41 +00003575#endif
danc0003312013-03-22 17:46:11 +00003576
mistachkine98844f2013-08-24 00:59:24 +00003577#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003578 /* If the file was just truncated to a size smaller than the currently
3579 ** mapped region, reduce the effective mapping size as well. SQLite will
3580 ** use read() and write() to access data beyond this point from now on.
3581 */
3582 if( nByte<pFile->mmapSize ){
3583 pFile->mmapSize = nByte;
3584 }
mistachkine98844f2013-08-24 00:59:24 +00003585#endif
drh3313b142009-11-06 04:13:18 +00003586
drh734c9862008-11-28 15:37:20 +00003587 return SQLITE_OK;
3588 }
3589}
3590
3591/*
3592** Determine the current size of a file in bytes
3593*/
3594static int unixFileSize(sqlite3_file *id, i64 *pSize){
3595 int rc;
3596 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003597 assert( id );
3598 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003599 SimulateIOError( rc=1 );
3600 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003601 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003602 return SQLITE_IOERR_FSTAT;
3603 }
3604 *pSize = buf.st_size;
3605
drh8af6c222010-05-14 12:43:01 +00003606 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003607 ** writes a single byte into that file in order to work around a bug
3608 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3609 ** layers, we need to report this file size as zero even though it is
3610 ** really 1. Ticket #3260.
3611 */
3612 if( *pSize==1 ) *pSize = 0;
3613
3614
3615 return SQLITE_OK;
3616}
3617
drhd2cb50b2009-01-09 21:41:17 +00003618#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003619/*
3620** Handler for proxy-locking file-control verbs. Defined below in the
3621** proxying locking division.
3622*/
3623static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003624#endif
drh715ff302008-12-03 22:32:44 +00003625
dan502019c2010-07-28 14:26:17 +00003626/*
3627** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003628** file-control operation. Enlarge the database to nBytes in size
3629** (rounded up to the next chunk-size). If the database is already
3630** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003631*/
3632static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003633 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003634 i64 nSize; /* Required file size */
3635 struct stat buf; /* Used to hold return values of fstat() */
3636
drh4bf66fd2015-02-19 02:43:02 +00003637 if( osFstat(pFile->h, &buf) ){
3638 return SQLITE_IOERR_FSTAT;
3639 }
dan502019c2010-07-28 14:26:17 +00003640
3641 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3642 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003643
dan502019c2010-07-28 14:26:17 +00003644#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003645 /* The code below is handling the return value of osFallocate()
3646 ** correctly. posix_fallocate() is defined to "returns zero on success,
3647 ** or an error number on failure". See the manpage for details. */
3648 int err;
drhff812312011-02-23 13:33:46 +00003649 do{
dan661d71a2011-03-30 19:08:03 +00003650 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3651 }while( err==EINTR );
3652 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003653#else
dan592bf7f2014-12-30 19:58:31 +00003654 /* If the OS does not have posix_fallocate(), fake it. Write a
3655 ** single byte to the last byte in each block that falls entirely
3656 ** within the extended region. Then, if required, a single byte
3657 ** at offset (nSize-1), to set the size of the file correctly.
3658 ** This is a similar technique to that used by glibc on systems
3659 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003660 */
3661 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003662 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003663 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003664
dan502019c2010-07-28 14:26:17 +00003665 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003666 assert( iWrite>=buf.st_size );
3667 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3668 assert( ((iWrite+1)%nBlk)==0 );
3669 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003670 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003671 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003672 }
danef3d66c2015-01-06 21:31:47 +00003673 if( nWrite==0 || (nSize%nBlk) ){
3674 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003675 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003676 }
dan502019c2010-07-28 14:26:17 +00003677#endif
3678 }
3679 }
3680
mistachkine98844f2013-08-24 00:59:24 +00003681#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003682 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003683 int rc;
3684 if( pFile->szChunk<=0 ){
3685 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003686 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003687 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3688 }
3689 }
3690
3691 rc = unixMapfile(pFile, nByte);
3692 return rc;
3693 }
mistachkine98844f2013-08-24 00:59:24 +00003694#endif
danf23da962013-03-23 21:00:41 +00003695
dan502019c2010-07-28 14:26:17 +00003696 return SQLITE_OK;
3697}
danielk1977ad94b582007-08-20 06:44:22 +00003698
danielk1977e3026632004-06-22 11:29:02 +00003699/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003700** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003701** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3702**
3703** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3704*/
3705static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3706 if( *pArg<0 ){
3707 *pArg = (pFile->ctrlFlags & mask)!=0;
3708 }else if( (*pArg)==0 ){
3709 pFile->ctrlFlags &= ~mask;
3710 }else{
3711 pFile->ctrlFlags |= mask;
3712 }
3713}
3714
drh696b33e2012-12-06 19:01:42 +00003715/* Forward declaration */
3716static int unixGetTempname(int nBuf, char *zBuf);
3717
drhf12b3f62011-12-21 14:42:29 +00003718/*
drh9e33c2c2007-08-31 18:34:59 +00003719** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003720*/
drhcc6bb3e2007-08-31 16:11:35 +00003721static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003722 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003723 switch( op ){
drhc435cf72015-03-21 16:36:03 +00003724 case SQLITE_FCNTL_WAL_BLOCK: {
drh62ca61e2015-04-03 20:33:33 +00003725 /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
drhc435cf72015-03-21 16:36:03 +00003726 return SQLITE_OK;
3727 }
drh9e33c2c2007-08-31 18:34:59 +00003728 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003729 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003730 return SQLITE_OK;
3731 }
drh4bf66fd2015-02-19 02:43:02 +00003732 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003733 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003734 return SQLITE_OK;
3735 }
dan6e09d692010-07-27 18:34:15 +00003736 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003737 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003738 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003739 }
drh9ff27ec2010-05-19 19:26:05 +00003740 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003741 int rc;
3742 SimulateIOErrorBenign(1);
3743 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3744 SimulateIOErrorBenign(0);
3745 return rc;
drhf0b190d2011-07-26 16:03:07 +00003746 }
3747 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003748 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3749 return SQLITE_OK;
3750 }
drhcb15f352011-12-23 01:04:17 +00003751 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3752 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003753 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003754 }
drhde60fc22011-12-14 17:53:36 +00003755 case SQLITE_FCNTL_VFSNAME: {
3756 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3757 return SQLITE_OK;
3758 }
drh696b33e2012-12-06 19:01:42 +00003759 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003760 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003761 if( zTFile ){
3762 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3763 *(char**)pArg = zTFile;
3764 }
3765 return SQLITE_OK;
3766 }
drhb959a012013-12-07 12:29:22 +00003767 case SQLITE_FCNTL_HAS_MOVED: {
3768 *(int*)pArg = fileHasMoved(pFile);
3769 return SQLITE_OK;
3770 }
mistachkine98844f2013-08-24 00:59:24 +00003771#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003772 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003773 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003774 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003775 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3776 newLimit = sqlite3GlobalConfig.mxMmap;
3777 }
3778 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003779 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003780 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003781 if( pFile->mmapSize>0 ){
3782 unixUnmapfile(pFile);
3783 rc = unixMapfile(pFile, -1);
3784 }
danbcb8a862013-04-08 15:30:41 +00003785 }
drh34e258c2013-05-23 01:40:53 +00003786 return rc;
danb2d3de32013-03-14 18:34:37 +00003787 }
mistachkine98844f2013-08-24 00:59:24 +00003788#endif
drhd3d8c042012-05-29 17:02:40 +00003789#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003790 /* The pager calls this method to signal that it has done
3791 ** a rollback and that the database is therefore unchanged and
3792 ** it hence it is OK for the transaction change counter to be
3793 ** unchanged.
3794 */
3795 case SQLITE_FCNTL_DB_UNCHANGED: {
3796 ((unixFile*)id)->dbUpdate = 0;
3797 return SQLITE_OK;
3798 }
3799#endif
drhd2cb50b2009-01-09 21:41:17 +00003800#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003801 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3802 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003803 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003804 }
drhd2cb50b2009-01-09 21:41:17 +00003805#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003806 }
drh0b52b7d2011-01-26 19:46:22 +00003807 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003808}
3809
3810/*
danielk1977a3d4c882007-03-23 10:08:38 +00003811** Return the sector size in bytes of the underlying block device for
3812** the specified file. This is almost always 512 bytes, but may be
3813** larger for some devices.
3814**
3815** SQLite code assumes this function cannot fail. It also assumes that
3816** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003817** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003818** same for both.
3819*/
drh537dddf2012-10-26 13:46:24 +00003820#ifndef __QNXNTO__
3821static int unixSectorSize(sqlite3_file *NotUsed){
3822 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003823 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003824}
drh537dddf2012-10-26 13:46:24 +00003825#endif
3826
3827/*
3828** The following version of unixSectorSize() is optimized for QNX.
3829*/
3830#ifdef __QNXNTO__
3831#include <sys/dcmd_blk.h>
3832#include <sys/statvfs.h>
3833static int unixSectorSize(sqlite3_file *id){
3834 unixFile *pFile = (unixFile*)id;
3835 if( pFile->sectorSize == 0 ){
3836 struct statvfs fsInfo;
3837
3838 /* Set defaults for non-supported filesystems */
3839 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3840 pFile->deviceCharacteristics = 0;
3841 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3842 return pFile->sectorSize;
3843 }
3844
3845 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3846 pFile->sectorSize = fsInfo.f_bsize;
3847 pFile->deviceCharacteristics =
3848 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3849 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3850 ** the write succeeds */
3851 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3852 ** so it is ordered */
3853 0;
3854 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3855 pFile->sectorSize = fsInfo.f_bsize;
3856 pFile->deviceCharacteristics =
3857 /* etfs cluster size writes are atomic */
3858 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3859 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3860 ** the write succeeds */
3861 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3862 ** so it is ordered */
3863 0;
3864 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3865 pFile->sectorSize = fsInfo.f_bsize;
3866 pFile->deviceCharacteristics =
3867 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3868 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3869 ** the write succeeds */
3870 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3871 ** so it is ordered */
3872 0;
3873 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3874 pFile->sectorSize = fsInfo.f_bsize;
3875 pFile->deviceCharacteristics =
3876 /* full bitset of atomics from max sector size and smaller */
3877 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3878 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3879 ** so it is ordered */
3880 0;
3881 }else if( strstr(fsInfo.f_basetype, "dos") ){
3882 pFile->sectorSize = fsInfo.f_bsize;
3883 pFile->deviceCharacteristics =
3884 /* full bitset of atomics from max sector size and smaller */
3885 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3886 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3887 ** so it is ordered */
3888 0;
3889 }else{
3890 pFile->deviceCharacteristics =
3891 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3892 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3893 ** the write succeeds */
3894 0;
3895 }
3896 }
3897 /* Last chance verification. If the sector size isn't a multiple of 512
3898 ** then it isn't valid.*/
3899 if( pFile->sectorSize % 512 != 0 ){
3900 pFile->deviceCharacteristics = 0;
3901 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3902 }
3903 return pFile->sectorSize;
3904}
3905#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003906
danielk197790949c22007-08-17 16:50:38 +00003907/*
drhf12b3f62011-12-21 14:42:29 +00003908** Return the device characteristics for the file.
3909**
drhcb15f352011-12-23 01:04:17 +00003910** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003911** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003912** file system does not always provide powersafe overwrites. (In other
3913** words, after a power-loss event, parts of the file that were never
3914** written might end up being altered.) However, non-PSOW behavior is very,
3915** very rare. And asserting PSOW makes a large reduction in the amount
3916** of required I/O for journaling, since a lot of padding is eliminated.
3917** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3918** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003919*/
drhf12b3f62011-12-21 14:42:29 +00003920static int unixDeviceCharacteristics(sqlite3_file *id){
3921 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003922 int rc = 0;
3923#ifdef __QNXNTO__
3924 if( p->sectorSize==0 ) unixSectorSize(id);
3925 rc = p->deviceCharacteristics;
3926#endif
drhcb15f352011-12-23 01:04:17 +00003927 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003928 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003929 }
drh537dddf2012-10-26 13:46:24 +00003930 return rc;
danielk197762079062007-08-15 17:08:46 +00003931}
3932
dan702eec12014-06-23 10:04:58 +00003933#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003934
dan702eec12014-06-23 10:04:58 +00003935/*
3936** Return the system page size.
3937**
3938** This function should not be called directly by other code in this file.
3939** Instead, it should be called via macro osGetpagesize().
3940*/
3941static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003942#if OS_VXWORKS
3943 return 1024;
3944#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003945 return getpagesize();
3946#else
3947 return (int)sysconf(_SC_PAGESIZE);
3948#endif
3949}
3950
3951#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3952
3953#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003954
3955/*
drhd91c68f2010-05-14 14:52:25 +00003956** Object used to represent an shared memory buffer.
3957**
3958** When multiple threads all reference the same wal-index, each thread
3959** has its own unixShm object, but they all point to a single instance
3960** of this unixShmNode object. In other words, each wal-index is opened
3961** only once per process.
3962**
3963** Each unixShmNode object is connected to a single unixInodeInfo object.
3964** We could coalesce this object into unixInodeInfo, but that would mean
3965** every open file that does not use shared memory (in other words, most
3966** open files) would have to carry around this extra information. So
3967** the unixInodeInfo object contains a pointer to this unixShmNode object
3968** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003969**
3970** unixMutexHeld() must be true when creating or destroying
3971** this object or while reading or writing the following fields:
3972**
3973** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003974**
3975** The following fields are read-only after the object is created:
3976**
3977** fid
3978** zFilename
3979**
drhd91c68f2010-05-14 14:52:25 +00003980** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003981** unixMutexHeld() is true when reading or writing any other field
3982** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003983*/
drhd91c68f2010-05-14 14:52:25 +00003984struct unixShmNode {
3985 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003986 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003987 char *zFilename; /* Name of the mmapped file */
3988 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003989 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003990 u16 nRegion; /* Size of array apRegion */
3991 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003992 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003993 int nRef; /* Number of unixShm objects pointing to this */
3994 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003995#ifdef SQLITE_DEBUG
3996 u8 exclMask; /* Mask of exclusive locks held */
3997 u8 sharedMask; /* Mask of shared locks held */
3998 u8 nextShmId; /* Next available unixShm.id value */
3999#endif
4000};
4001
4002/*
drhd9e5c4f2010-05-12 18:01:39 +00004003** Structure used internally by this VFS to record the state of an
4004** open shared memory connection.
4005**
drhd91c68f2010-05-14 14:52:25 +00004006** The following fields are initialized when this object is created and
4007** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004008**
drhd91c68f2010-05-14 14:52:25 +00004009** unixShm.pFile
4010** unixShm.id
4011**
4012** All other fields are read/write. The unixShm.pFile->mutex must be held
4013** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004014*/
4015struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004016 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4017 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004018 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004019 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004020 u16 sharedMask; /* Mask of shared locks held */
4021 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004022};
4023
4024/*
drhd9e5c4f2010-05-12 18:01:39 +00004025** Constants used for locking
4026*/
drhbd9676c2010-06-23 17:58:38 +00004027#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004028#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004029
drhd9e5c4f2010-05-12 18:01:39 +00004030/*
drh73b64e42010-05-30 19:55:15 +00004031** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004032**
4033** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4034** otherwise.
4035*/
4036static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004037 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004038 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004039 int ofst, /* First byte of the locking range */
4040 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004041){
drhbbf76ee2015-03-10 20:22:35 +00004042 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4043 struct flock f; /* The posix advisory locking structure */
4044 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004045
drhd91c68f2010-05-14 14:52:25 +00004046 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004047 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004048 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004049
drh73b64e42010-05-30 19:55:15 +00004050 /* Shared locks never span more than one byte */
4051 assert( n==1 || lockType!=F_RDLCK );
4052
4053 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004054 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004055
drh3cb93392011-03-12 18:10:44 +00004056 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004057 int lkType;
drh3cb93392011-03-12 18:10:44 +00004058 /* Initialize the locking parameters */
4059 memset(&f, 0, sizeof(f));
4060 f.l_type = lockType;
4061 f.l_whence = SEEK_SET;
4062 f.l_start = ofst;
4063 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004064
drhbbf76ee2015-03-10 20:22:35 +00004065 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4066 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004067 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004068 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004069 }
drhd9e5c4f2010-05-12 18:01:39 +00004070
4071 /* Update the global lock state and do debug tracing */
4072#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004073 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004074 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004075 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004076 if( rc==SQLITE_OK ){
4077 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004078 OSTRACE(("unlock %d ok", ofst));
4079 pShmNode->exclMask &= ~mask;
4080 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004081 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004082 OSTRACE(("read-lock %d ok", ofst));
4083 pShmNode->exclMask &= ~mask;
4084 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004085 }else{
4086 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004087 OSTRACE(("write-lock %d ok", ofst));
4088 pShmNode->exclMask |= mask;
4089 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004090 }
4091 }else{
4092 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004093 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004094 }else if( lockType==F_RDLCK ){
4095 OSTRACE(("read-lock failed"));
4096 }else{
4097 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004098 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004099 }
4100 }
drh20e1f082010-05-31 16:10:12 +00004101 OSTRACE((" - afterwards %03x,%03x\n",
4102 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004103 }
drhd9e5c4f2010-05-12 18:01:39 +00004104#endif
4105
4106 return rc;
4107}
4108
dan781e34c2014-03-20 08:59:47 +00004109/*
dan781e34c2014-03-20 08:59:47 +00004110** Return the minimum number of 32KB shm regions that should be mapped at
4111** a time, assuming that each mapping must be an integer multiple of the
4112** current system page-size.
4113**
4114** Usually, this is 1. The exception seems to be systems that are configured
4115** to use 64KB pages - in this case each mapping must cover at least two
4116** shm regions.
4117*/
4118static int unixShmRegionPerMap(void){
4119 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004120 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004121 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4122 if( pgsz<shmsz ) return 1;
4123 return pgsz/shmsz;
4124}
drhd9e5c4f2010-05-12 18:01:39 +00004125
4126/*
drhd91c68f2010-05-14 14:52:25 +00004127** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004128**
4129** This is not a VFS shared-memory method; it is a utility function called
4130** by VFS shared-memory methods.
4131*/
drhd91c68f2010-05-14 14:52:25 +00004132static void unixShmPurge(unixFile *pFd){
4133 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004134 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004135 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004136 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004137 int i;
drhd91c68f2010-05-14 14:52:25 +00004138 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004139 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004140 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004141 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004142 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004143 }else{
4144 sqlite3_free(p->apRegion[i]);
4145 }
dan13a3cb82010-06-11 19:04:21 +00004146 }
dan18801912010-06-14 14:07:50 +00004147 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004148 if( p->h>=0 ){
4149 robust_close(pFd, p->h, __LINE__);
4150 p->h = -1;
4151 }
drhd91c68f2010-05-14 14:52:25 +00004152 p->pInode->pShmNode = 0;
4153 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004154 }
4155}
4156
4157/*
danda9fe0c2010-07-13 18:44:03 +00004158** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004159** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004160**
drh7234c6d2010-06-19 15:10:09 +00004161** The file used to implement shared-memory is in the same directory
4162** as the open database file and has the same name as the open database
4163** file with the "-shm" suffix added. For example, if the database file
4164** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004165** for shared memory will be called "/home/user1/config.db-shm".
4166**
4167** Another approach to is to use files in /dev/shm or /dev/tmp or an
4168** some other tmpfs mount. But if a file in a different directory
4169** from the database file is used, then differing access permissions
4170** or a chroot() might cause two different processes on the same
4171** database to end up using different files for shared memory -
4172** meaning that their memory would not really be shared - resulting
4173** in database corruption. Nevertheless, this tmpfs file usage
4174** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4175** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4176** option results in an incompatible build of SQLite; builds of SQLite
4177** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4178** same database file at the same time, database corruption will likely
4179** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4180** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004181**
4182** When opening a new shared-memory file, if no other instances of that
4183** file are currently open, in this process or in other processes, then
4184** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004185**
4186** If the original database file (pDbFd) is using the "unix-excl" VFS
4187** that means that an exclusive lock is held on the database file and
4188** that no other processes are able to read or write the database. In
4189** that case, we do not really need shared memory. No shared memory
4190** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004191*/
danda9fe0c2010-07-13 18:44:03 +00004192static int unixOpenSharedMemory(unixFile *pDbFd){
4193 struct unixShm *p = 0; /* The connection to be opened */
4194 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4195 int rc; /* Result code */
4196 unixInodeInfo *pInode; /* The inode of fd */
4197 char *zShmFilename; /* Name of the file used for SHM */
4198 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004199
danda9fe0c2010-07-13 18:44:03 +00004200 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004201 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004202 if( p==0 ) return SQLITE_NOMEM;
4203 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004204 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004205
danda9fe0c2010-07-13 18:44:03 +00004206 /* Check to see if a unixShmNode object already exists. Reuse an existing
4207 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004208 */
4209 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004210 pInode = pDbFd->pInode;
4211 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004212 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004213 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004214#ifndef SQLITE_SHM_DIRECTORY
4215 const char *zBasePath = pDbFd->zPath;
4216#endif
danddb0ac42010-07-14 14:48:58 +00004217
4218 /* Call fstat() to figure out the permissions on the database file. If
4219 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004220 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004221 */
drh3cb93392011-03-12 18:10:44 +00004222 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004223 rc = SQLITE_IOERR_FSTAT;
4224 goto shm_open_err;
4225 }
4226
drha4ced192010-07-15 18:32:40 +00004227#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004228 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004229#else
drh4bf66fd2015-02-19 02:43:02 +00004230 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004231#endif
drhf3cdcdc2015-04-29 16:50:28 +00004232 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004233 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004234 rc = SQLITE_NOMEM;
4235 goto shm_open_err;
4236 }
drh9cb5a0d2012-01-05 21:19:54 +00004237 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004238 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004239#ifdef SQLITE_SHM_DIRECTORY
4240 sqlite3_snprintf(nShmFilename, zShmFilename,
4241 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4242 (u32)sStat.st_ino, (u32)sStat.st_dev);
4243#else
drh4bf66fd2015-02-19 02:43:02 +00004244 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004245 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004246#endif
drhd91c68f2010-05-14 14:52:25 +00004247 pShmNode->h = -1;
4248 pDbFd->pInode->pShmNode = pShmNode;
4249 pShmNode->pInode = pDbFd->pInode;
4250 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4251 if( pShmNode->mutex==0 ){
4252 rc = SQLITE_NOMEM;
4253 goto shm_open_err;
4254 }
drhd9e5c4f2010-05-12 18:01:39 +00004255
drh3cb93392011-03-12 18:10:44 +00004256 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004257 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004258 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004259 openFlags = O_RDONLY;
4260 pShmNode->isReadonly = 1;
4261 }
4262 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004263 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004264 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4265 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004266 }
drhac7c3ac2012-02-11 19:23:48 +00004267
4268 /* If this process is running as root, make sure that the SHM file
4269 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004270 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004271 */
drh6226ca22015-11-24 15:06:28 +00004272 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004273
4274 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004275 ** If not, truncate the file to zero length.
4276 */
4277 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004278 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004279 if( robust_ftruncate(pShmNode->h, 0) ){
4280 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004281 }
4282 }
drh66dfec8b2011-06-01 20:01:49 +00004283 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004284 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004285 }
4286 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004287 }
drhd9e5c4f2010-05-12 18:01:39 +00004288 }
4289
drhd91c68f2010-05-14 14:52:25 +00004290 /* Make the new connection a child of the unixShmNode */
4291 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004292#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004293 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004294#endif
drhd91c68f2010-05-14 14:52:25 +00004295 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004296 pDbFd->pShm = p;
4297 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004298
4299 /* The reference count on pShmNode has already been incremented under
4300 ** the cover of the unixEnterMutex() mutex and the pointer from the
4301 ** new (struct unixShm) object to the pShmNode has been set. All that is
4302 ** left to do is to link the new object into the linked list starting
4303 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4304 ** mutex.
4305 */
4306 sqlite3_mutex_enter(pShmNode->mutex);
4307 p->pNext = pShmNode->pFirst;
4308 pShmNode->pFirst = p;
4309 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004310 return SQLITE_OK;
4311
4312 /* Jump here on any error */
4313shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004314 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004315 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004316 unixLeaveMutex();
4317 return rc;
4318}
4319
4320/*
danda9fe0c2010-07-13 18:44:03 +00004321** This function is called to obtain a pointer to region iRegion of the
4322** shared-memory associated with the database file fd. Shared-memory regions
4323** are numbered starting from zero. Each shared-memory region is szRegion
4324** bytes in size.
4325**
4326** If an error occurs, an error code is returned and *pp is set to NULL.
4327**
4328** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4329** region has not been allocated (by any client, including one running in a
4330** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4331** bExtend is non-zero and the requested shared-memory region has not yet
4332** been allocated, it is allocated by this function.
4333**
4334** If the shared-memory region has already been allocated or is allocated by
4335** this call as described above, then it is mapped into this processes
4336** address space (if it is not already), *pp is set to point to the mapped
4337** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004338*/
danda9fe0c2010-07-13 18:44:03 +00004339static int unixShmMap(
4340 sqlite3_file *fd, /* Handle open on database file */
4341 int iRegion, /* Region to retrieve */
4342 int szRegion, /* Size of regions */
4343 int bExtend, /* True to extend file if necessary */
4344 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004345){
danda9fe0c2010-07-13 18:44:03 +00004346 unixFile *pDbFd = (unixFile*)fd;
4347 unixShm *p;
4348 unixShmNode *pShmNode;
4349 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004350 int nShmPerMap = unixShmRegionPerMap();
4351 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004352
danda9fe0c2010-07-13 18:44:03 +00004353 /* If the shared-memory file has not yet been opened, open it now. */
4354 if( pDbFd->pShm==0 ){
4355 rc = unixOpenSharedMemory(pDbFd);
4356 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004357 }
drhd9e5c4f2010-05-12 18:01:39 +00004358
danda9fe0c2010-07-13 18:44:03 +00004359 p = pDbFd->pShm;
4360 pShmNode = p->pShmNode;
4361 sqlite3_mutex_enter(pShmNode->mutex);
4362 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004363 assert( pShmNode->pInode==pDbFd->pInode );
4364 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4365 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004366
dan781e34c2014-03-20 08:59:47 +00004367 /* Minimum number of regions required to be mapped. */
4368 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4369
4370 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004371 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004372 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004373 struct stat sStat; /* Used by fstat() */
4374
4375 pShmNode->szRegion = szRegion;
4376
drh3cb93392011-03-12 18:10:44 +00004377 if( pShmNode->h>=0 ){
4378 /* The requested region is not mapped into this processes address space.
4379 ** Check to see if it has been allocated (i.e. if the wal-index file is
4380 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004381 */
drh3cb93392011-03-12 18:10:44 +00004382 if( osFstat(pShmNode->h, &sStat) ){
4383 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004384 goto shmpage_out;
4385 }
drh3cb93392011-03-12 18:10:44 +00004386
4387 if( sStat.st_size<nByte ){
4388 /* The requested memory region does not exist. If bExtend is set to
4389 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004390 */
dan47a2b4a2013-04-26 16:09:29 +00004391 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004392 goto shmpage_out;
4393 }
dan47a2b4a2013-04-26 16:09:29 +00004394
4395 /* Alternatively, if bExtend is true, extend the file. Do this by
4396 ** writing a single byte to the end of each (OS) page being
4397 ** allocated or extended. Technically, we need only write to the
4398 ** last page in order to extend the file. But writing to all new
4399 ** pages forces the OS to allocate them immediately, which reduces
4400 ** the chances of SIGBUS while accessing the mapped region later on.
4401 */
4402 else{
4403 static const int pgsz = 4096;
4404 int iPg;
4405
4406 /* Write to the last byte of each newly allocated or extended page */
4407 assert( (nByte % pgsz)==0 );
4408 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004409 int x = 0;
4410 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004411 const char *zFile = pShmNode->zFilename;
4412 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4413 goto shmpage_out;
4414 }
4415 }
drh3cb93392011-03-12 18:10:44 +00004416 }
4417 }
danda9fe0c2010-07-13 18:44:03 +00004418 }
4419
4420 /* Map the requested memory region into this processes address space. */
4421 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004422 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004423 );
4424 if( !apNew ){
4425 rc = SQLITE_IOERR_NOMEM;
4426 goto shmpage_out;
4427 }
4428 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004429 while( pShmNode->nRegion<nReqRegion ){
4430 int nMap = szRegion*nShmPerMap;
4431 int i;
drh3cb93392011-03-12 18:10:44 +00004432 void *pMem;
4433 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004434 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004435 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004436 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004437 );
4438 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004439 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004440 goto shmpage_out;
4441 }
4442 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004443 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004444 if( pMem==0 ){
4445 rc = SQLITE_NOMEM;
4446 goto shmpage_out;
4447 }
4448 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004449 }
dan781e34c2014-03-20 08:59:47 +00004450
4451 for(i=0; i<nShmPerMap; i++){
4452 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4453 }
4454 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004455 }
4456 }
4457
4458shmpage_out:
4459 if( pShmNode->nRegion>iRegion ){
4460 *pp = pShmNode->apRegion[iRegion];
4461 }else{
4462 *pp = 0;
4463 }
drh66dfec8b2011-06-01 20:01:49 +00004464 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004465 sqlite3_mutex_leave(pShmNode->mutex);
4466 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004467}
4468
4469/*
drhd9e5c4f2010-05-12 18:01:39 +00004470** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004471**
4472** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4473** different here than in posix. In xShmLock(), one can go from unlocked
4474** to shared and back or from unlocked to exclusive and back. But one may
4475** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004476*/
4477static int unixShmLock(
4478 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004479 int ofst, /* First lock to acquire or release */
4480 int n, /* Number of locks to acquire or release */
4481 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004482){
drh73b64e42010-05-30 19:55:15 +00004483 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4484 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4485 unixShm *pX; /* For looping over all siblings */
4486 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4487 int rc = SQLITE_OK; /* Result code */
4488 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004489
drhd91c68f2010-05-14 14:52:25 +00004490 assert( pShmNode==pDbFd->pInode->pShmNode );
4491 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004492 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004493 assert( n>=1 );
4494 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4495 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4496 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4497 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4498 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004499 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4500 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004501
drhc99597c2010-05-31 01:41:15 +00004502 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004503 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004504 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004505 if( flags & SQLITE_SHM_UNLOCK ){
4506 u16 allMask = 0; /* Mask of locks held by siblings */
4507
4508 /* See if any siblings hold this same lock */
4509 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4510 if( pX==p ) continue;
4511 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4512 allMask |= pX->sharedMask;
4513 }
4514
4515 /* Unlock the system-level locks */
4516 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004517 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004518 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004519 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004520 }
drh73b64e42010-05-30 19:55:15 +00004521
4522 /* Undo the local locks */
4523 if( rc==SQLITE_OK ){
4524 p->exclMask &= ~mask;
4525 p->sharedMask &= ~mask;
4526 }
4527 }else if( flags & SQLITE_SHM_SHARED ){
4528 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4529
4530 /* Find out which shared locks are already held by sibling connections.
4531 ** If any sibling already holds an exclusive lock, go ahead and return
4532 ** SQLITE_BUSY.
4533 */
4534 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004535 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004536 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004537 break;
4538 }
4539 allShared |= pX->sharedMask;
4540 }
4541
4542 /* Get shared locks at the system level, if necessary */
4543 if( rc==SQLITE_OK ){
4544 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004545 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004546 }else{
drh73b64e42010-05-30 19:55:15 +00004547 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004548 }
drhd9e5c4f2010-05-12 18:01:39 +00004549 }
drh73b64e42010-05-30 19:55:15 +00004550
4551 /* Get the local shared locks */
4552 if( rc==SQLITE_OK ){
4553 p->sharedMask |= mask;
4554 }
4555 }else{
4556 /* Make sure no sibling connections hold locks that will block this
4557 ** lock. If any do, return SQLITE_BUSY right away.
4558 */
4559 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004560 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4561 rc = SQLITE_BUSY;
4562 break;
4563 }
4564 }
4565
4566 /* Get the exclusive locks at the system level. Then if successful
4567 ** also mark the local connection as being locked.
4568 */
4569 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004570 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004571 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004572 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004573 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004574 }
drhd9e5c4f2010-05-12 18:01:39 +00004575 }
4576 }
drhd91c68f2010-05-14 14:52:25 +00004577 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004578 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004579 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004580 return rc;
4581}
4582
drh286a2882010-05-20 23:51:06 +00004583/*
4584** Implement a memory barrier or memory fence on shared memory.
4585**
4586** All loads and stores begun before the barrier must complete before
4587** any load or store begun after the barrier.
4588*/
4589static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004590 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004591){
drhff828942010-06-26 21:34:06 +00004592 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004593 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4594 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004595 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004596}
4597
dan18801912010-06-14 14:07:50 +00004598/*
danda9fe0c2010-07-13 18:44:03 +00004599** Close a connection to shared-memory. Delete the underlying
4600** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004601**
4602** If there is no shared memory associated with the connection then this
4603** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004604*/
danda9fe0c2010-07-13 18:44:03 +00004605static int unixShmUnmap(
4606 sqlite3_file *fd, /* The underlying database file */
4607 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004608){
danda9fe0c2010-07-13 18:44:03 +00004609 unixShm *p; /* The connection to be closed */
4610 unixShmNode *pShmNode; /* The underlying shared-memory file */
4611 unixShm **pp; /* For looping over sibling connections */
4612 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004613
danda9fe0c2010-07-13 18:44:03 +00004614 pDbFd = (unixFile*)fd;
4615 p = pDbFd->pShm;
4616 if( p==0 ) return SQLITE_OK;
4617 pShmNode = p->pShmNode;
4618
4619 assert( pShmNode==pDbFd->pInode->pShmNode );
4620 assert( pShmNode->pInode==pDbFd->pInode );
4621
4622 /* Remove connection p from the set of connections associated
4623 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004624 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004625 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4626 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004627
danda9fe0c2010-07-13 18:44:03 +00004628 /* Free the connection p */
4629 sqlite3_free(p);
4630 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004631 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004632
4633 /* If pShmNode->nRef has reached 0, then close the underlying
4634 ** shared-memory file, too */
4635 unixEnterMutex();
4636 assert( pShmNode->nRef>0 );
4637 pShmNode->nRef--;
4638 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004639 if( deleteFlag && pShmNode->h>=0 ){
4640 osUnlink(pShmNode->zFilename);
4641 }
danda9fe0c2010-07-13 18:44:03 +00004642 unixShmPurge(pDbFd);
4643 }
4644 unixLeaveMutex();
4645
4646 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004647}
drh286a2882010-05-20 23:51:06 +00004648
danda9fe0c2010-07-13 18:44:03 +00004649
drhd9e5c4f2010-05-12 18:01:39 +00004650#else
drh6b017cc2010-06-14 18:01:46 +00004651# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004652# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004653# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004654# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004655#endif /* #ifndef SQLITE_OMIT_WAL */
4656
mistachkine98844f2013-08-24 00:59:24 +00004657#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004658/*
danaef49d72013-03-25 16:28:54 +00004659** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004660*/
danf23da962013-03-23 21:00:41 +00004661static void unixUnmapfile(unixFile *pFd){
4662 assert( pFd->nFetchOut==0 );
4663 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004664 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004665 pFd->pMapRegion = 0;
4666 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004667 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004668 }
4669}
dan5d8a1372013-03-19 19:28:06 +00004670
danaef49d72013-03-25 16:28:54 +00004671/*
dane6ecd662013-04-01 17:56:59 +00004672** Attempt to set the size of the memory mapping maintained by file
4673** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4674**
4675** If successful, this function sets the following variables:
4676**
4677** unixFile.pMapRegion
4678** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004679** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004680**
4681** If unsuccessful, an error message is logged via sqlite3_log() and
4682** the three variables above are zeroed. In this case SQLite should
4683** continue accessing the database using the xRead() and xWrite()
4684** methods.
4685*/
4686static void unixRemapfile(
4687 unixFile *pFd, /* File descriptor object */
4688 i64 nNew /* Required mapping size */
4689){
dan4ff7bc42013-04-02 12:04:09 +00004690 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004691 int h = pFd->h; /* File descriptor open on db file */
4692 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004693 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004694 u8 *pNew = 0; /* Location of new mapping */
4695 int flags = PROT_READ; /* Flags to pass to mmap() */
4696
4697 assert( pFd->nFetchOut==0 );
4698 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004699 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004700 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004701 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004702 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004703
danfe33e392015-11-17 20:56:06 +00004704#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004705 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004706#endif
dane6ecd662013-04-01 17:56:59 +00004707
4708 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004709#if HAVE_MREMAP
4710 i64 nReuse = pFd->mmapSize;
4711#else
danbc760632014-03-20 09:42:09 +00004712 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004713 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004714#endif
dane6ecd662013-04-01 17:56:59 +00004715 u8 *pReq = &pOrig[nReuse];
4716
4717 /* Unmap any pages of the existing mapping that cannot be reused. */
4718 if( nReuse!=nOrig ){
4719 osMunmap(pReq, nOrig-nReuse);
4720 }
4721
4722#if HAVE_MREMAP
4723 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004724 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004725#else
4726 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4727 if( pNew!=MAP_FAILED ){
4728 if( pNew!=pReq ){
4729 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004730 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004731 }else{
4732 pNew = pOrig;
4733 }
4734 }
4735#endif
4736
dan48ccef82013-04-02 20:55:01 +00004737 /* The attempt to extend the existing mapping failed. Free it. */
4738 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004739 osMunmap(pOrig, nReuse);
4740 }
4741 }
4742
4743 /* If pNew is still NULL, try to create an entirely new mapping. */
4744 if( pNew==0 ){
4745 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004746 }
4747
dan4ff7bc42013-04-02 12:04:09 +00004748 if( pNew==MAP_FAILED ){
4749 pNew = 0;
4750 nNew = 0;
4751 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4752
4753 /* If the mmap() above failed, assume that all subsequent mmap() calls
4754 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4755 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004756 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004757 }
dane6ecd662013-04-01 17:56:59 +00004758 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004759 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004760}
4761
4762/*
danaef49d72013-03-25 16:28:54 +00004763** Memory map or remap the file opened by file-descriptor pFd (if the file
4764** is already mapped, the existing mapping is replaced by the new). Or, if
4765** there already exists a mapping for this file, and there are still
4766** outstanding xFetch() references to it, this function is a no-op.
4767**
4768** If parameter nByte is non-negative, then it is the requested size of
4769** the mapping to create. Otherwise, if nByte is less than zero, then the
4770** requested size is the size of the file on disk. The actual size of the
4771** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004772** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004773**
4774** SQLITE_OK is returned if no error occurs (even if the mapping is not
4775** recreated as a result of outstanding references) or an SQLite error
4776** code otherwise.
4777*/
danf23da962013-03-23 21:00:41 +00004778static int unixMapfile(unixFile *pFd, i64 nByte){
4779 i64 nMap = nByte;
4780 int rc;
daneb97b292013-03-20 14:26:59 +00004781
danf23da962013-03-23 21:00:41 +00004782 assert( nMap>=0 || pFd->nFetchOut==0 );
4783 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4784
4785 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004786 struct stat statbuf; /* Low-level file information */
4787 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004788 if( rc!=SQLITE_OK ){
4789 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004790 }
drh3044b512014-06-16 16:41:52 +00004791 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004792 }
drh9b4c59f2013-04-15 17:03:42 +00004793 if( nMap>pFd->mmapSizeMax ){
4794 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004795 }
4796
danf23da962013-03-23 21:00:41 +00004797 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004798 if( nMap>0 ){
4799 unixRemapfile(pFd, nMap);
4800 }else{
danb7e3a322013-03-25 20:30:13 +00004801 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004802 }
4803 }
4804
danf23da962013-03-23 21:00:41 +00004805 return SQLITE_OK;
4806}
mistachkine98844f2013-08-24 00:59:24 +00004807#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004808
danaef49d72013-03-25 16:28:54 +00004809/*
4810** If possible, return a pointer to a mapping of file fd starting at offset
4811** iOff. The mapping must be valid for at least nAmt bytes.
4812**
4813** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4814** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4815** Finally, if an error does occur, return an SQLite error code. The final
4816** value of *pp is undefined in this case.
4817**
4818** If this function does return a pointer, the caller must eventually
4819** release the reference by calling unixUnfetch().
4820*/
danf23da962013-03-23 21:00:41 +00004821static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004822#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004823 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004824#endif
danf23da962013-03-23 21:00:41 +00004825 *pp = 0;
4826
drh9b4c59f2013-04-15 17:03:42 +00004827#if SQLITE_MAX_MMAP_SIZE>0
4828 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004829 if( pFd->pMapRegion==0 ){
4830 int rc = unixMapfile(pFd, -1);
4831 if( rc!=SQLITE_OK ) return rc;
4832 }
4833 if( pFd->mmapSize >= iOff+nAmt ){
4834 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4835 pFd->nFetchOut++;
4836 }
4837 }
drh6e0b6d52013-04-09 16:19:20 +00004838#endif
danf23da962013-03-23 21:00:41 +00004839 return SQLITE_OK;
4840}
4841
danaef49d72013-03-25 16:28:54 +00004842/*
dandf737fe2013-03-25 17:00:24 +00004843** If the third argument is non-NULL, then this function releases a
4844** reference obtained by an earlier call to unixFetch(). The second
4845** argument passed to this function must be the same as the corresponding
4846** argument that was passed to the unixFetch() invocation.
4847**
4848** Or, if the third argument is NULL, then this function is being called
4849** to inform the VFS layer that, according to POSIX, any existing mapping
4850** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004851*/
dandf737fe2013-03-25 17:00:24 +00004852static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004853#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004854 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004855 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004856
danaef49d72013-03-25 16:28:54 +00004857 /* If p==0 (unmap the entire file) then there must be no outstanding
4858 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4859 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004860 assert( (p==0)==(pFd->nFetchOut==0) );
4861
dandf737fe2013-03-25 17:00:24 +00004862 /* If p!=0, it must match the iOff value. */
4863 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4864
danf23da962013-03-23 21:00:41 +00004865 if( p ){
4866 pFd->nFetchOut--;
4867 }else{
4868 unixUnmapfile(pFd);
4869 }
4870
4871 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004872#else
4873 UNUSED_PARAMETER(fd);
4874 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004875 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004876#endif
danf23da962013-03-23 21:00:41 +00004877 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004878}
4879
4880/*
drh734c9862008-11-28 15:37:20 +00004881** Here ends the implementation of all sqlite3_file methods.
4882**
4883********************** End sqlite3_file Methods *******************************
4884******************************************************************************/
4885
4886/*
drh6b9d6dd2008-12-03 19:34:47 +00004887** This division contains definitions of sqlite3_io_methods objects that
4888** implement various file locking strategies. It also contains definitions
4889** of "finder" functions. A finder-function is used to locate the appropriate
4890** sqlite3_io_methods object for a particular database file. The pAppData
4891** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4892** the correct finder-function for that VFS.
4893**
4894** Most finder functions return a pointer to a fixed sqlite3_io_methods
4895** object. The only interesting finder-function is autolockIoFinder, which
4896** looks at the filesystem type and tries to guess the best locking
4897** strategy from that.
4898**
peter.d.reid60ec9142014-09-06 16:39:46 +00004899** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004900**
4901** (1) The real finder-function named "FImpt()".
4902**
dane946c392009-08-22 11:39:46 +00004903** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004904**
4905**
4906** A pointer to the F pointer is used as the pAppData value for VFS
4907** objects. We have to do this instead of letting pAppData point
4908** directly at the finder-function since C90 rules prevent a void*
4909** from be cast into a function pointer.
4910**
drh6b9d6dd2008-12-03 19:34:47 +00004911**
drh7708e972008-11-29 00:56:52 +00004912** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004913**
drh7708e972008-11-29 00:56:52 +00004914** * A constant sqlite3_io_methods object call METHOD that has locking
4915** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4916**
4917** * An I/O method finder function called FINDER that returns a pointer
4918** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004919*/
drhe6d41732015-02-21 00:49:00 +00004920#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004921static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004922 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004923 CLOSE, /* xClose */ \
4924 unixRead, /* xRead */ \
4925 unixWrite, /* xWrite */ \
4926 unixTruncate, /* xTruncate */ \
4927 unixSync, /* xSync */ \
4928 unixFileSize, /* xFileSize */ \
4929 LOCK, /* xLock */ \
4930 UNLOCK, /* xUnlock */ \
4931 CKLOCK, /* xCheckReservedLock */ \
4932 unixFileControl, /* xFileControl */ \
4933 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004934 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004935 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004936 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004937 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004938 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004939 unixFetch, /* xFetch */ \
4940 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004941}; \
drh0c2694b2009-09-03 16:23:44 +00004942static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4943 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004944 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004945} \
drh0c2694b2009-09-03 16:23:44 +00004946static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004947 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004948
4949/*
4950** Here are all of the sqlite3_io_methods objects for each of the
4951** locking strategies. Functions that return pointers to these methods
4952** are also created.
4953*/
4954IOMETHODS(
4955 posixIoFinder, /* Finder function name */
4956 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004957 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004958 unixClose, /* xClose method */
4959 unixLock, /* xLock method */
4960 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004961 unixCheckReservedLock, /* xCheckReservedLock method */
4962 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004963)
drh7708e972008-11-29 00:56:52 +00004964IOMETHODS(
4965 nolockIoFinder, /* Finder function name */
4966 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004967 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004968 nolockClose, /* xClose method */
4969 nolockLock, /* xLock method */
4970 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004971 nolockCheckReservedLock, /* xCheckReservedLock method */
4972 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004973)
drh7708e972008-11-29 00:56:52 +00004974IOMETHODS(
4975 dotlockIoFinder, /* Finder function name */
4976 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004977 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004978 dotlockClose, /* xClose method */
4979 dotlockLock, /* xLock method */
4980 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004981 dotlockCheckReservedLock, /* xCheckReservedLock method */
4982 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004983)
drh7708e972008-11-29 00:56:52 +00004984
drhe89b2912015-03-03 20:42:01 +00004985#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004986IOMETHODS(
4987 flockIoFinder, /* Finder function name */
4988 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004989 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004990 flockClose, /* xClose method */
4991 flockLock, /* xLock method */
4992 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004993 flockCheckReservedLock, /* xCheckReservedLock method */
4994 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004995)
drh7708e972008-11-29 00:56:52 +00004996#endif
4997
drh6c7d5c52008-11-21 20:32:33 +00004998#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004999IOMETHODS(
5000 semIoFinder, /* Finder function name */
5001 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005002 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005003 semXClose, /* xClose method */
5004 semXLock, /* xLock method */
5005 semXUnlock, /* xUnlock method */
5006 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005007 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005008)
aswiftaebf4132008-11-21 00:10:35 +00005009#endif
drh7708e972008-11-29 00:56:52 +00005010
drhd2cb50b2009-01-09 21:41:17 +00005011#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005012IOMETHODS(
5013 afpIoFinder, /* Finder function name */
5014 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005015 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005016 afpClose, /* xClose method */
5017 afpLock, /* xLock method */
5018 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005019 afpCheckReservedLock, /* xCheckReservedLock method */
5020 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005021)
drh715ff302008-12-03 22:32:44 +00005022#endif
5023
5024/*
5025** The proxy locking method is a "super-method" in the sense that it
5026** opens secondary file descriptors for the conch and lock files and
5027** it uses proxy, dot-file, AFP, and flock() locking methods on those
5028** secondary files. For this reason, the division that implements
5029** proxy locking is located much further down in the file. But we need
5030** to go ahead and define the sqlite3_io_methods and finder function
5031** for proxy locking here. So we forward declare the I/O methods.
5032*/
drhd2cb50b2009-01-09 21:41:17 +00005033#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005034static int proxyClose(sqlite3_file*);
5035static int proxyLock(sqlite3_file*, int);
5036static int proxyUnlock(sqlite3_file*, int);
5037static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005038IOMETHODS(
5039 proxyIoFinder, /* Finder function name */
5040 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005041 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005042 proxyClose, /* xClose method */
5043 proxyLock, /* xLock method */
5044 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005045 proxyCheckReservedLock, /* xCheckReservedLock method */
5046 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005047)
aswiftaebf4132008-11-21 00:10:35 +00005048#endif
drh7708e972008-11-29 00:56:52 +00005049
drh7ed97b92010-01-20 13:07:21 +00005050/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5051#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5052IOMETHODS(
5053 nfsIoFinder, /* Finder function name */
5054 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005055 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005056 unixClose, /* xClose method */
5057 unixLock, /* xLock method */
5058 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005059 unixCheckReservedLock, /* xCheckReservedLock method */
5060 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005061)
5062#endif
drh7708e972008-11-29 00:56:52 +00005063
drhd2cb50b2009-01-09 21:41:17 +00005064#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005065/*
drh6b9d6dd2008-12-03 19:34:47 +00005066** This "finder" function attempts to determine the best locking strategy
5067** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005068** object that implements that strategy.
5069**
5070** This is for MacOSX only.
5071*/
drh1875f7a2008-12-08 18:19:17 +00005072static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005073 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005074 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005075){
5076 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005077 const char *zFilesystem; /* Filesystem type name */
5078 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005079 } aMap[] = {
5080 { "hfs", &posixIoMethods },
5081 { "ufs", &posixIoMethods },
5082 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005083 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005084 { "webdav", &nolockIoMethods },
5085 { 0, 0 }
5086 };
5087 int i;
5088 struct statfs fsInfo;
5089 struct flock lockInfo;
5090
5091 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005092 /* If filePath==NULL that means we are dealing with a transient file
5093 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005094 return &nolockIoMethods;
5095 }
5096 if( statfs(filePath, &fsInfo) != -1 ){
5097 if( fsInfo.f_flags & MNT_RDONLY ){
5098 return &nolockIoMethods;
5099 }
5100 for(i=0; aMap[i].zFilesystem; i++){
5101 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5102 return aMap[i].pMethods;
5103 }
5104 }
5105 }
5106
5107 /* Default case. Handles, amongst others, "nfs".
5108 ** Test byte-range lock using fcntl(). If the call succeeds,
5109 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005110 */
drh7708e972008-11-29 00:56:52 +00005111 lockInfo.l_len = 1;
5112 lockInfo.l_start = 0;
5113 lockInfo.l_whence = SEEK_SET;
5114 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005115 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005116 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5117 return &nfsIoMethods;
5118 } else {
5119 return &posixIoMethods;
5120 }
drh7708e972008-11-29 00:56:52 +00005121 }else{
5122 return &dotlockIoMethods;
5123 }
5124}
drh0c2694b2009-09-03 16:23:44 +00005125static const sqlite3_io_methods
5126 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005127
drhd2cb50b2009-01-09 21:41:17 +00005128#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005129
drhe89b2912015-03-03 20:42:01 +00005130#if OS_VXWORKS
5131/*
5132** This "finder" function for VxWorks checks to see if posix advisory
5133** locking works. If it does, then that is what is used. If it does not
5134** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005135*/
drhe89b2912015-03-03 20:42:01 +00005136static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005137 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005138 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005139){
5140 struct flock lockInfo;
5141
5142 if( !filePath ){
5143 /* If filePath==NULL that means we are dealing with a transient file
5144 ** that does not need to be locked. */
5145 return &nolockIoMethods;
5146 }
5147
5148 /* Test if fcntl() is supported and use POSIX style locks.
5149 ** Otherwise fall back to the named semaphore method.
5150 */
5151 lockInfo.l_len = 1;
5152 lockInfo.l_start = 0;
5153 lockInfo.l_whence = SEEK_SET;
5154 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005155 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005156 return &posixIoMethods;
5157 }else{
5158 return &semIoMethods;
5159 }
5160}
drh0c2694b2009-09-03 16:23:44 +00005161static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005162 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005163
drhe89b2912015-03-03 20:42:01 +00005164#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005165
drh7708e972008-11-29 00:56:52 +00005166/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005167** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005168*/
drh0c2694b2009-09-03 16:23:44 +00005169typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005170
aswiftaebf4132008-11-21 00:10:35 +00005171
drh734c9862008-11-28 15:37:20 +00005172/****************************************************************************
5173**************************** sqlite3_vfs methods ****************************
5174**
5175** This division contains the implementation of methods on the
5176** sqlite3_vfs object.
5177*/
5178
danielk1977a3d4c882007-03-23 10:08:38 +00005179/*
danielk1977e339d652008-06-28 11:23:00 +00005180** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005181*/
5182static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005183 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005184 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005185 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005186 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005187 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005188){
drh7708e972008-11-29 00:56:52 +00005189 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005190 unixFile *pNew = (unixFile *)pId;
5191 int rc = SQLITE_OK;
5192
drh8af6c222010-05-14 12:43:01 +00005193 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005194
dan00157392010-10-05 11:33:15 +00005195 /* Usually the path zFilename should not be a relative pathname. The
5196 ** exception is when opening the proxy "conch" file in builds that
5197 ** include the special Apple locking styles.
5198 */
dan00157392010-10-05 11:33:15 +00005199#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005200 assert( zFilename==0 || zFilename[0]=='/'
5201 || pVfs->pAppData==(void*)&autolockIoFinder );
5202#else
5203 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005204#endif
dan00157392010-10-05 11:33:15 +00005205
drhb07028f2011-10-14 21:49:18 +00005206 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005207 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005208
drh308c2a52010-05-14 11:30:18 +00005209 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005210 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005211 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005212 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005213 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005214#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005215 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005216#endif
drhc02a43a2012-01-10 23:18:38 +00005217 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5218 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005219 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005220 }
drh503a6862013-03-01 01:07:17 +00005221 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005222 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005223 }
drh339eb0b2008-03-07 15:34:11 +00005224
drh6c7d5c52008-11-21 20:32:33 +00005225#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005226 pNew->pId = vxworksFindFileId(zFilename);
5227 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005228 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005229 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005230 }
5231#endif
5232
drhc02a43a2012-01-10 23:18:38 +00005233 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005234 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005235 }else{
drh0c2694b2009-09-03 16:23:44 +00005236 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005237#if SQLITE_ENABLE_LOCKING_STYLE
5238 /* Cache zFilename in the locking context (AFP and dotlock override) for
5239 ** proxyLock activation is possible (remote proxy is based on db name)
5240 ** zFilename remains valid until file is closed, to support */
5241 pNew->lockingContext = (void*)zFilename;
5242#endif
drhda0e7682008-07-30 15:27:54 +00005243 }
danielk1977e339d652008-06-28 11:23:00 +00005244
drh7ed97b92010-01-20 13:07:21 +00005245 if( pLockingStyle == &posixIoMethods
5246#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5247 || pLockingStyle == &nfsIoMethods
5248#endif
5249 ){
drh7708e972008-11-29 00:56:52 +00005250 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005251 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005252 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005253 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005254 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005255 ** in two scenarios:
5256 **
5257 ** (a) A call to fstat() failed.
5258 ** (b) A malloc failed.
5259 **
5260 ** Scenario (b) may only occur if the process is holding no other
5261 ** file descriptors open on the same file. If there were other file
5262 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005263 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005264 ** handle h - as it is guaranteed that no posix locks will be released
5265 ** by doing so.
5266 **
5267 ** If scenario (a) caused the error then things are not so safe. The
5268 ** implicit assumption here is that if fstat() fails, things are in
5269 ** such bad shape that dropping a lock or two doesn't matter much.
5270 */
drh0e9365c2011-03-02 02:08:13 +00005271 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005272 h = -1;
5273 }
drh7708e972008-11-29 00:56:52 +00005274 unixLeaveMutex();
5275 }
danielk1977e339d652008-06-28 11:23:00 +00005276
drhd2cb50b2009-01-09 21:41:17 +00005277#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005278 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005279 /* AFP locking uses the file path so it needs to be included in
5280 ** the afpLockingContext.
5281 */
5282 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005283 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005284 if( pCtx==0 ){
5285 rc = SQLITE_NOMEM;
5286 }else{
5287 /* NB: zFilename exists and remains valid until the file is closed
5288 ** according to requirement F11141. So we do not need to make a
5289 ** copy of the filename. */
5290 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005291 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005292 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005293 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005294 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005295 if( rc!=SQLITE_OK ){
5296 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005297 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005298 h = -1;
5299 }
drh7708e972008-11-29 00:56:52 +00005300 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005301 }
drh7708e972008-11-29 00:56:52 +00005302 }
5303#endif
danielk1977e339d652008-06-28 11:23:00 +00005304
drh7708e972008-11-29 00:56:52 +00005305 else if( pLockingStyle == &dotlockIoMethods ){
5306 /* Dotfile locking uses the file path so it needs to be included in
5307 ** the dotlockLockingContext
5308 */
5309 char *zLockFile;
5310 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005311 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005312 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005313 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005314 if( zLockFile==0 ){
5315 rc = SQLITE_NOMEM;
5316 }else{
5317 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005318 }
drh7708e972008-11-29 00:56:52 +00005319 pNew->lockingContext = zLockFile;
5320 }
danielk1977e339d652008-06-28 11:23:00 +00005321
drh6c7d5c52008-11-21 20:32:33 +00005322#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005323 else if( pLockingStyle == &semIoMethods ){
5324 /* Named semaphore locking uses the file path so it needs to be
5325 ** included in the semLockingContext
5326 */
5327 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005328 rc = findInodeInfo(pNew, &pNew->pInode);
5329 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5330 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005331 int n;
drh2238dcc2009-08-27 17:56:20 +00005332 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005333 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005334 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005335 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005336 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5337 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005338 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005339 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005340 }
chw97185482008-11-17 08:05:31 +00005341 }
drh7708e972008-11-29 00:56:52 +00005342 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005343 }
drh7708e972008-11-29 00:56:52 +00005344#endif
aswift5b1a2562008-08-22 00:22:35 +00005345
drh4bf66fd2015-02-19 02:43:02 +00005346 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005347#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005348 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005349 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005350 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005351 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005352 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005353 }
chw97185482008-11-17 08:05:31 +00005354#endif
danielk1977e339d652008-06-28 11:23:00 +00005355 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005356 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005357 }else{
drh7708e972008-11-29 00:56:52 +00005358 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005359 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005360 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005361 }
danielk1977e339d652008-06-28 11:23:00 +00005362 return rc;
drh054889e2005-11-30 03:20:31 +00005363}
drh9c06c952005-11-26 00:25:00 +00005364
danielk1977ad94b582007-08-20 06:44:22 +00005365/*
drh8b3cf822010-06-01 21:02:51 +00005366** Return the name of a directory in which to put temporary files.
5367** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005368*/
drh7234c6d2010-06-19 15:10:09 +00005369static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005370 static const char *azDirs[] = {
5371 0,
aswiftaebf4132008-11-21 00:10:35 +00005372 0,
danielk197717b90b52008-06-06 11:11:25 +00005373 "/var/tmp",
5374 "/usr/tmp",
5375 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005376 "."
danielk197717b90b52008-06-06 11:11:25 +00005377 };
drh8b3cf822010-06-01 21:02:51 +00005378 unsigned int i;
5379 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005380 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005381
drhb7e50ad2015-11-28 21:49:53 +00005382 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5383 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005384 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005385 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005386 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005387 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005388 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005389 break;
5390 }
5391 return zDir;
5392}
5393
5394/*
5395** Create a temporary file name in zBuf. zBuf must be allocated
5396** by the calling process and must be big enough to hold at least
5397** pVfs->mxPathname bytes.
5398*/
5399static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005400 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005401 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005402
5403 /* It's odd to simulate an io-error here, but really this is just
5404 ** using the io-error infrastructure to test that SQLite handles this
5405 ** function failing.
5406 */
5407 SimulateIOError( return SQLITE_IOERR );
5408
drh7234c6d2010-06-19 15:10:09 +00005409 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005410 do{
drh970942e2015-11-25 23:13:14 +00005411 u64 r;
5412 sqlite3_randomness(sizeof(r), &r);
5413 assert( nBuf>2 );
5414 zBuf[nBuf-2] = 0;
5415 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5416 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005417 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005418 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005419 return SQLITE_OK;
5420}
5421
drhd2cb50b2009-01-09 21:41:17 +00005422#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005423/*
5424** Routine to transform a unixFile into a proxy-locking unixFile.
5425** Implementation in the proxy-lock division, but used by unixOpen()
5426** if SQLITE_PREFER_PROXY_LOCKING is defined.
5427*/
5428static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005429#endif
drhc66d5b62008-12-03 22:48:32 +00005430
dan08da86a2009-08-21 17:18:03 +00005431/*
5432** Search for an unused file descriptor that was opened on the database
5433** file (not a journal or master-journal file) identified by pathname
5434** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5435** argument to this function.
5436**
5437** Such a file descriptor may exist if a database connection was closed
5438** but the associated file descriptor could not be closed because some
5439** other file descriptor open on the same file is holding a file-lock.
5440** Refer to comments in the unixClose() function and the lengthy comment
5441** describing "Posix Advisory Locking" at the start of this file for
5442** further details. Also, ticket #4018.
5443**
5444** If a suitable file descriptor is found, then it is returned. If no
5445** such file descriptor is located, -1 is returned.
5446*/
dane946c392009-08-22 11:39:46 +00005447static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5448 UnixUnusedFd *pUnused = 0;
5449
5450 /* Do not search for an unused file descriptor on vxworks. Not because
5451 ** vxworks would not benefit from the change (it might, we're not sure),
5452 ** but because no way to test it is currently available. It is better
5453 ** not to risk breaking vxworks support for the sake of such an obscure
5454 ** feature. */
5455#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005456 struct stat sStat; /* Results of stat() call */
5457
5458 /* A stat() call may fail for various reasons. If this happens, it is
5459 ** almost certain that an open() call on the same path will also fail.
5460 ** For this reason, if an error occurs in the stat() call here, it is
5461 ** ignored and -1 is returned. The caller will try to open a new file
5462 ** descriptor on the same path, fail, and return an error to SQLite.
5463 **
5464 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005465 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005466 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005467 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005468
5469 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005470 pInode = inodeList;
5471 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5472 || pInode->fileId.ino!=sStat.st_ino) ){
5473 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005474 }
drh8af6c222010-05-14 12:43:01 +00005475 if( pInode ){
dane946c392009-08-22 11:39:46 +00005476 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005477 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005478 pUnused = *pp;
5479 if( pUnused ){
5480 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005481 }
5482 }
5483 unixLeaveMutex();
5484 }
dane946c392009-08-22 11:39:46 +00005485#endif /* if !OS_VXWORKS */
5486 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005487}
danielk197717b90b52008-06-06 11:11:25 +00005488
5489/*
danddb0ac42010-07-14 14:48:58 +00005490** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005491** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005492** and a value suitable for passing as the third argument to open(2) is
5493** written to *pMode. If an IO error occurs, an SQLite error code is
5494** returned and the value of *pMode is not modified.
5495**
peter.d.reid60ec9142014-09-06 16:39:46 +00005496** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005497** an indication to robust_open() to create the file using
5498** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5499** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005500** this function queries the file-system for the permissions on the
5501** corresponding database file and sets *pMode to this value. Whenever
5502** possible, WAL and journal files are created using the same permissions
5503** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005504**
5505** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5506** original filename is unavailable. But 8_3_NAMES is only used for
5507** FAT filesystems and permissions do not matter there, so just use
5508** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005509*/
5510static int findCreateFileMode(
5511 const char *zPath, /* Path of file (possibly) being created */
5512 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005513 mode_t *pMode, /* OUT: Permissions to open file with */
5514 uid_t *pUid, /* OUT: uid to set on the file */
5515 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005516){
5517 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005518 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005519 *pUid = 0;
5520 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005521 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005522 char zDb[MAX_PATHNAME+1]; /* Database file path */
5523 int nDb; /* Number of valid bytes in zDb */
5524 struct stat sStat; /* Output of stat() on database file */
5525
dana0c989d2010-11-05 18:07:37 +00005526 /* zPath is a path to a WAL or journal file. The following block derives
5527 ** the path to the associated database file from zPath. This block handles
5528 ** the following naming conventions:
5529 **
5530 ** "<path to db>-journal"
5531 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005532 ** "<path to db>-journalNN"
5533 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005534 **
drhd337c5b2011-10-20 18:23:35 +00005535 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005536 ** used by the test_multiplex.c module.
5537 */
5538 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005539#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005540 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005541 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005542#else
5543 while( zPath[nDb]!='-' ){
5544 assert( nDb>0 );
5545 assert( zPath[nDb]!='\n' );
5546 nDb--;
5547 }
5548#endif
danddb0ac42010-07-14 14:48:58 +00005549 memcpy(zDb, zPath, nDb);
5550 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005551
drh58384f12011-07-28 00:14:45 +00005552 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005553 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005554 *pUid = sStat.st_uid;
5555 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005556 }else{
5557 rc = SQLITE_IOERR_FSTAT;
5558 }
5559 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5560 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005561 }
5562 return rc;
5563}
5564
5565/*
danielk1977ad94b582007-08-20 06:44:22 +00005566** Open the file zPath.
5567**
danielk1977b4b47412007-08-17 15:53:36 +00005568** Previously, the SQLite OS layer used three functions in place of this
5569** one:
5570**
5571** sqlite3OsOpenReadWrite();
5572** sqlite3OsOpenReadOnly();
5573** sqlite3OsOpenExclusive();
5574**
5575** These calls correspond to the following combinations of flags:
5576**
5577** ReadWrite() -> (READWRITE | CREATE)
5578** ReadOnly() -> (READONLY)
5579** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5580**
5581** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5582** true, the file was configured to be automatically deleted when the
5583** file handle closed. To achieve the same effect using this new
5584** interface, add the DELETEONCLOSE flag to those specified above for
5585** OpenExclusive().
5586*/
5587static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005588 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5589 const char *zPath, /* Pathname of file to be opened */
5590 sqlite3_file *pFile, /* The file descriptor to be filled in */
5591 int flags, /* Input flags to control the opening */
5592 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005593){
dan08da86a2009-08-21 17:18:03 +00005594 unixFile *p = (unixFile *)pFile;
5595 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005596 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005597 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005598 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005599 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005600 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005601
5602 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5603 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5604 int isCreate = (flags & SQLITE_OPEN_CREATE);
5605 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5606 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005607#if SQLITE_ENABLE_LOCKING_STYLE
5608 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5609#endif
drh3d4435b2011-08-26 20:55:50 +00005610#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5611 struct statfs fsInfo;
5612#endif
danielk1977b4b47412007-08-17 15:53:36 +00005613
danielk1977fee2d252007-08-18 10:59:19 +00005614 /* If creating a master or main-file journal, this function will open
5615 ** a file-descriptor on the directory too. The first time unixSync()
5616 ** is called the directory file descriptor will be fsync()ed and close()d.
5617 */
drh0059eae2011-08-08 23:48:40 +00005618 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005619 eType==SQLITE_OPEN_MASTER_JOURNAL
5620 || eType==SQLITE_OPEN_MAIN_JOURNAL
5621 || eType==SQLITE_OPEN_WAL
5622 ));
danielk1977fee2d252007-08-18 10:59:19 +00005623
danielk197717b90b52008-06-06 11:11:25 +00005624 /* If argument zPath is a NULL pointer, this function is required to open
5625 ** a temporary file. Use this buffer to store the file name in.
5626 */
drhc02a43a2012-01-10 23:18:38 +00005627 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005628 const char *zName = zPath;
5629
danielk1977fee2d252007-08-18 10:59:19 +00005630 /* Check the following statements are true:
5631 **
5632 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5633 ** (b) if CREATE is set, then READWRITE must also be set, and
5634 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005635 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005636 */
danielk1977b4b47412007-08-17 15:53:36 +00005637 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005638 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005639 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005640 assert(isDelete==0 || isCreate);
5641
danddb0ac42010-07-14 14:48:58 +00005642 /* The main DB, main journal, WAL file and master journal are never
5643 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005644 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5645 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5646 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005647 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005648
danielk1977fee2d252007-08-18 10:59:19 +00005649 /* Assert that the upper layer has set one of the "file-type" flags. */
5650 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5651 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5652 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005653 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005654 );
5655
drhb00d8622014-01-01 15:18:36 +00005656 /* Detect a pid change and reset the PRNG. There is a race condition
5657 ** here such that two or more threads all trying to open databases at
5658 ** the same instant might all reset the PRNG. But multiple resets
5659 ** are harmless.
5660 */
drh5ac93652015-03-21 20:59:43 +00005661 if( randomnessPid!=osGetpid(0) ){
5662 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005663 sqlite3_randomness(0,0);
5664 }
5665
dan08da86a2009-08-21 17:18:03 +00005666 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005667
dan08da86a2009-08-21 17:18:03 +00005668 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005669 UnixUnusedFd *pUnused;
5670 pUnused = findReusableFd(zName, flags);
5671 if( pUnused ){
5672 fd = pUnused->fd;
5673 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005674 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005675 if( !pUnused ){
5676 return SQLITE_NOMEM;
5677 }
5678 }
5679 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005680
5681 /* Database filenames are double-zero terminated if they are not
5682 ** URIs with parameters. Hence, they can always be passed into
5683 ** sqlite3_uri_parameter(). */
5684 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5685
dan08da86a2009-08-21 17:18:03 +00005686 }else if( !zName ){
5687 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005688 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005689 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005690 if( rc!=SQLITE_OK ){
5691 return rc;
5692 }
5693 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005694
5695 /* Generated temporary filenames are always double-zero terminated
5696 ** for use by sqlite3_uri_parameter(). */
5697 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005698 }
5699
dan08da86a2009-08-21 17:18:03 +00005700 /* Determine the value of the flags parameter passed to POSIX function
5701 ** open(). These must be calculated even if open() is not called, as
5702 ** they may be stored as part of the file handle and used by the
5703 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005704 if( isReadonly ) openFlags |= O_RDONLY;
5705 if( isReadWrite ) openFlags |= O_RDWR;
5706 if( isCreate ) openFlags |= O_CREAT;
5707 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5708 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005709
danielk1977b4b47412007-08-17 15:53:36 +00005710 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005711 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005712 uid_t uid; /* Userid for the file */
5713 gid_t gid; /* Groupid for the file */
5714 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005715 if( rc!=SQLITE_OK ){
5716 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005717 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005718 return rc;
5719 }
drhad4f1e52011-03-04 15:43:57 +00005720 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005721 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005722 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5723 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005724 /* Failed to open the file for read/write access. Try read-only. */
5725 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005726 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005727 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005728 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005729 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005730 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005731 }
5732 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005733 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005734 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005735 }
drhac7c3ac2012-02-11 19:23:48 +00005736
5737 /* If this process is running as root and if creating a new rollback
5738 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005739 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005740 */
5741 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005742 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005743 }
danielk1977b4b47412007-08-17 15:53:36 +00005744 }
dan08da86a2009-08-21 17:18:03 +00005745 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005746 if( pOutFlags ){
5747 *pOutFlags = flags;
5748 }
5749
dane946c392009-08-22 11:39:46 +00005750 if( p->pUnused ){
5751 p->pUnused->fd = fd;
5752 p->pUnused->flags = flags;
5753 }
5754
danielk1977b4b47412007-08-17 15:53:36 +00005755 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005756#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005757 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005758#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5759 zPath = sqlite3_mprintf("%s", zName);
5760 if( zPath==0 ){
5761 robust_close(p, fd, __LINE__);
5762 return SQLITE_NOMEM;
5763 }
chw97185482008-11-17 08:05:31 +00005764#else
drh036ac7f2011-08-08 23:18:05 +00005765 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005766#endif
danielk1977b4b47412007-08-17 15:53:36 +00005767 }
drh41022642008-11-21 00:24:42 +00005768#if SQLITE_ENABLE_LOCKING_STYLE
5769 else{
dan08da86a2009-08-21 17:18:03 +00005770 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005771 }
5772#endif
5773
drhda0e7682008-07-30 15:27:54 +00005774 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005775
drh7ed97b92010-01-20 13:07:21 +00005776
5777#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005778 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005779 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005780 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005781 return SQLITE_IOERR_ACCESS;
5782 }
5783 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5784 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5785 }
drh4bf66fd2015-02-19 02:43:02 +00005786 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5787 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5788 }
drh7ed97b92010-01-20 13:07:21 +00005789#endif
drhc02a43a2012-01-10 23:18:38 +00005790
5791 /* Set up appropriate ctrlFlags */
5792 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5793 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5794 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5795 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5796 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5797
drh7ed97b92010-01-20 13:07:21 +00005798#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005799#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005800 isAutoProxy = 1;
5801#endif
5802 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005803 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5804 int useProxy = 0;
5805
dan08da86a2009-08-21 17:18:03 +00005806 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5807 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005808 if( envforce!=NULL ){
5809 useProxy = atoi(envforce)>0;
5810 }else{
aswiftaebf4132008-11-21 00:10:35 +00005811 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5812 }
5813 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005814 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005815 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005816 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005817 if( rc!=SQLITE_OK ){
5818 /* Use unixClose to clean up the resources added in fillInUnixFile
5819 ** and clear all the structure's references. Specifically,
5820 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5821 */
5822 unixClose(pFile);
5823 return rc;
5824 }
aswiftaebf4132008-11-21 00:10:35 +00005825 }
dane946c392009-08-22 11:39:46 +00005826 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005827 }
5828 }
5829#endif
5830
drhc02a43a2012-01-10 23:18:38 +00005831 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5832
dane946c392009-08-22 11:39:46 +00005833open_finished:
5834 if( rc!=SQLITE_OK ){
5835 sqlite3_free(p->pUnused);
5836 }
5837 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005838}
5839
dane946c392009-08-22 11:39:46 +00005840
danielk1977b4b47412007-08-17 15:53:36 +00005841/*
danielk1977fee2d252007-08-18 10:59:19 +00005842** Delete the file at zPath. If the dirSync argument is true, fsync()
5843** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005844*/
drh6b9d6dd2008-12-03 19:34:47 +00005845static int unixDelete(
5846 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5847 const char *zPath, /* Name of file to be deleted */
5848 int dirSync /* If true, fsync() directory after deleting file */
5849){
danielk1977fee2d252007-08-18 10:59:19 +00005850 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005851 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005852 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005853 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005854 if( errno==ENOENT
5855#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005856 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005857#endif
5858 ){
dan9fc5b4a2012-11-09 20:17:26 +00005859 rc = SQLITE_IOERR_DELETE_NOENT;
5860 }else{
drhb4308162012-11-09 21:40:02 +00005861 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005862 }
drhb4308162012-11-09 21:40:02 +00005863 return rc;
drh5d4feff2010-07-14 01:45:22 +00005864 }
danielk1977d39fa702008-10-16 13:27:40 +00005865#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005866 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005867 int fd;
drh90315a22011-08-10 01:52:12 +00005868 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005869 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005870#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005871 if( fsync(fd)==-1 )
5872#else
5873 if( fsync(fd) )
5874#endif
5875 {
dane18d4952011-02-21 11:46:24 +00005876 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005877 }
drh0e9365c2011-03-02 02:08:13 +00005878 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005879 }else{
5880 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005881 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005882 }
5883 }
danielk1977d138dd82008-10-15 16:02:48 +00005884#endif
danielk1977fee2d252007-08-18 10:59:19 +00005885 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005886}
5887
danielk197790949c22007-08-17 16:50:38 +00005888/*
mistachkin48864df2013-03-21 21:20:32 +00005889** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005890** test performed depends on the value of flags:
5891**
5892** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5893** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5894** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5895**
5896** Otherwise return 0.
5897*/
danielk1977861f7452008-06-05 11:39:11 +00005898static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005899 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5900 const char *zPath, /* Path of the file to examine */
5901 int flags, /* What do we want to learn about the zPath file? */
5902 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005903){
danielk1977397d65f2008-11-19 11:35:39 +00005904 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005905 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005906 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005907
drhd260b5b2015-11-25 18:03:33 +00005908 /* The spec says there are three possible values for flags. But only
5909 ** two of them are actually used */
5910 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5911
5912 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005913 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005914 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5915 }else{
5916 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005917 }
danielk1977861f7452008-06-05 11:39:11 +00005918 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005919}
5920
danielk1977b4b47412007-08-17 15:53:36 +00005921
5922/*
5923** Turn a relative pathname into a full pathname. The relative path
5924** is stored as a nul-terminated string in the buffer pointed to by
5925** zPath.
5926**
5927** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5928** (in this case, MAX_PATHNAME bytes). The full-path is written to
5929** this buffer before returning.
5930*/
danielk1977adfb9b02007-09-17 07:02:56 +00005931static int unixFullPathname(
5932 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5933 const char *zPath, /* Possibly relative input path */
5934 int nOut, /* Size of output buffer in bytes */
5935 char *zOut /* Output buffer */
5936){
dan245fdc62015-10-31 17:58:33 +00005937 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00005938
5939 /* It's odd to simulate an io-error here, but really this is just
5940 ** using the io-error infrastructure to test that SQLite handles this
5941 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005942 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005943 */
5944 SimulateIOError( return SQLITE_ERROR );
5945
drh153c62c2007-08-24 03:51:33 +00005946 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005947 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005948
dan245fdc62015-10-31 17:58:33 +00005949 /* Attempt to resolve the path as if it were a symbolic link. If it is
5950 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
5951 ** the identified file is not a symbolic link or does not exist, then
5952 ** zPath is copied directly into zOut. Either way, nByte is left set to
5953 ** the size of the string copied into zOut[] in bytes. */
5954 nByte = osReadlink(zPath, zOut, nOut-1);
5955 if( nByte<0 ){
5956 if( errno!=EINVAL && errno!=ENOENT ){
5957 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
5958 }
drhd260b5b2015-11-25 18:03:33 +00005959 sqlite3_snprintf(nOut, zOut, "%s", zPath);
dan245fdc62015-10-31 17:58:33 +00005960 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00005961 }else{
dan245fdc62015-10-31 17:58:33 +00005962 zOut[nByte] = '\0';
5963 }
5964
5965 /* If buffer zOut[] now contains an absolute path there is nothing more
5966 ** to do. If it contains a relative path, do the following:
5967 **
5968 ** * move the relative path string so that it is at the end of th
5969 ** zOut[] buffer.
5970 ** * Call getcwd() to read the path of the current working directory
5971 ** into the start of the zOut[] buffer.
5972 ** * Append a '/' character to the cwd string and move the
5973 ** relative path back within the buffer so that it immediately
5974 ** follows the '/'.
5975 **
5976 ** This code is written so that if the combination of the CWD and relative
5977 ** path are larger than the allocated size of zOut[] the CWD is silently
5978 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
5979 ** file for which this function returns a full path larger than (nOut-8)
5980 ** bytes in size. */
drh025d2f72015-11-30 22:22:23 +00005981 testcase( nByte==nOut-5 );
5982 testcase( nByte==nOut-4 );
5983 if( zOut[0]!='/' && nByte<nOut-4 ){
danielk1977b4b47412007-08-17 15:53:36 +00005984 int nCwd;
dan245fdc62015-10-31 17:58:33 +00005985 int nRem = nOut-nByte-1;
5986 memmove(&zOut[nRem], zOut, nByte+1);
5987 zOut[nRem-1] = '\0';
5988 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005989 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005990 }
dan245fdc62015-10-31 17:58:33 +00005991 nCwd = sqlite3Strlen30(zOut);
5992 assert( nCwd<=nRem-1 );
5993 zOut[nCwd] = '/';
5994 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00005995 }
dan245fdc62015-10-31 17:58:33 +00005996
danielk1977b4b47412007-08-17 15:53:36 +00005997 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005998}
5999
drh0ccebe72005-06-07 22:22:50 +00006000
drh761df872006-12-21 01:29:22 +00006001#ifndef SQLITE_OMIT_LOAD_EXTENSION
6002/*
6003** Interfaces for opening a shared library, finding entry points
6004** within the shared library, and closing the shared library.
6005*/
6006#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006007static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6008 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006009 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6010}
danielk197795c8a542007-09-01 06:51:27 +00006011
6012/*
6013** SQLite calls this function immediately after a call to unixDlSym() or
6014** unixDlOpen() fails (returns a null pointer). If a more detailed error
6015** message is available, it is written to zBufOut. If no error message
6016** is available, zBufOut is left unmodified and SQLite uses a default
6017** error message.
6018*/
danielk1977397d65f2008-11-19 11:35:39 +00006019static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006020 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006021 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006022 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006023 zErr = dlerror();
6024 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006025 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006026 }
drh6c7d5c52008-11-21 20:32:33 +00006027 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006028}
drh1875f7a2008-12-08 18:19:17 +00006029static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6030 /*
6031 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6032 ** cast into a pointer to a function. And yet the library dlsym() routine
6033 ** returns a void* which is really a pointer to a function. So how do we
6034 ** use dlsym() with -pedantic-errors?
6035 **
6036 ** Variable x below is defined to be a pointer to a function taking
6037 ** parameters void* and const char* and returning a pointer to a function.
6038 ** We initialize x by assigning it a pointer to the dlsym() function.
6039 ** (That assignment requires a cast.) Then we call the function that
6040 ** x points to.
6041 **
6042 ** This work-around is unlikely to work correctly on any system where
6043 ** you really cannot cast a function pointer into void*. But then, on the
6044 ** other hand, dlsym() will not work on such a system either, so we have
6045 ** not really lost anything.
6046 */
6047 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006048 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006049 x = (void(*(*)(void*,const char*))(void))dlsym;
6050 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006051}
danielk1977397d65f2008-11-19 11:35:39 +00006052static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6053 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006054 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006055}
danielk1977b4b47412007-08-17 15:53:36 +00006056#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6057 #define unixDlOpen 0
6058 #define unixDlError 0
6059 #define unixDlSym 0
6060 #define unixDlClose 0
6061#endif
6062
6063/*
danielk197790949c22007-08-17 16:50:38 +00006064** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006065*/
danielk1977397d65f2008-11-19 11:35:39 +00006066static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6067 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006068 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006069
drhbbd42a62004-05-22 17:41:58 +00006070 /* We have to initialize zBuf to prevent valgrind from reporting
6071 ** errors. The reports issued by valgrind are incorrect - we would
6072 ** prefer that the randomness be increased by making use of the
6073 ** uninitialized space in zBuf - but valgrind errors tend to worry
6074 ** some users. Rather than argue, it seems easier just to initialize
6075 ** the whole array and silence valgrind, even if that means less randomness
6076 ** in the random seed.
6077 **
6078 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006079 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006080 ** tests repeatable.
6081 */
danielk1977b4b47412007-08-17 15:53:36 +00006082 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006083 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006084#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006085 {
drhb00d8622014-01-01 15:18:36 +00006086 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006087 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006088 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006089 time_t t;
6090 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006091 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006092 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6093 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6094 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006095 }else{
drhc18b4042012-02-10 03:10:27 +00006096 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006097 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006098 }
drhbbd42a62004-05-22 17:41:58 +00006099 }
6100#endif
drh72cbd072008-10-14 17:58:38 +00006101 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006102}
6103
danielk1977b4b47412007-08-17 15:53:36 +00006104
drhbbd42a62004-05-22 17:41:58 +00006105/*
6106** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006107** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006108** The return value is the number of microseconds of sleep actually
6109** requested from the underlying operating system, a number which
6110** might be greater than or equal to the argument, but not less
6111** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006112*/
danielk1977397d65f2008-11-19 11:35:39 +00006113static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006114#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006115 struct timespec sp;
6116
6117 sp.tv_sec = microseconds / 1000000;
6118 sp.tv_nsec = (microseconds % 1000000) * 1000;
6119 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006120 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006121 return microseconds;
6122#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006123 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006124 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006125 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006126#else
danielk1977b4b47412007-08-17 15:53:36 +00006127 int seconds = (microseconds+999999)/1000000;
6128 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006129 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006130 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006131#endif
drh88f474a2006-01-02 20:00:12 +00006132}
6133
6134/*
drh6b9d6dd2008-12-03 19:34:47 +00006135** The following variable, if set to a non-zero value, is interpreted as
6136** the number of seconds since 1970 and is used to set the result of
6137** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006138*/
6139#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006140int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006141#endif
6142
6143/*
drhb7e8ea22010-05-03 14:32:30 +00006144** Find the current time (in Universal Coordinated Time). Write into *piNow
6145** the current time and date as a Julian Day number times 86_400_000. In
6146** other words, write into *piNow the number of milliseconds since the Julian
6147** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6148** proleptic Gregorian calendar.
6149**
drh31702252011-10-12 23:13:43 +00006150** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6151** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006152*/
6153static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6154 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006155 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006156#if defined(NO_GETTOD)
6157 time_t t;
6158 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006159 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006160#elif OS_VXWORKS
6161 struct timespec sNow;
6162 clock_gettime(CLOCK_REALTIME, &sNow);
6163 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6164#else
6165 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006166 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6167 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006168#endif
6169
6170#ifdef SQLITE_TEST
6171 if( sqlite3_current_time ){
6172 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6173 }
6174#endif
6175 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006176 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006177}
6178
drh5337dac2015-11-25 15:15:03 +00006179#if 0 /* Not used */
drhb7e8ea22010-05-03 14:32:30 +00006180/*
drhbbd42a62004-05-22 17:41:58 +00006181** Find the current time (in Universal Coordinated Time). Write the
6182** current time and date as a Julian Day number into *prNow and
6183** return 0. Return 1 if the time and date cannot be found.
6184*/
danielk1977397d65f2008-11-19 11:35:39 +00006185static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006186 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006187 int rc;
drhff828942010-06-26 21:34:06 +00006188 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006189 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006190 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006191 return rc;
drhbbd42a62004-05-22 17:41:58 +00006192}
drh5337dac2015-11-25 15:15:03 +00006193#else
6194# define unixCurrentTime 0
6195#endif
danielk1977b4b47412007-08-17 15:53:36 +00006196
drh5337dac2015-11-25 15:15:03 +00006197#if 0 /* Not used */
drh6b9d6dd2008-12-03 19:34:47 +00006198/*
6199** We added the xGetLastError() method with the intention of providing
6200** better low-level error messages when operating-system problems come up
6201** during SQLite operation. But so far, none of that has been implemented
6202** in the core. So this routine is never called. For now, it is merely
6203** a place-holder.
6204*/
danielk1977397d65f2008-11-19 11:35:39 +00006205static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6206 UNUSED_PARAMETER(NotUsed);
6207 UNUSED_PARAMETER(NotUsed2);
6208 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006209 return 0;
6210}
drh5337dac2015-11-25 15:15:03 +00006211#else
6212# define unixGetLastError 0
6213#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006214
drhf2424c52010-04-26 00:04:55 +00006215
6216/*
drh734c9862008-11-28 15:37:20 +00006217************************ End of sqlite3_vfs methods ***************************
6218******************************************************************************/
6219
drh715ff302008-12-03 22:32:44 +00006220/******************************************************************************
6221************************** Begin Proxy Locking ********************************
6222**
6223** Proxy locking is a "uber-locking-method" in this sense: It uses the
6224** other locking methods on secondary lock files. Proxy locking is a
6225** meta-layer over top of the primitive locking implemented above. For
6226** this reason, the division that implements of proxy locking is deferred
6227** until late in the file (here) after all of the other I/O methods have
6228** been defined - so that the primitive locking methods are available
6229** as services to help with the implementation of proxy locking.
6230**
6231****
6232**
6233** The default locking schemes in SQLite use byte-range locks on the
6234** database file to coordinate safe, concurrent access by multiple readers
6235** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6236** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6237** as POSIX read & write locks over fixed set of locations (via fsctl),
6238** on AFP and SMB only exclusive byte-range locks are available via fsctl
6239** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6240** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6241** address in the shared range is taken for a SHARED lock, the entire
6242** shared range is taken for an EXCLUSIVE lock):
6243**
drhf2f105d2012-08-20 15:53:54 +00006244** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006245** RESERVED_BYTE 0x40000001
6246** SHARED_RANGE 0x40000002 -> 0x40000200
6247**
6248** This works well on the local file system, but shows a nearly 100x
6249** slowdown in read performance on AFP because the AFP client disables
6250** the read cache when byte-range locks are present. Enabling the read
6251** cache exposes a cache coherency problem that is present on all OS X
6252** supported network file systems. NFS and AFP both observe the
6253** close-to-open semantics for ensuring cache coherency
6254** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6255** address the requirements for concurrent database access by multiple
6256** readers and writers
6257** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6258**
6259** To address the performance and cache coherency issues, proxy file locking
6260** changes the way database access is controlled by limiting access to a
6261** single host at a time and moving file locks off of the database file
6262** and onto a proxy file on the local file system.
6263**
6264**
6265** Using proxy locks
6266** -----------------
6267**
6268** C APIs
6269**
drh4bf66fd2015-02-19 02:43:02 +00006270** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006271** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006272** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6273** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006274**
6275**
6276** SQL pragmas
6277**
6278** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6279** PRAGMA [database.]lock_proxy_file
6280**
6281** Specifying ":auto:" means that if there is a conch file with a matching
6282** host ID in it, the proxy path in the conch file will be used, otherwise
6283** a proxy path based on the user's temp dir
6284** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6285** actual proxy file name is generated from the name and path of the
6286** database file. For example:
6287**
6288** For database path "/Users/me/foo.db"
6289** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6290**
6291** Once a lock proxy is configured for a database connection, it can not
6292** be removed, however it may be switched to a different proxy path via
6293** the above APIs (assuming the conch file is not being held by another
6294** connection or process).
6295**
6296**
6297** How proxy locking works
6298** -----------------------
6299**
6300** Proxy file locking relies primarily on two new supporting files:
6301**
6302** * conch file to limit access to the database file to a single host
6303** at a time
6304**
6305** * proxy file to act as a proxy for the advisory locks normally
6306** taken on the database
6307**
6308** The conch file - to use a proxy file, sqlite must first "hold the conch"
6309** by taking an sqlite-style shared lock on the conch file, reading the
6310** contents and comparing the host's unique host ID (see below) and lock
6311** proxy path against the values stored in the conch. The conch file is
6312** stored in the same directory as the database file and the file name
6313** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006314** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006315** host ID and/or proxy path, then the lock is escalated to an exclusive
6316** lock and the conch file contents is updated with the host ID and proxy
6317** path and the lock is downgraded to a shared lock again. If the conch
6318** is held by another process (with a shared lock), the exclusive lock
6319** will fail and SQLITE_BUSY is returned.
6320**
6321** The proxy file - a single-byte file used for all advisory file locks
6322** normally taken on the database file. This allows for safe sharing
6323** of the database file for multiple readers and writers on the same
6324** host (the conch ensures that they all use the same local lock file).
6325**
drh715ff302008-12-03 22:32:44 +00006326** Requesting the lock proxy does not immediately take the conch, it is
6327** only taken when the first request to lock database file is made.
6328** This matches the semantics of the traditional locking behavior, where
6329** opening a connection to a database file does not take a lock on it.
6330** The shared lock and an open file descriptor are maintained until
6331** the connection to the database is closed.
6332**
6333** The proxy file and the lock file are never deleted so they only need
6334** to be created the first time they are used.
6335**
6336** Configuration options
6337** ---------------------
6338**
6339** SQLITE_PREFER_PROXY_LOCKING
6340**
6341** Database files accessed on non-local file systems are
6342** automatically configured for proxy locking, lock files are
6343** named automatically using the same logic as
6344** PRAGMA lock_proxy_file=":auto:"
6345**
6346** SQLITE_PROXY_DEBUG
6347**
6348** Enables the logging of error messages during host id file
6349** retrieval and creation
6350**
drh715ff302008-12-03 22:32:44 +00006351** LOCKPROXYDIR
6352**
6353** Overrides the default directory used for lock proxy files that
6354** are named automatically via the ":auto:" setting
6355**
6356** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6357**
6358** Permissions to use when creating a directory for storing the
6359** lock proxy files, only used when LOCKPROXYDIR is not set.
6360**
6361**
6362** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6363** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6364** force proxy locking to be used for every database file opened, and 0
6365** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006366** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006367** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6368*/
6369
6370/*
6371** Proxy locking is only available on MacOSX
6372*/
drhd2cb50b2009-01-09 21:41:17 +00006373#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006374
drh715ff302008-12-03 22:32:44 +00006375/*
6376** The proxyLockingContext has the path and file structures for the remote
6377** and local proxy files in it
6378*/
6379typedef struct proxyLockingContext proxyLockingContext;
6380struct proxyLockingContext {
6381 unixFile *conchFile; /* Open conch file */
6382 char *conchFilePath; /* Name of the conch file */
6383 unixFile *lockProxy; /* Open proxy lock file */
6384 char *lockProxyPath; /* Name of the proxy lock file */
6385 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006386 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006387 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006388 void *oldLockingContext; /* Original lockingcontext to restore on close */
6389 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6390};
6391
drh7ed97b92010-01-20 13:07:21 +00006392/*
6393** The proxy lock file path for the database at dbPath is written into lPath,
6394** which must point to valid, writable memory large enough for a maxLen length
6395** file path.
drh715ff302008-12-03 22:32:44 +00006396*/
drh715ff302008-12-03 22:32:44 +00006397static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6398 int len;
6399 int dbLen;
6400 int i;
6401
6402#ifdef LOCKPROXYDIR
6403 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6404#else
6405# ifdef _CS_DARWIN_USER_TEMP_DIR
6406 {
drh7ed97b92010-01-20 13:07:21 +00006407 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006408 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006409 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006410 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006411 }
drh7ed97b92010-01-20 13:07:21 +00006412 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006413 }
6414# else
6415 len = strlcpy(lPath, "/tmp/", maxLen);
6416# endif
6417#endif
6418
6419 if( lPath[len-1]!='/' ){
6420 len = strlcat(lPath, "/", maxLen);
6421 }
6422
6423 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006424 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006425 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006426 char c = dbPath[i];
6427 lPath[i+len] = (c=='/')?'_':c;
6428 }
6429 lPath[i+len]='\0';
6430 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006431 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006432 return SQLITE_OK;
6433}
6434
drh7ed97b92010-01-20 13:07:21 +00006435/*
6436 ** Creates the lock file and any missing directories in lockPath
6437 */
6438static int proxyCreateLockPath(const char *lockPath){
6439 int i, len;
6440 char buf[MAXPATHLEN];
6441 int start = 0;
6442
6443 assert(lockPath!=NULL);
6444 /* try to create all the intermediate directories */
6445 len = (int)strlen(lockPath);
6446 buf[0] = lockPath[0];
6447 for( i=1; i<len; i++ ){
6448 if( lockPath[i] == '/' && (i - start > 0) ){
6449 /* only mkdir if leaf dir != "." or "/" or ".." */
6450 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6451 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6452 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006453 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006454 int err=errno;
6455 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006456 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006457 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006458 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006459 return err;
6460 }
6461 }
6462 }
6463 start=i+1;
6464 }
6465 buf[i] = lockPath[i];
6466 }
drh62aaa6c2015-11-21 17:27:42 +00006467 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006468 return 0;
6469}
6470
drh715ff302008-12-03 22:32:44 +00006471/*
6472** Create a new VFS file descriptor (stored in memory obtained from
6473** sqlite3_malloc) and open the file named "path" in the file descriptor.
6474**
6475** The caller is responsible not only for closing the file descriptor
6476** but also for freeing the memory associated with the file descriptor.
6477*/
drh7ed97b92010-01-20 13:07:21 +00006478static int proxyCreateUnixFile(
6479 const char *path, /* path for the new unixFile */
6480 unixFile **ppFile, /* unixFile created and returned by ref */
6481 int islockfile /* if non zero missing dirs will be created */
6482) {
6483 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006484 unixFile *pNew;
6485 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006486 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006487 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006488 int terrno = 0;
6489 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006490
drh7ed97b92010-01-20 13:07:21 +00006491 /* 1. first try to open/create the file
6492 ** 2. if that fails, and this is a lock file (not-conch), try creating
6493 ** the parent directories and then try again.
6494 ** 3. if that fails, try to open the file read-only
6495 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6496 */
6497 pUnused = findReusableFd(path, openFlags);
6498 if( pUnused ){
6499 fd = pUnused->fd;
6500 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006501 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006502 if( !pUnused ){
6503 return SQLITE_NOMEM;
6504 }
6505 }
6506 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006507 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006508 terrno = errno;
6509 if( fd<0 && errno==ENOENT && islockfile ){
6510 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006511 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006512 }
6513 }
6514 }
6515 if( fd<0 ){
6516 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006517 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006518 terrno = errno;
6519 }
6520 if( fd<0 ){
6521 if( islockfile ){
6522 return SQLITE_BUSY;
6523 }
6524 switch (terrno) {
6525 case EACCES:
6526 return SQLITE_PERM;
6527 case EIO:
6528 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6529 default:
drh9978c972010-02-23 17:36:32 +00006530 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006531 }
6532 }
6533
drhf3cdcdc2015-04-29 16:50:28 +00006534 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006535 if( pNew==NULL ){
6536 rc = SQLITE_NOMEM;
6537 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006538 }
6539 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006540 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006541 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006542 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006543 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006544 pUnused->fd = fd;
6545 pUnused->flags = openFlags;
6546 pNew->pUnused = pUnused;
6547
drhc02a43a2012-01-10 23:18:38 +00006548 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006549 if( rc==SQLITE_OK ){
6550 *ppFile = pNew;
6551 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006552 }
drh7ed97b92010-01-20 13:07:21 +00006553end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006554 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006555 sqlite3_free(pNew);
6556 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006557 return rc;
6558}
6559
drh7ed97b92010-01-20 13:07:21 +00006560#ifdef SQLITE_TEST
6561/* simulate multiple hosts by creating unique hostid file paths */
6562int sqlite3_hostid_num = 0;
6563#endif
6564
6565#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6566
drh6bca6512015-04-13 23:05:28 +00006567#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006568/* Not always defined in the headers as it ought to be */
6569extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006570#endif
drh0ab216a2010-07-02 17:10:40 +00006571
drh7ed97b92010-01-20 13:07:21 +00006572/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6573** bytes of writable memory.
6574*/
6575static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006576 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6577 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006578#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006579 {
drh4bf66fd2015-02-19 02:43:02 +00006580 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006581 if( gethostuuid(pHostID, &timeout) ){
6582 int err = errno;
6583 if( pError ){
6584 *pError = err;
6585 }
6586 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006587 }
drh7ed97b92010-01-20 13:07:21 +00006588 }
drh3d4435b2011-08-26 20:55:50 +00006589#else
6590 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006591#endif
drh7ed97b92010-01-20 13:07:21 +00006592#ifdef SQLITE_TEST
6593 /* simulate multiple hosts by creating unique hostid file paths */
6594 if( sqlite3_hostid_num != 0){
6595 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6596 }
6597#endif
6598
6599 return SQLITE_OK;
6600}
6601
6602/* The conch file contains the header, host id and lock file path
6603 */
6604#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6605#define PROXY_HEADERLEN 1 /* conch file header length */
6606#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6607#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6608
6609/*
6610** Takes an open conch file, copies the contents to a new path and then moves
6611** it back. The newly created file's file descriptor is assigned to the
6612** conch file structure and finally the original conch file descriptor is
6613** closed. Returns zero if successful.
6614*/
6615static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6616 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6617 unixFile *conchFile = pCtx->conchFile;
6618 char tPath[MAXPATHLEN];
6619 char buf[PROXY_MAXCONCHLEN];
6620 char *cPath = pCtx->conchFilePath;
6621 size_t readLen = 0;
6622 size_t pathLen = 0;
6623 char errmsg[64] = "";
6624 int fd = -1;
6625 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006626 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006627
6628 /* create a new path by replace the trailing '-conch' with '-break' */
6629 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6630 if( pathLen>MAXPATHLEN || pathLen<6 ||
6631 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006632 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006633 goto end_breaklock;
6634 }
6635 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006636 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006637 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006638 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006639 goto end_breaklock;
6640 }
6641 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006642 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006643 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006644 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006645 goto end_breaklock;
6646 }
drhe562be52011-03-02 18:01:10 +00006647 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006648 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006649 goto end_breaklock;
6650 }
6651 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006652 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006653 goto end_breaklock;
6654 }
6655 rc = 0;
6656 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006657 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006658 conchFile->h = fd;
6659 conchFile->openFlags = O_RDWR | O_CREAT;
6660
6661end_breaklock:
6662 if( rc ){
6663 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006664 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006665 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006666 }
6667 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6668 }
6669 return rc;
6670}
6671
6672/* Take the requested lock on the conch file and break a stale lock if the
6673** host id matches.
6674*/
6675static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6676 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6677 unixFile *conchFile = pCtx->conchFile;
6678 int rc = SQLITE_OK;
6679 int nTries = 0;
6680 struct timespec conchModTime;
6681
drh3d4435b2011-08-26 20:55:50 +00006682 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006683 do {
6684 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6685 nTries ++;
6686 if( rc==SQLITE_BUSY ){
6687 /* If the lock failed (busy):
6688 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6689 * 2nd try: fail if the mod time changed or host id is different, wait
6690 * 10 sec and try again
6691 * 3rd try: break the lock unless the mod time has changed.
6692 */
6693 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006694 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006695 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006696 return SQLITE_IOERR_LOCK;
6697 }
6698
6699 if( nTries==1 ){
6700 conchModTime = buf.st_mtimespec;
6701 usleep(500000); /* wait 0.5 sec and try the lock again*/
6702 continue;
6703 }
6704
6705 assert( nTries>1 );
6706 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6707 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6708 return SQLITE_BUSY;
6709 }
6710
6711 if( nTries==2 ){
6712 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006713 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006714 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006715 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006716 return SQLITE_IOERR_LOCK;
6717 }
6718 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6719 /* don't break the lock if the host id doesn't match */
6720 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6721 return SQLITE_BUSY;
6722 }
6723 }else{
6724 /* don't break the lock on short read or a version mismatch */
6725 return SQLITE_BUSY;
6726 }
6727 usleep(10000000); /* wait 10 sec and try the lock again */
6728 continue;
6729 }
6730
6731 assert( nTries==3 );
6732 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6733 rc = SQLITE_OK;
6734 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006735 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006736 }
6737 if( !rc ){
6738 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6739 }
6740 }
6741 }
6742 } while( rc==SQLITE_BUSY && nTries<3 );
6743
6744 return rc;
6745}
6746
6747/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006748** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6749** lockPath means that the lockPath in the conch file will be used if the
6750** host IDs match, or a new lock path will be generated automatically
6751** and written to the conch file.
6752*/
6753static int proxyTakeConch(unixFile *pFile){
6754 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6755
drh7ed97b92010-01-20 13:07:21 +00006756 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006757 return SQLITE_OK;
6758 }else{
6759 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006760 uuid_t myHostID;
6761 int pError = 0;
6762 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006763 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006764 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006765 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006766 int createConch = 0;
6767 int hostIdMatch = 0;
6768 int readLen = 0;
6769 int tryOldLockPath = 0;
6770 int forceNewLockPath = 0;
6771
drh308c2a52010-05-14 11:30:18 +00006772 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006773 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006774 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006775
drh7ed97b92010-01-20 13:07:21 +00006776 rc = proxyGetHostID(myHostID, &pError);
6777 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006778 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006779 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006780 }
drh7ed97b92010-01-20 13:07:21 +00006781 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006782 if( rc!=SQLITE_OK ){
6783 goto end_takeconch;
6784 }
drh7ed97b92010-01-20 13:07:21 +00006785 /* read the existing conch file */
6786 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6787 if( readLen<0 ){
6788 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006789 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006790 rc = SQLITE_IOERR_READ;
6791 goto end_takeconch;
6792 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6793 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6794 /* a short read or version format mismatch means we need to create a new
6795 ** conch file.
6796 */
6797 createConch = 1;
6798 }
6799 /* if the host id matches and the lock path already exists in the conch
6800 ** we'll try to use the path there, if we can't open that path, we'll
6801 ** retry with a new auto-generated path
6802 */
6803 do { /* in case we need to try again for an :auto: named lock file */
6804
6805 if( !createConch && !forceNewLockPath ){
6806 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6807 PROXY_HOSTIDLEN);
6808 /* if the conch has data compare the contents */
6809 if( !pCtx->lockProxyPath ){
6810 /* for auto-named local lock file, just check the host ID and we'll
6811 ** use the local lock file path that's already in there
6812 */
6813 if( hostIdMatch ){
6814 size_t pathLen = (readLen - PROXY_PATHINDEX);
6815
6816 if( pathLen>=MAXPATHLEN ){
6817 pathLen=MAXPATHLEN-1;
6818 }
6819 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6820 lockPath[pathLen] = 0;
6821 tempLockPath = lockPath;
6822 tryOldLockPath = 1;
6823 /* create a copy of the lock path if the conch is taken */
6824 goto end_takeconch;
6825 }
6826 }else if( hostIdMatch
6827 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6828 readLen-PROXY_PATHINDEX)
6829 ){
6830 /* conch host and lock path match */
6831 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006832 }
drh7ed97b92010-01-20 13:07:21 +00006833 }
6834
6835 /* if the conch isn't writable and doesn't match, we can't take it */
6836 if( (conchFile->openFlags&O_RDWR) == 0 ){
6837 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006838 goto end_takeconch;
6839 }
drh7ed97b92010-01-20 13:07:21 +00006840
6841 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006842 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006843 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6844 tempLockPath = lockPath;
6845 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006846 }
drh7ed97b92010-01-20 13:07:21 +00006847
6848 /* update conch with host and path (this will fail if other process
6849 ** has a shared lock already), if the host id matches, use the big
6850 ** stick.
drh715ff302008-12-03 22:32:44 +00006851 */
drh7ed97b92010-01-20 13:07:21 +00006852 futimes(conchFile->h, NULL);
6853 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006854 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006855 /* We are trying for an exclusive lock but another thread in this
6856 ** same process is still holding a shared lock. */
6857 rc = SQLITE_BUSY;
6858 } else {
6859 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006860 }
drh715ff302008-12-03 22:32:44 +00006861 }else{
drh4bf66fd2015-02-19 02:43:02 +00006862 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006863 }
drh7ed97b92010-01-20 13:07:21 +00006864 if( rc==SQLITE_OK ){
6865 char writeBuffer[PROXY_MAXCONCHLEN];
6866 int writeSize = 0;
6867
6868 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6869 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6870 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006871 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6872 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006873 }else{
6874 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6875 }
6876 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006877 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006878 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6879 fsync(conchFile->h);
6880 /* If we created a new conch file (not just updated the contents of a
6881 ** valid conch file), try to match the permissions of the database
6882 */
6883 if( rc==SQLITE_OK && createConch ){
6884 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006885 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006886 if( err==0 ){
6887 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6888 S_IROTH|S_IWOTH);
6889 /* try to match the database file R/W permissions, ignore failure */
6890#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006891 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006892#else
drhff812312011-02-23 13:33:46 +00006893 do{
drhe562be52011-03-02 18:01:10 +00006894 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006895 }while( rc==(-1) && errno==EINTR );
6896 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006897 int code = errno;
6898 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6899 cmode, code, strerror(code));
6900 } else {
6901 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6902 }
6903 }else{
6904 int code = errno;
6905 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6906 err, code, strerror(code));
6907#endif
6908 }
drh715ff302008-12-03 22:32:44 +00006909 }
6910 }
drh7ed97b92010-01-20 13:07:21 +00006911 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6912
6913 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006914 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006915 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006916 int fd;
drh7ed97b92010-01-20 13:07:21 +00006917 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006918 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006919 }
6920 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006921 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006922 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006923 if( fd>=0 ){
6924 pFile->h = fd;
6925 }else{
drh9978c972010-02-23 17:36:32 +00006926 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006927 during locking */
6928 }
6929 }
6930 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6931 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6932 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6933 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6934 /* we couldn't create the proxy lock file with the old lock file path
6935 ** so try again via auto-naming
6936 */
6937 forceNewLockPath = 1;
6938 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006939 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006940 }
6941 }
6942 if( rc==SQLITE_OK ){
6943 /* Need to make a copy of path if we extracted the value
6944 ** from the conch file or the path was allocated on the stack
6945 */
6946 if( tempLockPath ){
6947 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6948 if( !pCtx->lockProxyPath ){
6949 rc = SQLITE_NOMEM;
6950 }
6951 }
6952 }
6953 if( rc==SQLITE_OK ){
6954 pCtx->conchHeld = 1;
6955
6956 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6957 afpLockingContext *afpCtx;
6958 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6959 afpCtx->dbPath = pCtx->lockProxyPath;
6960 }
6961 } else {
6962 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6963 }
drh308c2a52010-05-14 11:30:18 +00006964 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6965 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006966 return rc;
drh308c2a52010-05-14 11:30:18 +00006967 } while (1); /* in case we need to retry the :auto: lock file -
6968 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006969 }
6970}
6971
6972/*
6973** If pFile holds a lock on a conch file, then release that lock.
6974*/
6975static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006976 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006977 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6978 unixFile *conchFile; /* Name of the conch file */
6979
6980 pCtx = (proxyLockingContext *)pFile->lockingContext;
6981 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006982 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006983 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006984 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006985 if( pCtx->conchHeld>0 ){
6986 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6987 }
drh715ff302008-12-03 22:32:44 +00006988 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006989 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6990 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006991 return rc;
6992}
6993
6994/*
6995** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00006996** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00006997** Make *pConchPath point to the new name. Return SQLITE_OK on success
6998** or SQLITE_NOMEM if unable to obtain memory.
6999**
7000** The caller is responsible for ensuring that the allocated memory
7001** space is eventually freed.
7002**
7003** *pConchPath is set to NULL if a memory allocation error occurs.
7004*/
7005static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7006 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007007 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007008 char *conchPath; /* buffer in which to construct conch name */
7009
7010 /* Allocate space for the conch filename and initialize the name to
7011 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007012 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007013 if( conchPath==0 ){
7014 return SQLITE_NOMEM;
7015 }
7016 memcpy(conchPath, dbPath, len+1);
7017
7018 /* now insert a "." before the last / character */
7019 for( i=(len-1); i>=0; i-- ){
7020 if( conchPath[i]=='/' ){
7021 i++;
7022 break;
7023 }
7024 }
7025 conchPath[i]='.';
7026 while ( i<len ){
7027 conchPath[i+1]=dbPath[i];
7028 i++;
7029 }
7030
7031 /* append the "-conch" suffix to the file */
7032 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007033 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007034
7035 return SQLITE_OK;
7036}
7037
7038
7039/* Takes a fully configured proxy locking-style unix file and switches
7040** the local lock file path
7041*/
7042static int switchLockProxyPath(unixFile *pFile, const char *path) {
7043 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7044 char *oldPath = pCtx->lockProxyPath;
7045 int rc = SQLITE_OK;
7046
drh308c2a52010-05-14 11:30:18 +00007047 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007048 return SQLITE_BUSY;
7049 }
7050
7051 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7052 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7053 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7054 return SQLITE_OK;
7055 }else{
7056 unixFile *lockProxy = pCtx->lockProxy;
7057 pCtx->lockProxy=NULL;
7058 pCtx->conchHeld = 0;
7059 if( lockProxy!=NULL ){
7060 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7061 if( rc ) return rc;
7062 sqlite3_free(lockProxy);
7063 }
7064 sqlite3_free(oldPath);
7065 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7066 }
7067
7068 return rc;
7069}
7070
7071/*
7072** pFile is a file that has been opened by a prior xOpen call. dbPath
7073** is a string buffer at least MAXPATHLEN+1 characters in size.
7074**
7075** This routine find the filename associated with pFile and writes it
7076** int dbPath.
7077*/
7078static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007079#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007080 if( pFile->pMethod == &afpIoMethods ){
7081 /* afp style keeps a reference to the db path in the filePath field
7082 ** of the struct */
drhea678832008-12-10 19:26:22 +00007083 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007084 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7085 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007086 } else
drh715ff302008-12-03 22:32:44 +00007087#endif
7088 if( pFile->pMethod == &dotlockIoMethods ){
7089 /* dot lock style uses the locking context to store the dot lock
7090 ** file path */
7091 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7092 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7093 }else{
7094 /* all other styles use the locking context to store the db file path */
7095 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007096 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007097 }
7098 return SQLITE_OK;
7099}
7100
7101/*
7102** Takes an already filled in unix file and alters it so all file locking
7103** will be performed on the local proxy lock file. The following fields
7104** are preserved in the locking context so that they can be restored and
7105** the unix structure properly cleaned up at close time:
7106** ->lockingContext
7107** ->pMethod
7108*/
7109static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7110 proxyLockingContext *pCtx;
7111 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7112 char *lockPath=NULL;
7113 int rc = SQLITE_OK;
7114
drh308c2a52010-05-14 11:30:18 +00007115 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007116 return SQLITE_BUSY;
7117 }
7118 proxyGetDbPathForUnixFile(pFile, dbPath);
7119 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7120 lockPath=NULL;
7121 }else{
7122 lockPath=(char *)path;
7123 }
7124
drh308c2a52010-05-14 11:30:18 +00007125 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007126 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007127
drhf3cdcdc2015-04-29 16:50:28 +00007128 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007129 if( pCtx==0 ){
7130 return SQLITE_NOMEM;
7131 }
7132 memset(pCtx, 0, sizeof(*pCtx));
7133
7134 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7135 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007136 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7137 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7138 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7139 ** (c) the file system is read-only, then enable no-locking access.
7140 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7141 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7142 */
7143 struct statfs fsInfo;
7144 struct stat conchInfo;
7145 int goLockless = 0;
7146
drh99ab3b12011-03-02 15:09:07 +00007147 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007148 int err = errno;
7149 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7150 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7151 }
7152 }
7153 if( goLockless ){
7154 pCtx->conchHeld = -1; /* read only FS/ lockless */
7155 rc = SQLITE_OK;
7156 }
7157 }
drh715ff302008-12-03 22:32:44 +00007158 }
7159 if( rc==SQLITE_OK && lockPath ){
7160 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7161 }
7162
7163 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007164 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7165 if( pCtx->dbPath==NULL ){
7166 rc = SQLITE_NOMEM;
7167 }
7168 }
7169 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007170 /* all memory is allocated, proxys are created and assigned,
7171 ** switch the locking context and pMethod then return.
7172 */
drh715ff302008-12-03 22:32:44 +00007173 pCtx->oldLockingContext = pFile->lockingContext;
7174 pFile->lockingContext = pCtx;
7175 pCtx->pOldMethod = pFile->pMethod;
7176 pFile->pMethod = &proxyIoMethods;
7177 }else{
7178 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007179 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007180 sqlite3_free(pCtx->conchFile);
7181 }
drhd56b1212010-08-11 06:14:15 +00007182 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007183 sqlite3_free(pCtx->conchFilePath);
7184 sqlite3_free(pCtx);
7185 }
drh308c2a52010-05-14 11:30:18 +00007186 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7187 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007188 return rc;
7189}
7190
7191
7192/*
7193** This routine handles sqlite3_file_control() calls that are specific
7194** to proxy locking.
7195*/
7196static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7197 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007198 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007199 unixFile *pFile = (unixFile*)id;
7200 if( pFile->pMethod == &proxyIoMethods ){
7201 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7202 proxyTakeConch(pFile);
7203 if( pCtx->lockProxyPath ){
7204 *(const char **)pArg = pCtx->lockProxyPath;
7205 }else{
7206 *(const char **)pArg = ":auto: (not held)";
7207 }
7208 } else {
7209 *(const char **)pArg = NULL;
7210 }
7211 return SQLITE_OK;
7212 }
drh4bf66fd2015-02-19 02:43:02 +00007213 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007214 unixFile *pFile = (unixFile*)id;
7215 int rc = SQLITE_OK;
7216 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7217 if( pArg==NULL || (const char *)pArg==0 ){
7218 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007219 /* turn off proxy locking - not supported. If support is added for
7220 ** switching proxy locking mode off then it will need to fail if
7221 ** the journal mode is WAL mode.
7222 */
drh715ff302008-12-03 22:32:44 +00007223 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7224 }else{
7225 /* turn off proxy locking - already off - NOOP */
7226 rc = SQLITE_OK;
7227 }
7228 }else{
7229 const char *proxyPath = (const char *)pArg;
7230 if( isProxyStyle ){
7231 proxyLockingContext *pCtx =
7232 (proxyLockingContext*)pFile->lockingContext;
7233 if( !strcmp(pArg, ":auto:")
7234 || (pCtx->lockProxyPath &&
7235 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7236 ){
7237 rc = SQLITE_OK;
7238 }else{
7239 rc = switchLockProxyPath(pFile, proxyPath);
7240 }
7241 }else{
7242 /* turn on proxy file locking */
7243 rc = proxyTransformUnixFile(pFile, proxyPath);
7244 }
7245 }
7246 return rc;
7247 }
7248 default: {
7249 assert( 0 ); /* The call assures that only valid opcodes are sent */
7250 }
7251 }
7252 /*NOTREACHED*/
7253 return SQLITE_ERROR;
7254}
7255
7256/*
7257** Within this division (the proxying locking implementation) the procedures
7258** above this point are all utilities. The lock-related methods of the
7259** proxy-locking sqlite3_io_method object follow.
7260*/
7261
7262
7263/*
7264** This routine checks if there is a RESERVED lock held on the specified
7265** file by this or any other process. If such a lock is held, set *pResOut
7266** to a non-zero value otherwise *pResOut is set to zero. The return value
7267** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7268*/
7269static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7270 unixFile *pFile = (unixFile*)id;
7271 int rc = proxyTakeConch(pFile);
7272 if( rc==SQLITE_OK ){
7273 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007274 if( pCtx->conchHeld>0 ){
7275 unixFile *proxy = pCtx->lockProxy;
7276 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7277 }else{ /* conchHeld < 0 is lockless */
7278 pResOut=0;
7279 }
drh715ff302008-12-03 22:32:44 +00007280 }
7281 return rc;
7282}
7283
7284/*
drh308c2a52010-05-14 11:30:18 +00007285** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007286** of the following:
7287**
7288** (1) SHARED_LOCK
7289** (2) RESERVED_LOCK
7290** (3) PENDING_LOCK
7291** (4) EXCLUSIVE_LOCK
7292**
7293** Sometimes when requesting one lock state, additional lock states
7294** are inserted in between. The locking might fail on one of the later
7295** transitions leaving the lock state different from what it started but
7296** still short of its goal. The following chart shows the allowed
7297** transitions and the inserted intermediate states:
7298**
7299** UNLOCKED -> SHARED
7300** SHARED -> RESERVED
7301** SHARED -> (PENDING) -> EXCLUSIVE
7302** RESERVED -> (PENDING) -> EXCLUSIVE
7303** PENDING -> EXCLUSIVE
7304**
7305** This routine will only increase a lock. Use the sqlite3OsUnlock()
7306** routine to lower a locking level.
7307*/
drh308c2a52010-05-14 11:30:18 +00007308static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007309 unixFile *pFile = (unixFile*)id;
7310 int rc = proxyTakeConch(pFile);
7311 if( rc==SQLITE_OK ){
7312 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007313 if( pCtx->conchHeld>0 ){
7314 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007315 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7316 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007317 }else{
7318 /* conchHeld < 0 is lockless */
7319 }
drh715ff302008-12-03 22:32:44 +00007320 }
7321 return rc;
7322}
7323
7324
7325/*
drh308c2a52010-05-14 11:30:18 +00007326** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007327** must be either NO_LOCK or SHARED_LOCK.
7328**
7329** If the locking level of the file descriptor is already at or below
7330** the requested locking level, this routine is a no-op.
7331*/
drh308c2a52010-05-14 11:30:18 +00007332static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007333 unixFile *pFile = (unixFile*)id;
7334 int rc = proxyTakeConch(pFile);
7335 if( rc==SQLITE_OK ){
7336 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007337 if( pCtx->conchHeld>0 ){
7338 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007339 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7340 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007341 }else{
7342 /* conchHeld < 0 is lockless */
7343 }
drh715ff302008-12-03 22:32:44 +00007344 }
7345 return rc;
7346}
7347
7348/*
7349** Close a file that uses proxy locks.
7350*/
7351static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007352 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007353 unixFile *pFile = (unixFile*)id;
7354 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7355 unixFile *lockProxy = pCtx->lockProxy;
7356 unixFile *conchFile = pCtx->conchFile;
7357 int rc = SQLITE_OK;
7358
7359 if( lockProxy ){
7360 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7361 if( rc ) return rc;
7362 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7363 if( rc ) return rc;
7364 sqlite3_free(lockProxy);
7365 pCtx->lockProxy = 0;
7366 }
7367 if( conchFile ){
7368 if( pCtx->conchHeld ){
7369 rc = proxyReleaseConch(pFile);
7370 if( rc ) return rc;
7371 }
7372 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7373 if( rc ) return rc;
7374 sqlite3_free(conchFile);
7375 }
drhd56b1212010-08-11 06:14:15 +00007376 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007377 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007378 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007379 /* restore the original locking context and pMethod then close it */
7380 pFile->lockingContext = pCtx->oldLockingContext;
7381 pFile->pMethod = pCtx->pOldMethod;
7382 sqlite3_free(pCtx);
7383 return pFile->pMethod->xClose(id);
7384 }
7385 return SQLITE_OK;
7386}
7387
7388
7389
drhd2cb50b2009-01-09 21:41:17 +00007390#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007391/*
7392** The proxy locking style is intended for use with AFP filesystems.
7393** And since AFP is only supported on MacOSX, the proxy locking is also
7394** restricted to MacOSX.
7395**
7396**
7397******************* End of the proxy lock implementation **********************
7398******************************************************************************/
7399
drh734c9862008-11-28 15:37:20 +00007400/*
danielk1977e339d652008-06-28 11:23:00 +00007401** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007402**
7403** This routine registers all VFS implementations for unix-like operating
7404** systems. This routine, and the sqlite3_os_end() routine that follows,
7405** should be the only routines in this file that are visible from other
7406** files.
drh6b9d6dd2008-12-03 19:34:47 +00007407**
7408** This routine is called once during SQLite initialization and by a
7409** single thread. The memory allocation and mutex subsystems have not
7410** necessarily been initialized when this routine is called, and so they
7411** should not be used.
drh153c62c2007-08-24 03:51:33 +00007412*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007413int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007414 /*
7415 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007416 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7417 ** to the "finder" function. (pAppData is a pointer to a pointer because
7418 ** silly C90 rules prohibit a void* from being cast to a function pointer
7419 ** and so we have to go through the intermediate pointer to avoid problems
7420 ** when compiling with -pedantic-errors on GCC.)
7421 **
7422 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007423 ** finder-function. The finder-function returns a pointer to the
7424 ** sqlite_io_methods object that implements the desired locking
7425 ** behaviors. See the division above that contains the IOMETHODS
7426 ** macro for addition information on finder-functions.
7427 **
7428 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7429 ** object. But the "autolockIoFinder" available on MacOSX does a little
7430 ** more than that; it looks at the filesystem type that hosts the
7431 ** database file and tries to choose an locking method appropriate for
7432 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007433 */
drh7708e972008-11-29 00:56:52 +00007434 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007435 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007436 sizeof(unixFile), /* szOsFile */ \
7437 MAX_PATHNAME, /* mxPathname */ \
7438 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007439 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007440 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007441 unixOpen, /* xOpen */ \
7442 unixDelete, /* xDelete */ \
7443 unixAccess, /* xAccess */ \
7444 unixFullPathname, /* xFullPathname */ \
7445 unixDlOpen, /* xDlOpen */ \
7446 unixDlError, /* xDlError */ \
7447 unixDlSym, /* xDlSym */ \
7448 unixDlClose, /* xDlClose */ \
7449 unixRandomness, /* xRandomness */ \
7450 unixSleep, /* xSleep */ \
7451 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007452 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007453 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007454 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007455 unixGetSystemCall, /* xGetSystemCall */ \
7456 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007457 }
7458
drh6b9d6dd2008-12-03 19:34:47 +00007459 /*
7460 ** All default VFSes for unix are contained in the following array.
7461 **
7462 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7463 ** by the SQLite core when the VFS is registered. So the following
7464 ** array cannot be const.
7465 */
danielk1977e339d652008-06-28 11:23:00 +00007466 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007467#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007468 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007469#elif OS_VXWORKS
7470 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007471#else
7472 UNIXVFS("unix", posixIoFinder ),
7473#endif
7474 UNIXVFS("unix-none", nolockIoFinder ),
7475 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007476 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007477#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007478 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007479#endif
drhe89b2912015-03-03 20:42:01 +00007480#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007481 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007482#endif
drhe89b2912015-03-03 20:42:01 +00007483#if SQLITE_ENABLE_LOCKING_STYLE
7484 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007485#endif
drhd2cb50b2009-01-09 21:41:17 +00007486#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007487 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007488 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007489 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007490#endif
drh153c62c2007-08-24 03:51:33 +00007491 };
drh6b9d6dd2008-12-03 19:34:47 +00007492 unsigned int i; /* Loop counter */
7493
drh2aa5a002011-04-13 13:42:25 +00007494 /* Double-check that the aSyscall[] array has been constructed
7495 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh6226ca22015-11-24 15:06:28 +00007496 assert( ArraySize(aSyscall)==27 );
drh2aa5a002011-04-13 13:42:25 +00007497
drh6b9d6dd2008-12-03 19:34:47 +00007498 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007499 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007500 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007501 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007502 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007503}
danielk1977e339d652008-06-28 11:23:00 +00007504
7505/*
drh6b9d6dd2008-12-03 19:34:47 +00007506** Shutdown the operating system interface.
7507**
7508** Some operating systems might need to do some cleanup in this routine,
7509** to release dynamically allocated objects. But not on unix.
7510** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007511*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007512int sqlite3_os_end(void){
7513 return SQLITE_OK;
7514}
drhdce8bdb2007-08-16 13:01:44 +00007515
danielk197729bafea2008-06-26 10:41:19 +00007516#endif /* SQLITE_OS_UNIX */