blob: 6e2429880b48fefc2a5dcc51b5da4a59e8a4cb17 [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
drh91be7dc2014-08-11 13:53:30 +000088#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +000089# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +000090# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +000091# include <semaphore.h>
92# include <limits.h>
93# else
drh9b35ea62008-11-29 02:20:26 +000094# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +000095# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +000096# endif
drhbfe66312006-10-03 17:40:40 +000097#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000098
drhf8b4d8c2010-03-05 13:53:22 +000099#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000100# include <sys/mount.h>
101#endif
102
drhdbe4b882011-06-20 18:00:17 +0000103#ifdef HAVE_UTIME
104# include <utime.h>
105#endif
106
drh9cbe6352005-11-29 03:13:21 +0000107/*
drh7ed97b92010-01-20 13:07:21 +0000108** Allowed values of unixFile.fsFlags
109*/
110#define SQLITE_FSFLAGS_IS_MSDOS 0x1
111
112/*
drhf1a221e2006-01-15 17:27:17 +0000113** If we are to be thread-safe, include the pthreads header and define
114** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000115*/
drhd677b3d2007-08-20 22:48:41 +0000116#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000117# include <pthread.h>
118# define SQLITE_UNIX_THREADS 1
119#endif
120
121/*
122** Default permissions when creating a new file
123*/
124#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
125# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
126#endif
127
danielk1977b4b47412007-08-17 15:53:36 +0000128/*
drh5adc60b2012-04-14 13:25:11 +0000129** Default permissions when creating auto proxy dir
130*/
aswiftaebf4132008-11-21 00:10:35 +0000131#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
132# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
133#endif
134
135/*
danielk1977b4b47412007-08-17 15:53:36 +0000136** Maximum supported path-length.
137*/
138#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000139
drh734c9862008-11-28 15:37:20 +0000140/*
drh734c9862008-11-28 15:37:20 +0000141** Only set the lastErrno if the error code is a real error and not
142** a normal expected return code of SQLITE_BUSY or SQLITE_OK
143*/
144#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
145
drhd91c68f2010-05-14 14:52:25 +0000146/* Forward references */
147typedef struct unixShm unixShm; /* Connection shared memory */
148typedef struct unixShmNode unixShmNode; /* Shared memory instance */
149typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
150typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000151
152/*
dane946c392009-08-22 11:39:46 +0000153** Sometimes, after a file handle is closed by SQLite, the file descriptor
154** cannot be closed immediately. In these cases, instances of the following
155** structure are used to store the file descriptor while waiting for an
156** opportunity to either close or reuse it.
157*/
dane946c392009-08-22 11:39:46 +0000158struct UnixUnusedFd {
159 int fd; /* File descriptor to close */
160 int flags; /* Flags this file descriptor was opened with */
161 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
162};
163
164/*
drh9b35ea62008-11-29 02:20:26 +0000165** The unixFile structure is subclass of sqlite3_file specific to the unix
166** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000167*/
drh054889e2005-11-30 03:20:31 +0000168typedef struct unixFile unixFile;
169struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000170 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000171 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000172 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000173 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000174 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000175 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000176 int lastErrno; /* The unix errno from last I/O error */
177 void *lockingContext; /* Locking style specific state */
178 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000179 const char *zPath; /* Name of the file */
180 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000181 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000182#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000183 int nFetchOut; /* Number of outstanding xFetch refs */
184 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000185 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
186 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000187 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000188#endif
drh537dddf2012-10-26 13:46:24 +0000189#ifdef __QNXNTO__
190 int sectorSize; /* Device sector size */
191 int deviceCharacteristics; /* Precomputed device characteristics */
192#endif
drh08c6d442009-02-09 17:34:07 +0000193#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000194 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000195#endif
drh7ed97b92010-01-20 13:07:21 +0000196#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000197 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000198#endif
199#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000200 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000201#endif
drhd3d8c042012-05-29 17:02:40 +0000202#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000203 /* The next group of variables are used to track whether or not the
204 ** transaction counter in bytes 24-27 of database files are updated
205 ** whenever any part of the database changes. An assertion fault will
206 ** occur if a file is updated without also updating the transaction
207 ** counter. This test is made to avoid new problems similar to the
208 ** one described by ticket #3584.
209 */
210 unsigned char transCntrChng; /* True if the transaction counter changed */
211 unsigned char dbUpdate; /* True if any part of database file changed */
212 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000213
drh8f941bc2009-01-14 23:03:40 +0000214#endif
danf23da962013-03-23 21:00:41 +0000215
danielk1977967a4a12007-08-20 14:23:44 +0000216#ifdef SQLITE_TEST
217 /* In test mode, increase the size of this structure a bit so that
218 ** it is larger than the struct CrashFile defined in test6.c.
219 */
220 char aPadding[32];
221#endif
drh9cbe6352005-11-29 03:13:21 +0000222};
223
drhb00d8622014-01-01 15:18:36 +0000224/* This variable holds the process id (pid) from when the xRandomness()
225** method was called. If xOpen() is called from a different process id,
226** indicating that a fork() has occurred, the PRNG will be reset.
227*/
drh8cd5b252015-03-02 22:06:43 +0000228static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000229
drh0ccebe72005-06-07 22:22:50 +0000230/*
drha7e61d82011-03-12 17:02:57 +0000231** Allowed values for the unixFile.ctrlFlags bitmask:
232*/
drhf0b190d2011-07-26 16:03:07 +0000233#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
234#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
235#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000236#ifndef SQLITE_DISABLE_DIRSYNC
237# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
238#else
239# define UNIXFILE_DIRSYNC 0x00
240#endif
drhcb15f352011-12-23 01:04:17 +0000241#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000242#define UNIXFILE_DELETE 0x20 /* Delete on close */
243#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
244#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhe6d41732015-02-21 00:49:00 +0000245#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
drha7e61d82011-03-12 17:02:57 +0000246
247/*
drh198bf392006-01-06 21:52:49 +0000248** Include code that is common to all os_*.c files
249*/
250#include "os_common.h"
251
252/*
drh0ccebe72005-06-07 22:22:50 +0000253** Define various macros that are missing from some systems.
254*/
drhbbd42a62004-05-22 17:41:58 +0000255#ifndef O_LARGEFILE
256# define O_LARGEFILE 0
257#endif
258#ifdef SQLITE_DISABLE_LFS
259# undef O_LARGEFILE
260# define O_LARGEFILE 0
261#endif
262#ifndef O_NOFOLLOW
263# define O_NOFOLLOW 0
264#endif
265#ifndef O_BINARY
266# define O_BINARY 0
267#endif
268
269/*
drh2b4b5962005-06-15 17:47:55 +0000270** The threadid macro resolves to the thread-id or to 0. Used for
271** testing and debugging only.
272*/
drhd677b3d2007-08-20 22:48:41 +0000273#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000274#define threadid pthread_self()
275#else
276#define threadid 0
277#endif
278
drh99ab3b12011-03-02 15:09:07 +0000279/*
dane6ecd662013-04-01 17:56:59 +0000280** HAVE_MREMAP defaults to true on Linux and false everywhere else.
281*/
282#if !defined(HAVE_MREMAP)
283# if defined(__linux__) && defined(_GNU_SOURCE)
284# define HAVE_MREMAP 1
285# else
286# define HAVE_MREMAP 0
287# endif
288#endif
289
290/*
dan2ee53412014-09-06 16:49:40 +0000291** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
292** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
293*/
294#ifdef __ANDROID__
295# define lseek lseek64
296#endif
297
298/*
drh9a3baf12011-04-25 18:01:27 +0000299** Different Unix systems declare open() in different ways. Same use
300** open(const char*,int,mode_t). Others use open(const char*,int,...).
301** The difference is important when using a pointer to the function.
302**
303** The safest way to deal with the problem is to always use this wrapper
304** which always has the same well-defined interface.
305*/
306static int posixOpen(const char *zFile, int flags, int mode){
307 return open(zFile, flags, mode);
308}
309
drhed466822012-05-31 13:10:49 +0000310/*
311** On some systems, calls to fchown() will trigger a message in a security
312** log if they come from non-root processes. So avoid calling fchown() if
313** we are not running as root.
314*/
315static int posixFchown(int fd, uid_t uid, gid_t gid){
drh91be7dc2014-08-11 13:53:30 +0000316#if OS_VXWORKS
317 return 0;
318#else
drhed466822012-05-31 13:10:49 +0000319 return geteuid() ? 0 : fchown(fd,uid,gid);
drh91be7dc2014-08-11 13:53:30 +0000320#endif
drhed466822012-05-31 13:10:49 +0000321}
322
drh90315a22011-08-10 01:52:12 +0000323/* Forward reference */
324static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000325static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000326
drh9a3baf12011-04-25 18:01:27 +0000327/*
drh99ab3b12011-03-02 15:09:07 +0000328** Many system calls are accessed through pointer-to-functions so that
329** they may be overridden at runtime to facilitate fault injection during
330** testing and sandboxing. The following array holds the names and pointers
331** to all overrideable system calls.
332*/
333static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000334 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000335 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
336 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000337} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000338 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
339#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000340
drh58ad5802011-03-23 22:02:23 +0000341 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000342#define osClose ((int(*)(int))aSyscall[1].pCurrent)
343
drh58ad5802011-03-23 22:02:23 +0000344 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
346
drh58ad5802011-03-23 22:02:23 +0000347 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
349
drh58ad5802011-03-23 22:02:23 +0000350 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
352
353/*
354** The DJGPP compiler environment looks mostly like Unix, but it
355** lacks the fcntl() system call. So redefine fcntl() to be something
356** that always succeeds. This means that locking does not occur under
357** DJGPP. But it is DOS - what did you expect?
358*/
359#ifdef __DJGPP__
360 { "fstat", 0, 0 },
361#define osFstat(a,b,c) 0
362#else
drh58ad5802011-03-23 22:02:23 +0000363 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000364#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
365#endif
366
drh58ad5802011-03-23 22:02:23 +0000367 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
369
drh58ad5802011-03-23 22:02:23 +0000370 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000372
drh58ad5802011-03-23 22:02:23 +0000373 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000374#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
375
drh91be7dc2014-08-11 13:53:30 +0000376#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh58ad5802011-03-23 22:02:23 +0000377 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000378#else
drh58ad5802011-03-23 22:02:23 +0000379 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000380#endif
381#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
382
383#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000384 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000385#else
drh58ad5802011-03-23 22:02:23 +0000386 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000387#endif
388#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
389
drh58ad5802011-03-23 22:02:23 +0000390 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000391#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
392
drh91be7dc2014-08-11 13:53:30 +0000393#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh58ad5802011-03-23 22:02:23 +0000394 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000395#else
drh58ad5802011-03-23 22:02:23 +0000396 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000397#endif
398#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
399 aSyscall[12].pCurrent)
400
401#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000402 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000403#else
drh58ad5802011-03-23 22:02:23 +0000404 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000405#endif
406#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
407 aSyscall[13].pCurrent)
408
drh58ad5802011-03-23 22:02:23 +0000409 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000410#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000411
412#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000413 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000414#else
drh58ad5802011-03-23 22:02:23 +0000415 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000416#endif
dan0fd7d862011-03-29 10:04:23 +0000417#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000418
drh036ac7f2011-08-08 23:18:05 +0000419 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
420#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
421
drh90315a22011-08-10 01:52:12 +0000422 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
423#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
424
drh9ef6bc42011-11-04 02:24:02 +0000425 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
426#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
427
428 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
429#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
430
drhed466822012-05-31 13:10:49 +0000431 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000432#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000433
dan4dd51442013-08-26 14:30:25 +0000434#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000435 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
436#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
437
drhd1ab8062013-03-25 20:50:25 +0000438 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
439#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
440
dane6ecd662013-04-01 17:56:59 +0000441#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000442 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
443#else
444 { "mremap", (sqlite3_syscall_ptr)0, 0 },
445#endif
446#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
danbc760632014-03-20 09:42:09 +0000447 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
448#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
449
dan702eec12014-06-23 10:04:58 +0000450#endif
451
drhe562be52011-03-02 18:01:10 +0000452}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000453
454/*
455** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000456** "unix" VFSes. Return SQLITE_OK opon successfully updating the
457** system call pointer, or SQLITE_NOTFOUND if there is no configurable
458** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000459*/
460static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000461 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
462 const char *zName, /* Name of system call to override */
463 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000464){
drh58ad5802011-03-23 22:02:23 +0000465 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000466 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000467
468 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000469 if( zName==0 ){
470 /* If no zName is given, restore all system calls to their default
471 ** settings and return NULL
472 */
dan51438a72011-04-02 17:00:47 +0000473 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000474 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
475 if( aSyscall[i].pDefault ){
476 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000477 }
478 }
479 }else{
480 /* If zName is specified, operate on only the one system call
481 ** specified.
482 */
483 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
484 if( strcmp(zName, aSyscall[i].zName)==0 ){
485 if( aSyscall[i].pDefault==0 ){
486 aSyscall[i].pDefault = aSyscall[i].pCurrent;
487 }
drh1df30962011-03-02 19:06:42 +0000488 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000489 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
490 aSyscall[i].pCurrent = pNewFunc;
491 break;
492 }
493 }
494 }
495 return rc;
496}
497
drh1df30962011-03-02 19:06:42 +0000498/*
499** Return the value of a system call. Return NULL if zName is not a
500** recognized system call name. NULL is also returned if the system call
501** is currently undefined.
502*/
drh58ad5802011-03-23 22:02:23 +0000503static sqlite3_syscall_ptr unixGetSystemCall(
504 sqlite3_vfs *pNotUsed,
505 const char *zName
506){
507 unsigned int i;
508
509 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000510 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
511 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
512 }
513 return 0;
514}
515
516/*
517** Return the name of the first system call after zName. If zName==NULL
518** then return the name of the first system call. Return NULL if zName
519** is the last system call or if zName is not the name of a valid
520** system call.
521*/
522static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000523 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000524
525 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000526 if( zName ){
527 for(i=0; i<ArraySize(aSyscall)-1; i++){
528 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000529 }
530 }
dan0fd7d862011-03-29 10:04:23 +0000531 for(i++; i<ArraySize(aSyscall); i++){
532 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000533 }
534 return 0;
535}
536
drhad4f1e52011-03-04 15:43:57 +0000537/*
drh77a3fdc2013-08-30 14:24:12 +0000538** Do not accept any file descriptor less than this value, in order to avoid
539** opening database file using file descriptors that are commonly used for
540** standard input, output, and error.
541*/
542#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
543# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
544#endif
545
546/*
drh8c815d12012-02-13 20:16:37 +0000547** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000548** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000549**
550** If the file creation mode "m" is 0 then set it to the default for
551** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
552** 0644) as modified by the system umask. If m is not 0, then
553** make the file creation mode be exactly m ignoring the umask.
554**
555** The m parameter will be non-zero only when creating -wal, -journal,
556** and -shm files. We want those files to have *exactly* the same
557** permissions as their original database, unadulterated by the umask.
558** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
559** transaction crashes and leaves behind hot journals, then any
560** process that is able to write to the database will also be able to
561** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000562*/
drh8c815d12012-02-13 20:16:37 +0000563static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000564 int fd;
drhe1186ab2013-01-04 20:45:13 +0000565 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000566 while(1){
drh5adc60b2012-04-14 13:25:11 +0000567#if defined(O_CLOEXEC)
568 fd = osOpen(z,f|O_CLOEXEC,m2);
569#else
570 fd = osOpen(z,f,m2);
571#endif
drh5128d002013-08-30 06:20:23 +0000572 if( fd<0 ){
573 if( errno==EINTR ) continue;
574 break;
575 }
drh77a3fdc2013-08-30 14:24:12 +0000576 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000577 osClose(fd);
578 sqlite3_log(SQLITE_WARNING,
579 "attempt to open \"%s\" as file descriptor %d", z, fd);
580 fd = -1;
581 if( osOpen("/dev/null", f, m)<0 ) break;
582 }
drhe1186ab2013-01-04 20:45:13 +0000583 if( fd>=0 ){
584 if( m!=0 ){
585 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000586 if( osFstat(fd, &statbuf)==0
587 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000588 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000589 ){
drhe1186ab2013-01-04 20:45:13 +0000590 osFchmod(fd, m);
591 }
592 }
drh5adc60b2012-04-14 13:25:11 +0000593#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000594 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000595#endif
drhe1186ab2013-01-04 20:45:13 +0000596 }
drh5adc60b2012-04-14 13:25:11 +0000597 return fd;
drhad4f1e52011-03-04 15:43:57 +0000598}
danielk197713adf8a2004-06-03 16:08:41 +0000599
drh107886a2008-11-21 22:21:50 +0000600/*
dan9359c7b2009-08-21 08:29:10 +0000601** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000602** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000603** vxworksFileId objects used by this file, all of which may be
604** shared by multiple threads.
605**
606** Function unixMutexHeld() is used to assert() that the global mutex
607** is held when required. This function is only used as part of assert()
608** statements. e.g.
609**
610** unixEnterMutex()
611** assert( unixMutexHeld() );
612** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000613*/
614static void unixEnterMutex(void){
615 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
616}
617static void unixLeaveMutex(void){
618 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
619}
dan9359c7b2009-08-21 08:29:10 +0000620#ifdef SQLITE_DEBUG
621static int unixMutexHeld(void) {
622 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
623}
624#endif
drh107886a2008-11-21 22:21:50 +0000625
drh734c9862008-11-28 15:37:20 +0000626
drh30ddce62011-10-15 00:16:30 +0000627#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000628/*
629** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000630** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000631** integer lock-type.
632*/
drh308c2a52010-05-14 11:30:18 +0000633static const char *azFileLock(int eFileLock){
634 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000635 case NO_LOCK: return "NONE";
636 case SHARED_LOCK: return "SHARED";
637 case RESERVED_LOCK: return "RESERVED";
638 case PENDING_LOCK: return "PENDING";
639 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000640 }
641 return "ERROR";
642}
643#endif
644
645#ifdef SQLITE_LOCK_TRACE
646/*
647** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000648**
drh734c9862008-11-28 15:37:20 +0000649** This routine is used for troubleshooting locks on multithreaded
650** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
651** command-line option on the compiler. This code is normally
652** turned off.
653*/
654static int lockTrace(int fd, int op, struct flock *p){
655 char *zOpName, *zType;
656 int s;
657 int savedErrno;
658 if( op==F_GETLK ){
659 zOpName = "GETLK";
660 }else if( op==F_SETLK ){
661 zOpName = "SETLK";
662 }else{
drh99ab3b12011-03-02 15:09:07 +0000663 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000664 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
665 return s;
666 }
667 if( p->l_type==F_RDLCK ){
668 zType = "RDLCK";
669 }else if( p->l_type==F_WRLCK ){
670 zType = "WRLCK";
671 }else if( p->l_type==F_UNLCK ){
672 zType = "UNLCK";
673 }else{
674 assert( 0 );
675 }
676 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000677 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000678 savedErrno = errno;
679 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
680 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
681 (int)p->l_pid, s);
682 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
683 struct flock l2;
684 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000685 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000686 if( l2.l_type==F_RDLCK ){
687 zType = "RDLCK";
688 }else if( l2.l_type==F_WRLCK ){
689 zType = "WRLCK";
690 }else if( l2.l_type==F_UNLCK ){
691 zType = "UNLCK";
692 }else{
693 assert( 0 );
694 }
695 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
696 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
697 }
698 errno = savedErrno;
699 return s;
700}
drh99ab3b12011-03-02 15:09:07 +0000701#undef osFcntl
702#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000703#endif /* SQLITE_LOCK_TRACE */
704
drhff812312011-02-23 13:33:46 +0000705/*
706** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000707**
drhe6d41732015-02-21 00:49:00 +0000708** All calls to ftruncate() within this file should be made through
709** this wrapper. On the Android platform, bypassing the logic below
710** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000711*/
drhff812312011-02-23 13:33:46 +0000712static int robust_ftruncate(int h, sqlite3_int64 sz){
713 int rc;
dan2ee53412014-09-06 16:49:40 +0000714#ifdef __ANDROID__
715 /* On Android, ftruncate() always uses 32-bit offsets, even if
716 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000717 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000718 ** such attempts. */
719 if( sz>(sqlite3_int64)0x7FFFFFFF ){
720 rc = SQLITE_OK;
721 }else
722#endif
drh99ab3b12011-03-02 15:09:07 +0000723 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000724 return rc;
725}
drh734c9862008-11-28 15:37:20 +0000726
727/*
728** This routine translates a standard POSIX errno code into something
729** useful to the clients of the sqlite3 functions. Specifically, it is
730** intended to translate a variety of "try again" errors into SQLITE_BUSY
731** and a variety of "please close the file descriptor NOW" errors into
732** SQLITE_IOERR
733**
734** Errors during initialization of locks, or file system support for locks,
735** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
736*/
737static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
738 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000739#if 0
740 /* At one point this code was not commented out. In theory, this branch
741 ** should never be hit, as this function should only be called after
742 ** a locking-related function (i.e. fcntl()) has returned non-zero with
743 ** the value of errno as the first argument. Since a system call has failed,
744 ** errno should be non-zero.
745 **
746 ** Despite this, if errno really is zero, we still don't want to return
747 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
748 ** propagated back to the caller. Commenting this branch out means errno==0
749 ** will be handled by the "default:" case below.
750 */
drh734c9862008-11-28 15:37:20 +0000751 case 0:
752 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000753#endif
754
drh734c9862008-11-28 15:37:20 +0000755 case EAGAIN:
756 case ETIMEDOUT:
757 case EBUSY:
758 case EINTR:
759 case ENOLCK:
760 /* random NFS retry error, unless during file system support
761 * introspection, in which it actually means what it says */
762 return SQLITE_BUSY;
763
764 case EACCES:
765 /* EACCES is like EAGAIN during locking operations, but not any other time*/
766 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000767 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
768 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
769 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000770 return SQLITE_BUSY;
771 }
772 /* else fall through */
773 case EPERM:
774 return SQLITE_PERM;
775
drh734c9862008-11-28 15:37:20 +0000776#if EOPNOTSUPP!=ENOTSUP
777 case EOPNOTSUPP:
778 /* something went terribly awry, unless during file system support
779 * introspection, in which it actually means what it says */
780#endif
781#ifdef ENOTSUP
782 case ENOTSUP:
783 /* invalid fd, unless during file system support introspection, in which
784 * it actually means what it says */
785#endif
786 case EIO:
787 case EBADF:
788 case EINVAL:
789 case ENOTCONN:
790 case ENODEV:
791 case ENXIO:
792 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000793#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000794 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000795#endif
drh734c9862008-11-28 15:37:20 +0000796 case ENOSYS:
797 /* these should force the client to close the file and reconnect */
798
799 default:
800 return sqliteIOErr;
801 }
802}
803
804
drh734c9862008-11-28 15:37:20 +0000805/******************************************************************************
806****************** Begin Unique File ID Utility Used By VxWorks ***************
807**
808** On most versions of unix, we can get a unique ID for a file by concatenating
809** the device number and the inode number. But this does not work on VxWorks.
810** On VxWorks, a unique file id must be based on the canonical filename.
811**
812** A pointer to an instance of the following structure can be used as a
813** unique file ID in VxWorks. Each instance of this structure contains
814** a copy of the canonical filename. There is also a reference count.
815** The structure is reclaimed when the number of pointers to it drops to
816** zero.
817**
818** There are never very many files open at one time and lookups are not
819** a performance-critical path, so it is sufficient to put these
820** structures on a linked list.
821*/
822struct vxworksFileId {
823 struct vxworksFileId *pNext; /* Next in a list of them all */
824 int nRef; /* Number of references to this one */
825 int nName; /* Length of the zCanonicalName[] string */
826 char *zCanonicalName; /* Canonical filename */
827};
828
829#if OS_VXWORKS
830/*
drh9b35ea62008-11-29 02:20:26 +0000831** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000832** variable:
833*/
834static struct vxworksFileId *vxworksFileList = 0;
835
836/*
837** Simplify a filename into its canonical form
838** by making the following changes:
839**
840** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000841** * convert /./ into just /
842** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000843**
844** Changes are made in-place. Return the new name length.
845**
846** The original filename is in z[0..n-1]. Return the number of
847** characters in the simplified name.
848*/
849static int vxworksSimplifyName(char *z, int n){
850 int i, j;
851 while( n>1 && z[n-1]=='/' ){ n--; }
852 for(i=j=0; i<n; i++){
853 if( z[i]=='/' ){
854 if( z[i+1]=='/' ) continue;
855 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
856 i += 1;
857 continue;
858 }
859 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
860 while( j>0 && z[j-1]!='/' ){ j--; }
861 if( j>0 ){ j--; }
862 i += 2;
863 continue;
864 }
865 }
866 z[j++] = z[i];
867 }
868 z[j] = 0;
869 return j;
870}
871
872/*
873** Find a unique file ID for the given absolute pathname. Return
874** a pointer to the vxworksFileId object. This pointer is the unique
875** file ID.
876**
877** The nRef field of the vxworksFileId object is incremented before
878** the object is returned. A new vxworksFileId object is created
879** and added to the global list if necessary.
880**
881** If a memory allocation error occurs, return NULL.
882*/
883static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
884 struct vxworksFileId *pNew; /* search key and new file ID */
885 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
886 int n; /* Length of zAbsoluteName string */
887
888 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000889 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000890 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
891 if( pNew==0 ) return 0;
892 pNew->zCanonicalName = (char*)&pNew[1];
893 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
894 n = vxworksSimplifyName(pNew->zCanonicalName, n);
895
896 /* Search for an existing entry that matching the canonical name.
897 ** If found, increment the reference count and return a pointer to
898 ** the existing file ID.
899 */
900 unixEnterMutex();
901 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
902 if( pCandidate->nName==n
903 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
904 ){
905 sqlite3_free(pNew);
906 pCandidate->nRef++;
907 unixLeaveMutex();
908 return pCandidate;
909 }
910 }
911
912 /* No match was found. We will make a new file ID */
913 pNew->nRef = 1;
914 pNew->nName = n;
915 pNew->pNext = vxworksFileList;
916 vxworksFileList = pNew;
917 unixLeaveMutex();
918 return pNew;
919}
920
921/*
922** Decrement the reference count on a vxworksFileId object. Free
923** the object when the reference count reaches zero.
924*/
925static void vxworksReleaseFileId(struct vxworksFileId *pId){
926 unixEnterMutex();
927 assert( pId->nRef>0 );
928 pId->nRef--;
929 if( pId->nRef==0 ){
930 struct vxworksFileId **pp;
931 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
932 assert( *pp==pId );
933 *pp = pId->pNext;
934 sqlite3_free(pId);
935 }
936 unixLeaveMutex();
937}
938#endif /* OS_VXWORKS */
939/*************** End of Unique File ID Utility Used By VxWorks ****************
940******************************************************************************/
941
942
943/******************************************************************************
944*************************** Posix Advisory Locking ****************************
945**
drh9b35ea62008-11-29 02:20:26 +0000946** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000947** section 6.5.2.2 lines 483 through 490 specify that when a process
948** sets or clears a lock, that operation overrides any prior locks set
949** by the same process. It does not explicitly say so, but this implies
950** that it overrides locks set by the same process using a different
951** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000952**
953** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000954** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
955**
956** Suppose ./file1 and ./file2 are really the same file (because
957** one is a hard or symbolic link to the other) then if you set
958** an exclusive lock on fd1, then try to get an exclusive lock
959** on fd2, it works. I would have expected the second lock to
960** fail since there was already a lock on the file due to fd1.
961** But not so. Since both locks came from the same process, the
962** second overrides the first, even though they were on different
963** file descriptors opened on different file names.
964**
drh734c9862008-11-28 15:37:20 +0000965** This means that we cannot use POSIX locks to synchronize file access
966** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000967** to synchronize access for threads in separate processes, but not
968** threads within the same process.
969**
970** To work around the problem, SQLite has to manage file locks internally
971** on its own. Whenever a new database is opened, we have to find the
972** specific inode of the database file (the inode is determined by the
973** st_dev and st_ino fields of the stat structure that fstat() fills in)
974** and check for locks already existing on that inode. When locks are
975** created or removed, we have to look at our own internal record of the
976** locks to see if another thread has previously set a lock on that same
977** inode.
978**
drh9b35ea62008-11-29 02:20:26 +0000979** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
980** For VxWorks, we have to use the alternative unique ID system based on
981** canonical filename and implemented in the previous division.)
982**
danielk1977ad94b582007-08-20 06:44:22 +0000983** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000984** descriptor. It is now a structure that holds the integer file
985** descriptor and a pointer to a structure that describes the internal
986** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000987** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000988** point to the same locking structure. The locking structure keeps
989** a reference count (so we will know when to delete it) and a "cnt"
990** field that tells us its internal lock status. cnt==0 means the
991** file is unlocked. cnt==-1 means the file has an exclusive lock.
992** cnt>0 means there are cnt shared locks on the file.
993**
994** Any attempt to lock or unlock a file first checks the locking
995** structure. The fcntl() system call is only invoked to set a
996** POSIX lock if the internal lock structure transitions between
997** a locked and an unlocked state.
998**
drh734c9862008-11-28 15:37:20 +0000999** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001000**
1001** If you close a file descriptor that points to a file that has locks,
1002** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001003** released. To work around this problem, each unixInodeInfo object
1004** maintains a count of the number of pending locks on tha inode.
1005** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001006** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001007** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001008** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001009** be closed and that list is walked (and cleared) when the last lock
1010** clears.
1011**
drh9b35ea62008-11-29 02:20:26 +00001012** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001013**
drh9b35ea62008-11-29 02:20:26 +00001014** Many older versions of linux use the LinuxThreads library which is
1015** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001016** A cannot be modified or overridden by a different thread B.
1017** Only thread A can modify the lock. Locking behavior is correct
1018** if the appliation uses the newer Native Posix Thread Library (NPTL)
1019** on linux - with NPTL a lock created by thread A can override locks
1020** in thread B. But there is no way to know at compile-time which
1021** threading library is being used. So there is no way to know at
1022** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001023** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001024** current process.
drh5fdae772004-06-29 03:29:00 +00001025**
drh8af6c222010-05-14 12:43:01 +00001026** SQLite used to support LinuxThreads. But support for LinuxThreads
1027** was dropped beginning with version 3.7.0. SQLite will still work with
1028** LinuxThreads provided that (1) there is no more than one connection
1029** per database file in the same process and (2) database connections
1030** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001031*/
1032
1033/*
1034** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001035** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001036*/
1037struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001038 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001039#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001040 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001041#else
drh107886a2008-11-21 22:21:50 +00001042 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001043#endif
1044};
1045
1046/*
drhbbd42a62004-05-22 17:41:58 +00001047** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001048** inode. Or, on LinuxThreads, there is one of these structures for
1049** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001050**
danielk1977ad94b582007-08-20 06:44:22 +00001051** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001052** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001053** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001054*/
drh8af6c222010-05-14 12:43:01 +00001055struct unixInodeInfo {
1056 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001057 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001058 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1059 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001060 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001061 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1062 int nLock; /* Number of outstanding file locks */
1063 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1064 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1065 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001066#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001067 unsigned long long sharedByte; /* for AFP simulated shared lock */
1068#endif
drh6c7d5c52008-11-21 20:32:33 +00001069#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001070 sem_t *pSem; /* Named POSIX semaphore */
1071 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001072#endif
drhbbd42a62004-05-22 17:41:58 +00001073};
1074
drhda0e7682008-07-30 15:27:54 +00001075/*
drh8af6c222010-05-14 12:43:01 +00001076** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001077*/
drhd91c68f2010-05-14 14:52:25 +00001078static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001079
drh5fdae772004-06-29 03:29:00 +00001080/*
dane18d4952011-02-21 11:46:24 +00001081**
1082** This function - unixLogError_x(), is only ever called via the macro
1083** unixLogError().
1084**
1085** It is invoked after an error occurs in an OS function and errno has been
1086** set. It logs a message using sqlite3_log() containing the current value of
1087** errno and, if possible, the human-readable equivalent from strerror() or
1088** strerror_r().
1089**
1090** The first argument passed to the macro should be the error code that
1091** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1092** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001093** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001094** if any.
1095*/
drh0e9365c2011-03-02 02:08:13 +00001096#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1097static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001098 int errcode, /* SQLite error code */
1099 const char *zFunc, /* Name of OS function that failed */
1100 const char *zPath, /* File path associated with error */
1101 int iLine /* Source line number where error occurred */
1102){
1103 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001104 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001105
1106 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1107 ** the strerror() function to obtain the human-readable error message
1108 ** equivalent to errno. Otherwise, use strerror_r().
1109 */
1110#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1111 char aErr[80];
1112 memset(aErr, 0, sizeof(aErr));
1113 zErr = aErr;
1114
1115 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001116 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001117 ** returns a pointer to a buffer containing the error message. That pointer
1118 ** may point to aErr[], or it may point to some static storage somewhere.
1119 ** Otherwise, assume that the system provides the POSIX version of
1120 ** strerror_r(), which always writes an error message into aErr[].
1121 **
1122 ** If the code incorrectly assumes that it is the POSIX version that is
1123 ** available, the error message will often be an empty string. Not a
1124 ** huge problem. Incorrectly concluding that the GNU version is available
1125 ** could lead to a segfault though.
1126 */
1127#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1128 zErr =
1129# endif
drh0e9365c2011-03-02 02:08:13 +00001130 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001131
1132#elif SQLITE_THREADSAFE
1133 /* This is a threadsafe build, but strerror_r() is not available. */
1134 zErr = "";
1135#else
1136 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001137 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001138#endif
1139
drh0e9365c2011-03-02 02:08:13 +00001140 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001141 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001142 "os_unix.c:%d: (%d) %s(%s) - %s",
1143 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001144 );
1145
1146 return errcode;
1147}
1148
drh0e9365c2011-03-02 02:08:13 +00001149/*
1150** Close a file descriptor.
1151**
1152** We assume that close() almost always works, since it is only in a
1153** very sick application or on a very sick platform that it might fail.
1154** If it does fail, simply leak the file descriptor, but do log the
1155** error.
1156**
1157** Note that it is not safe to retry close() after EINTR since the
1158** file descriptor might have already been reused by another thread.
1159** So we don't even try to recover from an EINTR. Just log the error
1160** and move on.
1161*/
1162static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001163 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001164 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1165 pFile ? pFile->zPath : 0, lineno);
1166 }
1167}
dane18d4952011-02-21 11:46:24 +00001168
1169/*
drhe6d41732015-02-21 00:49:00 +00001170** Set the pFile->lastErrno. Do this in a subroutine as that provides
1171** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001172*/
1173static void storeLastErrno(unixFile *pFile, int error){
1174 pFile->lastErrno = error;
1175}
1176
1177/*
danb0ac3e32010-06-16 10:55:42 +00001178** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001179*/
drh0e9365c2011-03-02 02:08:13 +00001180static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001181 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001182 UnixUnusedFd *p;
1183 UnixUnusedFd *pNext;
1184 for(p=pInode->pUnused; p; p=pNext){
1185 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001186 robust_close(pFile, p->fd, __LINE__);
1187 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001188 }
drh0e9365c2011-03-02 02:08:13 +00001189 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001190}
1191
1192/*
drh8af6c222010-05-14 12:43:01 +00001193** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001194**
1195** The mutex entered using the unixEnterMutex() function must be held
1196** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001197*/
danb0ac3e32010-06-16 10:55:42 +00001198static void releaseInodeInfo(unixFile *pFile){
1199 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001200 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001201 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001202 pInode->nRef--;
1203 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001204 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001205 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001206 if( pInode->pPrev ){
1207 assert( pInode->pPrev->pNext==pInode );
1208 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001209 }else{
drh8af6c222010-05-14 12:43:01 +00001210 assert( inodeList==pInode );
1211 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001212 }
drh8af6c222010-05-14 12:43:01 +00001213 if( pInode->pNext ){
1214 assert( pInode->pNext->pPrev==pInode );
1215 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001216 }
drh8af6c222010-05-14 12:43:01 +00001217 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001218 }
drhbbd42a62004-05-22 17:41:58 +00001219 }
1220}
1221
1222/*
drh8af6c222010-05-14 12:43:01 +00001223** Given a file descriptor, locate the unixInodeInfo object that
1224** describes that file descriptor. Create a new one if necessary. The
1225** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001226**
dan9359c7b2009-08-21 08:29:10 +00001227** The mutex entered using the unixEnterMutex() function must be held
1228** when this function is called.
1229**
drh6c7d5c52008-11-21 20:32:33 +00001230** Return an appropriate error code.
1231*/
drh8af6c222010-05-14 12:43:01 +00001232static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001233 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001234 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001235){
1236 int rc; /* System call return code */
1237 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001238 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1239 struct stat statbuf; /* Low-level file information */
1240 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001241
dan9359c7b2009-08-21 08:29:10 +00001242 assert( unixMutexHeld() );
1243
drh6c7d5c52008-11-21 20:32:33 +00001244 /* Get low-level information about the file that we can used to
1245 ** create a unique name for the file.
1246 */
1247 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001248 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001249 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001250 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001251#ifdef EOVERFLOW
1252 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1253#endif
1254 return SQLITE_IOERR;
1255 }
1256
drheb0d74f2009-02-03 15:27:02 +00001257#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001258 /* On OS X on an msdos filesystem, the inode number is reported
1259 ** incorrectly for zero-size files. See ticket #3260. To work
1260 ** around this problem (we consider it a bug in OS X, not SQLite)
1261 ** we always increase the file size to 1 by writing a single byte
1262 ** prior to accessing the inode number. The one byte written is
1263 ** an ASCII 'S' character which also happens to be the first byte
1264 ** in the header of every SQLite database. In this way, if there
1265 ** is a race condition such that another thread has already populated
1266 ** the first page of the database, no damage is done.
1267 */
drh7ed97b92010-01-20 13:07:21 +00001268 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001269 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001270 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001271 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001272 return SQLITE_IOERR;
1273 }
drh99ab3b12011-03-02 15:09:07 +00001274 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001275 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001276 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001277 return SQLITE_IOERR;
1278 }
1279 }
drheb0d74f2009-02-03 15:27:02 +00001280#endif
drh6c7d5c52008-11-21 20:32:33 +00001281
drh8af6c222010-05-14 12:43:01 +00001282 memset(&fileId, 0, sizeof(fileId));
1283 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001284#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001285 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001286#else
drh8af6c222010-05-14 12:43:01 +00001287 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001288#endif
drh8af6c222010-05-14 12:43:01 +00001289 pInode = inodeList;
1290 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1291 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001292 }
drh8af6c222010-05-14 12:43:01 +00001293 if( pInode==0 ){
1294 pInode = sqlite3_malloc( sizeof(*pInode) );
1295 if( pInode==0 ){
1296 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001297 }
drh8af6c222010-05-14 12:43:01 +00001298 memset(pInode, 0, sizeof(*pInode));
1299 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1300 pInode->nRef = 1;
1301 pInode->pNext = inodeList;
1302 pInode->pPrev = 0;
1303 if( inodeList ) inodeList->pPrev = pInode;
1304 inodeList = pInode;
1305 }else{
1306 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001307 }
drh8af6c222010-05-14 12:43:01 +00001308 *ppInode = pInode;
1309 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001310}
drh6c7d5c52008-11-21 20:32:33 +00001311
drhb959a012013-12-07 12:29:22 +00001312/*
1313** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1314*/
1315static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001316#if OS_VXWORKS
1317 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1318#else
drhb959a012013-12-07 12:29:22 +00001319 struct stat buf;
1320 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001321 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001322#endif
drhb959a012013-12-07 12:29:22 +00001323}
1324
aswift5b1a2562008-08-22 00:22:35 +00001325
1326/*
drhfbc7e882013-04-11 01:16:15 +00001327** Check a unixFile that is a database. Verify the following:
1328**
1329** (1) There is exactly one hard link on the file
1330** (2) The file is not a symbolic link
1331** (3) The file has not been renamed or unlinked
1332**
1333** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1334*/
1335static void verifyDbFile(unixFile *pFile){
1336 struct stat buf;
1337 int rc;
drh3044b512014-06-16 16:41:52 +00001338 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1339 /* One or more of the following warnings have already been issued. Do not
1340 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001341 return;
1342 }
1343 rc = osFstat(pFile->h, &buf);
1344 if( rc!=0 ){
1345 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1346 pFile->ctrlFlags |= UNIXFILE_WARNED;
1347 return;
1348 }
drh3044b512014-06-16 16:41:52 +00001349 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001350 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1351 pFile->ctrlFlags |= UNIXFILE_WARNED;
1352 return;
1353 }
1354 if( buf.st_nlink>1 ){
1355 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1356 pFile->ctrlFlags |= UNIXFILE_WARNED;
1357 return;
1358 }
drhb959a012013-12-07 12:29:22 +00001359 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001360 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1361 pFile->ctrlFlags |= UNIXFILE_WARNED;
1362 return;
1363 }
1364}
1365
1366
1367/*
danielk197713adf8a2004-06-03 16:08:41 +00001368** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001369** file by this or any other process. If such a lock is held, set *pResOut
1370** to a non-zero value otherwise *pResOut is set to zero. The return value
1371** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001372*/
danielk1977861f7452008-06-05 11:39:11 +00001373static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001374 int rc = SQLITE_OK;
1375 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001376 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001377
danielk1977861f7452008-06-05 11:39:11 +00001378 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1379
drh054889e2005-11-30 03:20:31 +00001380 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001381 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001382
1383 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001384 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001385 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001386 }
1387
drh2ac3ee92004-06-07 16:27:46 +00001388 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001389 */
danielk197709480a92009-02-09 05:32:32 +00001390#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001391 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001392 struct flock lock;
1393 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001394 lock.l_start = RESERVED_BYTE;
1395 lock.l_len = 1;
1396 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001397 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1398 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001399 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001400 } else if( lock.l_type!=F_UNLCK ){
1401 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001402 }
1403 }
danielk197709480a92009-02-09 05:32:32 +00001404#endif
danielk197713adf8a2004-06-03 16:08:41 +00001405
drh6c7d5c52008-11-21 20:32:33 +00001406 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001407 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001408
aswift5b1a2562008-08-22 00:22:35 +00001409 *pResOut = reserved;
1410 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001411}
1412
1413/*
drha7e61d82011-03-12 17:02:57 +00001414** Attempt to set a system-lock on the file pFile. The lock is
1415** described by pLock.
1416**
drh77197112011-03-15 19:08:48 +00001417** If the pFile was opened read/write from unix-excl, then the only lock
1418** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001419** the first time any lock is attempted. All subsequent system locking
1420** operations become no-ops. Locking operations still happen internally,
1421** in order to coordinate access between separate database connections
1422** within this process, but all of that is handled in memory and the
1423** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001424**
1425** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1426** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1427** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001428**
1429** Zero is returned if the call completes successfully, or -1 if a call
1430** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001431*/
1432static int unixFileLock(unixFile *pFile, struct flock *pLock){
1433 int rc;
drh3cb93392011-03-12 18:10:44 +00001434 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001435 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001436 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001437 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1438 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1439 ){
drh3cb93392011-03-12 18:10:44 +00001440 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001441 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001442 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001443 lock.l_whence = SEEK_SET;
1444 lock.l_start = SHARED_FIRST;
1445 lock.l_len = SHARED_SIZE;
1446 lock.l_type = F_WRLCK;
1447 rc = osFcntl(pFile->h, F_SETLK, &lock);
1448 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001449 pInode->bProcessLock = 1;
1450 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001451 }else{
1452 rc = 0;
1453 }
1454 }else{
1455 rc = osFcntl(pFile->h, F_SETLK, pLock);
1456 }
1457 return rc;
1458}
1459
1460/*
drh308c2a52010-05-14 11:30:18 +00001461** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001462** of the following:
1463**
drh2ac3ee92004-06-07 16:27:46 +00001464** (1) SHARED_LOCK
1465** (2) RESERVED_LOCK
1466** (3) PENDING_LOCK
1467** (4) EXCLUSIVE_LOCK
1468**
drhb3e04342004-06-08 00:47:47 +00001469** Sometimes when requesting one lock state, additional lock states
1470** are inserted in between. The locking might fail on one of the later
1471** transitions leaving the lock state different from what it started but
1472** still short of its goal. The following chart shows the allowed
1473** transitions and the inserted intermediate states:
1474**
1475** UNLOCKED -> SHARED
1476** SHARED -> RESERVED
1477** SHARED -> (PENDING) -> EXCLUSIVE
1478** RESERVED -> (PENDING) -> EXCLUSIVE
1479** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001480**
drha6abd042004-06-09 17:37:22 +00001481** This routine will only increase a lock. Use the sqlite3OsUnlock()
1482** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001483*/
drh308c2a52010-05-14 11:30:18 +00001484static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001485 /* The following describes the implementation of the various locks and
1486 ** lock transitions in terms of the POSIX advisory shared and exclusive
1487 ** lock primitives (called read-locks and write-locks below, to avoid
1488 ** confusion with SQLite lock names). The algorithms are complicated
1489 ** slightly in order to be compatible with windows systems simultaneously
1490 ** accessing the same database file, in case that is ever required.
1491 **
1492 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1493 ** byte', each single bytes at well known offsets, and the 'shared byte
1494 ** range', a range of 510 bytes at a well known offset.
1495 **
1496 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1497 ** byte'. If this is successful, a random byte from the 'shared byte
1498 ** range' is read-locked and the lock on the 'pending byte' released.
1499 **
danielk197790ba3bd2004-06-25 08:32:25 +00001500 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1501 ** A RESERVED lock is implemented by grabbing a write-lock on the
1502 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001503 **
1504 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001505 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1506 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1507 ** obtained, but existing SHARED locks are allowed to persist. A process
1508 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1509 ** This property is used by the algorithm for rolling back a journal file
1510 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001511 **
danielk197790ba3bd2004-06-25 08:32:25 +00001512 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1513 ** implemented by obtaining a write-lock on the entire 'shared byte
1514 ** range'. Since all other locks require a read-lock on one of the bytes
1515 ** within this range, this ensures that no other locks are held on the
1516 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001517 **
1518 ** The reason a single byte cannot be used instead of the 'shared byte
1519 ** range' is that some versions of windows do not support read-locks. By
1520 ** locking a random byte from a range, concurrent SHARED locks may exist
1521 ** even if the locking primitive used is always a write-lock.
1522 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001523 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001524 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001525 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001526 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001527 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001528
drh054889e2005-11-30 03:20:31 +00001529 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001530 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1531 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001532 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001533
1534 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001535 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001536 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 */
drh308c2a52010-05-14 11:30:18 +00001538 if( pFile->eFileLock>=eFileLock ){
1539 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1540 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001541 return SQLITE_OK;
1542 }
1543
drh0c2694b2009-09-03 16:23:44 +00001544 /* Make sure the locking sequence is correct.
1545 ** (1) We never move from unlocked to anything higher than shared lock.
1546 ** (2) SQLite never explicitly requests a pendig lock.
1547 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001548 */
drh308c2a52010-05-14 11:30:18 +00001549 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1550 assert( eFileLock!=PENDING_LOCK );
1551 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001552
drh8af6c222010-05-14 12:43:01 +00001553 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001554 */
drh6c7d5c52008-11-21 20:32:33 +00001555 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001556 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001557
danielk1977ad94b582007-08-20 06:44:22 +00001558 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001559 ** handle that precludes the requested lock, return BUSY.
1560 */
drh8af6c222010-05-14 12:43:01 +00001561 if( (pFile->eFileLock!=pInode->eFileLock &&
1562 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001563 ){
1564 rc = SQLITE_BUSY;
1565 goto end_lock;
1566 }
1567
1568 /* If a SHARED lock is requested, and some thread using this PID already
1569 ** has a SHARED or RESERVED lock, then increment reference counts and
1570 ** return SQLITE_OK.
1571 */
drh308c2a52010-05-14 11:30:18 +00001572 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001573 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001574 assert( eFileLock==SHARED_LOCK );
1575 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001576 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001577 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001578 pInode->nShared++;
1579 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001580 goto end_lock;
1581 }
1582
danielk19779a1d0ab2004-06-01 14:09:28 +00001583
drh3cde3bb2004-06-12 02:17:14 +00001584 /* A PENDING lock is needed before acquiring a SHARED lock and before
1585 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1586 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001587 */
drh0c2694b2009-09-03 16:23:44 +00001588 lock.l_len = 1L;
1589 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001590 if( eFileLock==SHARED_LOCK
1591 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001592 ){
drh308c2a52010-05-14 11:30:18 +00001593 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001594 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001595 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001596 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001597 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001598 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001599 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001600 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001601 goto end_lock;
1602 }
drh3cde3bb2004-06-12 02:17:14 +00001603 }
1604
1605
1606 /* If control gets to this point, then actually go ahead and make
1607 ** operating system calls for the specified lock.
1608 */
drh308c2a52010-05-14 11:30:18 +00001609 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001610 assert( pInode->nShared==0 );
1611 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001612 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001613
drh2ac3ee92004-06-07 16:27:46 +00001614 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001615 lock.l_start = SHARED_FIRST;
1616 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001617 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001618 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001619 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001620 }
dan661d71a2011-03-30 19:08:03 +00001621
drh2ac3ee92004-06-07 16:27:46 +00001622 /* Drop the temporary PENDING lock */
1623 lock.l_start = PENDING_BYTE;
1624 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001625 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001626 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1627 /* This could happen with a network mount */
1628 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001629 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001630 }
dan661d71a2011-03-30 19:08:03 +00001631
1632 if( rc ){
1633 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001634 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001635 }
dan661d71a2011-03-30 19:08:03 +00001636 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001637 }else{
drh308c2a52010-05-14 11:30:18 +00001638 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001639 pInode->nLock++;
1640 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001641 }
drh8af6c222010-05-14 12:43:01 +00001642 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001643 /* We are trying for an exclusive lock but another thread in this
1644 ** same process is still holding a shared lock. */
1645 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001646 }else{
drh3cde3bb2004-06-12 02:17:14 +00001647 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001648 ** assumed that there is a SHARED or greater lock on the file
1649 ** already.
1650 */
drh308c2a52010-05-14 11:30:18 +00001651 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001652 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001653
1654 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1655 if( eFileLock==RESERVED_LOCK ){
1656 lock.l_start = RESERVED_BYTE;
1657 lock.l_len = 1L;
1658 }else{
1659 lock.l_start = SHARED_FIRST;
1660 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001661 }
dan661d71a2011-03-30 19:08:03 +00001662
1663 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001664 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001665 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001666 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001667 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001668 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001669 }
drhbbd42a62004-05-22 17:41:58 +00001670 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001671
drh8f941bc2009-01-14 23:03:40 +00001672
drhd3d8c042012-05-29 17:02:40 +00001673#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001674 /* Set up the transaction-counter change checking flags when
1675 ** transitioning from a SHARED to a RESERVED lock. The change
1676 ** from SHARED to RESERVED marks the beginning of a normal
1677 ** write operation (not a hot journal rollback).
1678 */
1679 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001680 && pFile->eFileLock<=SHARED_LOCK
1681 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001682 ){
1683 pFile->transCntrChng = 0;
1684 pFile->dbUpdate = 0;
1685 pFile->inNormalWrite = 1;
1686 }
1687#endif
1688
1689
danielk1977ecb2a962004-06-02 06:30:16 +00001690 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001691 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001692 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001693 }else if( eFileLock==EXCLUSIVE_LOCK ){
1694 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001695 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001696 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001697
1698end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001699 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001700 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1701 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001702 return rc;
1703}
1704
1705/*
dan08da86a2009-08-21 17:18:03 +00001706** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001707** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001708*/
1709static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001710 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001711 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001712 p->pNext = pInode->pUnused;
1713 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001714 pFile->h = -1;
1715 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001716}
1717
1718/*
drh308c2a52010-05-14 11:30:18 +00001719** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001720** must be either NO_LOCK or SHARED_LOCK.
1721**
1722** If the locking level of the file descriptor is already at or below
1723** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001724**
1725** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1726** the byte range is divided into 2 parts and the first part is unlocked then
1727** set to a read lock, then the other part is simply unlocked. This works
1728** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1729** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001730*/
drha7e61d82011-03-12 17:02:57 +00001731static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001732 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001733 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001734 struct flock lock;
1735 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001736
drh054889e2005-11-30 03:20:31 +00001737 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001738 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001739 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001740 getpid()));
drha6abd042004-06-09 17:37:22 +00001741
drh308c2a52010-05-14 11:30:18 +00001742 assert( eFileLock<=SHARED_LOCK );
1743 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001744 return SQLITE_OK;
1745 }
drh6c7d5c52008-11-21 20:32:33 +00001746 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001747 pInode = pFile->pInode;
1748 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001749 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001750 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001751
drhd3d8c042012-05-29 17:02:40 +00001752#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001753 /* When reducing a lock such that other processes can start
1754 ** reading the database file again, make sure that the
1755 ** transaction counter was updated if any part of the database
1756 ** file changed. If the transaction counter is not updated,
1757 ** other connections to the same file might not realize that
1758 ** the file has changed and hence might not know to flush their
1759 ** cache. The use of a stale cache can lead to database corruption.
1760 */
drh8f941bc2009-01-14 23:03:40 +00001761 pFile->inNormalWrite = 0;
1762#endif
1763
drh7ed97b92010-01-20 13:07:21 +00001764 /* downgrading to a shared lock on NFS involves clearing the write lock
1765 ** before establishing the readlock - to avoid a race condition we downgrade
1766 ** the lock in 2 blocks, so that part of the range will be covered by a
1767 ** write lock until the rest is covered by a read lock:
1768 ** 1: [WWWWW]
1769 ** 2: [....W]
1770 ** 3: [RRRRW]
1771 ** 4: [RRRR.]
1772 */
drh308c2a52010-05-14 11:30:18 +00001773 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001774#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001775 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001776 assert( handleNFSUnlock==0 );
1777#endif
1778#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001779 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001780 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001781 off_t divSize = SHARED_SIZE - 1;
1782
1783 lock.l_type = F_UNLCK;
1784 lock.l_whence = SEEK_SET;
1785 lock.l_start = SHARED_FIRST;
1786 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001787 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001788 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001789 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001790 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001791 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001792 }
1793 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001794 }
drh7ed97b92010-01-20 13:07:21 +00001795 lock.l_type = F_RDLCK;
1796 lock.l_whence = SEEK_SET;
1797 lock.l_start = SHARED_FIRST;
1798 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001799 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001800 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001801 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1802 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001803 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001804 }
1805 goto end_unlock;
1806 }
1807 lock.l_type = F_UNLCK;
1808 lock.l_whence = SEEK_SET;
1809 lock.l_start = SHARED_FIRST+divSize;
1810 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001811 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001812 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001813 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001814 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001815 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001816 }
1817 goto end_unlock;
1818 }
drh30f776f2011-02-25 03:25:07 +00001819 }else
1820#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1821 {
drh7ed97b92010-01-20 13:07:21 +00001822 lock.l_type = F_RDLCK;
1823 lock.l_whence = SEEK_SET;
1824 lock.l_start = SHARED_FIRST;
1825 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001826 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001827 /* In theory, the call to unixFileLock() cannot fail because another
1828 ** process is holding an incompatible lock. If it does, this
1829 ** indicates that the other process is not following the locking
1830 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1831 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1832 ** an assert to fail). */
1833 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001834 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001835 goto end_unlock;
1836 }
drh9c105bb2004-10-02 20:38:28 +00001837 }
1838 }
drhbbd42a62004-05-22 17:41:58 +00001839 lock.l_type = F_UNLCK;
1840 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001841 lock.l_start = PENDING_BYTE;
1842 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001843 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001844 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001845 }else{
danea83bc62011-04-01 11:56:32 +00001846 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001847 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001848 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001849 }
drhbbd42a62004-05-22 17:41:58 +00001850 }
drh308c2a52010-05-14 11:30:18 +00001851 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001852 /* Decrement the shared lock counter. Release the lock using an
1853 ** OS call only when all threads in this same process have released
1854 ** the lock.
1855 */
drh8af6c222010-05-14 12:43:01 +00001856 pInode->nShared--;
1857 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001858 lock.l_type = F_UNLCK;
1859 lock.l_whence = SEEK_SET;
1860 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001861 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001862 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001863 }else{
danea83bc62011-04-01 11:56:32 +00001864 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001865 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001866 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001867 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001868 }
drha6abd042004-06-09 17:37:22 +00001869 }
1870
drhbbd42a62004-05-22 17:41:58 +00001871 /* Decrement the count of locks against this same file. When the
1872 ** count reaches zero, close any other file descriptors whose close
1873 ** was deferred because of outstanding locks.
1874 */
drh8af6c222010-05-14 12:43:01 +00001875 pInode->nLock--;
1876 assert( pInode->nLock>=0 );
1877 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001878 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001879 }
1880 }
drhf2f105d2012-08-20 15:53:54 +00001881
aswift5b1a2562008-08-22 00:22:35 +00001882end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001883 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001884 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001885 return rc;
drhbbd42a62004-05-22 17:41:58 +00001886}
1887
1888/*
drh308c2a52010-05-14 11:30:18 +00001889** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001890** must be either NO_LOCK or SHARED_LOCK.
1891**
1892** If the locking level of the file descriptor is already at or below
1893** the requested locking level, this routine is a no-op.
1894*/
drh308c2a52010-05-14 11:30:18 +00001895static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001896#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001897 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001898#endif
drha7e61d82011-03-12 17:02:57 +00001899 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001900}
1901
mistachkine98844f2013-08-24 00:59:24 +00001902#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001903static int unixMapfile(unixFile *pFd, i64 nByte);
1904static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001905#endif
danf23da962013-03-23 21:00:41 +00001906
drh7ed97b92010-01-20 13:07:21 +00001907/*
danielk1977e339d652008-06-28 11:23:00 +00001908** This function performs the parts of the "close file" operation
1909** common to all locking schemes. It closes the directory and file
1910** handles, if they are valid, and sets all fields of the unixFile
1911** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001912**
1913** It is *not* necessary to hold the mutex when this routine is called,
1914** even on VxWorks. A mutex will be acquired on VxWorks by the
1915** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001916*/
1917static int closeUnixFile(sqlite3_file *id){
1918 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001919#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001920 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001921#endif
dan661d71a2011-03-30 19:08:03 +00001922 if( pFile->h>=0 ){
1923 robust_close(pFile, pFile->h, __LINE__);
1924 pFile->h = -1;
1925 }
1926#if OS_VXWORKS
1927 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001928 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001929 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001930 }
1931 vxworksReleaseFileId(pFile->pId);
1932 pFile->pId = 0;
1933 }
1934#endif
drh0bdbc902014-06-16 18:35:06 +00001935#ifdef SQLITE_UNLINK_AFTER_CLOSE
1936 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1937 osUnlink(pFile->zPath);
1938 sqlite3_free(*(char**)&pFile->zPath);
1939 pFile->zPath = 0;
1940 }
1941#endif
dan661d71a2011-03-30 19:08:03 +00001942 OSTRACE(("CLOSE %-3d\n", pFile->h));
1943 OpenCounter(-1);
1944 sqlite3_free(pFile->pUnused);
1945 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001946 return SQLITE_OK;
1947}
1948
1949/*
danielk1977e3026632004-06-22 11:29:02 +00001950** Close a file.
1951*/
danielk197762079062007-08-15 17:08:46 +00001952static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001953 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001954 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001955 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001956 unixUnlock(id, NO_LOCK);
1957 unixEnterMutex();
1958
1959 /* unixFile.pInode is always valid here. Otherwise, a different close
1960 ** routine (e.g. nolockClose()) would be called instead.
1961 */
1962 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1963 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1964 /* If there are outstanding locks, do not actually close the file just
1965 ** yet because that would clear those locks. Instead, add the file
1966 ** descriptor to pInode->pUnused list. It will be automatically closed
1967 ** when the last lock is cleared.
1968 */
1969 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001970 }
dan661d71a2011-03-30 19:08:03 +00001971 releaseInodeInfo(pFile);
1972 rc = closeUnixFile(id);
1973 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001974 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001975}
1976
drh734c9862008-11-28 15:37:20 +00001977/************** End of the posix advisory lock implementation *****************
1978******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001979
drh734c9862008-11-28 15:37:20 +00001980/******************************************************************************
1981****************************** No-op Locking **********************************
1982**
1983** Of the various locking implementations available, this is by far the
1984** simplest: locking is ignored. No attempt is made to lock the database
1985** file for reading or writing.
1986**
1987** This locking mode is appropriate for use on read-only databases
1988** (ex: databases that are burned into CD-ROM, for example.) It can
1989** also be used if the application employs some external mechanism to
1990** prevent simultaneous access of the same database by two or more
1991** database connections. But there is a serious risk of database
1992** corruption if this locking mode is used in situations where multiple
1993** database connections are accessing the same database file at the same
1994** time and one or more of those connections are writing.
1995*/
drhbfe66312006-10-03 17:40:40 +00001996
drh734c9862008-11-28 15:37:20 +00001997static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1998 UNUSED_PARAMETER(NotUsed);
1999 *pResOut = 0;
2000 return SQLITE_OK;
2001}
drh734c9862008-11-28 15:37:20 +00002002static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2003 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2004 return SQLITE_OK;
2005}
drh734c9862008-11-28 15:37:20 +00002006static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2007 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2008 return SQLITE_OK;
2009}
2010
2011/*
drh9b35ea62008-11-29 02:20:26 +00002012** Close the file.
drh734c9862008-11-28 15:37:20 +00002013*/
2014static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002015 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002016}
2017
2018/******************* End of the no-op lock implementation *********************
2019******************************************************************************/
2020
2021/******************************************************************************
2022************************* Begin dot-file Locking ******************************
2023**
mistachkin48864df2013-03-21 21:20:32 +00002024** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002025** files (really a directory) to control access to the database. This works
2026** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002027**
2028** (1) There is zero concurrency. A single reader blocks all other
2029** connections from reading or writing the database.
2030**
2031** (2) An application crash or power loss can leave stale lock files
2032** sitting around that need to be cleared manually.
2033**
2034** Nevertheless, a dotlock is an appropriate locking mode for use if no
2035** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002036**
drh9ef6bc42011-11-04 02:24:02 +00002037** Dotfile locking works by creating a subdirectory in the same directory as
2038** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002039** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002040** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002041*/
2042
2043/*
2044** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002045** lock directory.
drh734c9862008-11-28 15:37:20 +00002046*/
2047#define DOTLOCK_SUFFIX ".lock"
2048
drh7708e972008-11-29 00:56:52 +00002049/*
2050** This routine checks if there is a RESERVED lock held on the specified
2051** file by this or any other process. If such a lock is held, set *pResOut
2052** to a non-zero value otherwise *pResOut is set to zero. The return value
2053** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2054**
2055** In dotfile locking, either a lock exists or it does not. So in this
2056** variation of CheckReservedLock(), *pResOut is set to true if any lock
2057** is held on the file and false if the file is unlocked.
2058*/
drh734c9862008-11-28 15:37:20 +00002059static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2060 int rc = SQLITE_OK;
2061 int reserved = 0;
2062 unixFile *pFile = (unixFile*)id;
2063
2064 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2065
2066 assert( pFile );
2067
2068 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002069 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002070 /* Either this connection or some other connection in the same process
2071 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002072 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002073 }else{
2074 /* The lock is held if and only if the lockfile exists */
2075 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002076 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002077 }
drh308c2a52010-05-14 11:30:18 +00002078 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002079 *pResOut = reserved;
2080 return rc;
2081}
2082
drh7708e972008-11-29 00:56:52 +00002083/*
drh308c2a52010-05-14 11:30:18 +00002084** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002085** of the following:
2086**
2087** (1) SHARED_LOCK
2088** (2) RESERVED_LOCK
2089** (3) PENDING_LOCK
2090** (4) EXCLUSIVE_LOCK
2091**
2092** Sometimes when requesting one lock state, additional lock states
2093** are inserted in between. The locking might fail on one of the later
2094** transitions leaving the lock state different from what it started but
2095** still short of its goal. The following chart shows the allowed
2096** transitions and the inserted intermediate states:
2097**
2098** UNLOCKED -> SHARED
2099** SHARED -> RESERVED
2100** SHARED -> (PENDING) -> EXCLUSIVE
2101** RESERVED -> (PENDING) -> EXCLUSIVE
2102** PENDING -> EXCLUSIVE
2103**
2104** This routine will only increase a lock. Use the sqlite3OsUnlock()
2105** routine to lower a locking level.
2106**
2107** With dotfile locking, we really only support state (4): EXCLUSIVE.
2108** But we track the other locking levels internally.
2109*/
drh308c2a52010-05-14 11:30:18 +00002110static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002111 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002112 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002113 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002114
drh7708e972008-11-29 00:56:52 +00002115
2116 /* If we have any lock, then the lock file already exists. All we have
2117 ** to do is adjust our internal record of the lock level.
2118 */
drh308c2a52010-05-14 11:30:18 +00002119 if( pFile->eFileLock > NO_LOCK ){
2120 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002121 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002122#ifdef HAVE_UTIME
2123 utime(zLockFile, NULL);
2124#else
drh734c9862008-11-28 15:37:20 +00002125 utimes(zLockFile, NULL);
2126#endif
drh7708e972008-11-29 00:56:52 +00002127 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002128 }
2129
2130 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002131 rc = osMkdir(zLockFile, 0777);
2132 if( rc<0 ){
2133 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002134 int tErrno = errno;
2135 if( EEXIST == tErrno ){
2136 rc = SQLITE_BUSY;
2137 } else {
2138 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2139 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002140 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002141 }
2142 }
drh7708e972008-11-29 00:56:52 +00002143 return rc;
drh734c9862008-11-28 15:37:20 +00002144 }
drh734c9862008-11-28 15:37:20 +00002145
2146 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002147 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002148 return rc;
2149}
2150
drh7708e972008-11-29 00:56:52 +00002151/*
drh308c2a52010-05-14 11:30:18 +00002152** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002153** must be either NO_LOCK or SHARED_LOCK.
2154**
2155** If the locking level of the file descriptor is already at or below
2156** the requested locking level, this routine is a no-op.
2157**
2158** When the locking level reaches NO_LOCK, delete the lock file.
2159*/
drh308c2a52010-05-14 11:30:18 +00002160static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002161 unixFile *pFile = (unixFile*)id;
2162 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002163 int rc;
drh734c9862008-11-28 15:37:20 +00002164
2165 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002166 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002167 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002168 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002169
2170 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002171 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002172 return SQLITE_OK;
2173 }
drh7708e972008-11-29 00:56:52 +00002174
2175 /* To downgrade to shared, simply update our internal notion of the
2176 ** lock state. No need to mess with the file on disk.
2177 */
drh308c2a52010-05-14 11:30:18 +00002178 if( eFileLock==SHARED_LOCK ){
2179 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002180 return SQLITE_OK;
2181 }
2182
drh7708e972008-11-29 00:56:52 +00002183 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002184 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002185 rc = osRmdir(zLockFile);
2186 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2187 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002188 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002189 rc = 0;
drh734c9862008-11-28 15:37:20 +00002190 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002191 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002192 }
2193 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002194 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002195 }
2196 return rc;
2197 }
drh308c2a52010-05-14 11:30:18 +00002198 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002199 return SQLITE_OK;
2200}
2201
2202/*
drh9b35ea62008-11-29 02:20:26 +00002203** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002204*/
2205static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002206 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002207 if( id ){
2208 unixFile *pFile = (unixFile*)id;
2209 dotlockUnlock(id, NO_LOCK);
2210 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002211 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002212 }
drh734c9862008-11-28 15:37:20 +00002213 return rc;
2214}
2215/****************** End of the dot-file lock implementation *******************
2216******************************************************************************/
2217
2218/******************************************************************************
2219************************** Begin flock Locking ********************************
2220**
2221** Use the flock() system call to do file locking.
2222**
drh6b9d6dd2008-12-03 19:34:47 +00002223** flock() locking is like dot-file locking in that the various
2224** fine-grain locking levels supported by SQLite are collapsed into
2225** a single exclusive lock. In other words, SHARED, RESERVED, and
2226** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2227** still works when you do this, but concurrency is reduced since
2228** only a single process can be reading the database at a time.
2229**
drh734c9862008-11-28 15:37:20 +00002230** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2231** compiling for VXWORKS.
2232*/
2233#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002234
drh6b9d6dd2008-12-03 19:34:47 +00002235/*
drhff812312011-02-23 13:33:46 +00002236** Retry flock() calls that fail with EINTR
2237*/
2238#ifdef EINTR
2239static int robust_flock(int fd, int op){
2240 int rc;
2241 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2242 return rc;
2243}
2244#else
drh5c819272011-02-23 14:00:12 +00002245# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002246#endif
2247
2248
2249/*
drh6b9d6dd2008-12-03 19:34:47 +00002250** This routine checks if there is a RESERVED lock held on the specified
2251** file by this or any other process. If such a lock is held, set *pResOut
2252** to a non-zero value otherwise *pResOut is set to zero. The return value
2253** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2254*/
drh734c9862008-11-28 15:37:20 +00002255static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2256 int rc = SQLITE_OK;
2257 int reserved = 0;
2258 unixFile *pFile = (unixFile*)id;
2259
2260 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2261
2262 assert( pFile );
2263
2264 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002265 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002266 reserved = 1;
2267 }
2268
2269 /* Otherwise see if some other process holds it. */
2270 if( !reserved ){
2271 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002272 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002273 if( !lrc ){
2274 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002275 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002276 if ( lrc ) {
2277 int tErrno = errno;
2278 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002279 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002280 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002281 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002282 rc = lrc;
2283 }
2284 }
2285 } else {
2286 int tErrno = errno;
2287 reserved = 1;
2288 /* someone else might have it reserved */
2289 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2290 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002291 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002292 rc = lrc;
2293 }
2294 }
2295 }
drh308c2a52010-05-14 11:30:18 +00002296 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002297
2298#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2299 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2300 rc = SQLITE_OK;
2301 reserved=1;
2302 }
2303#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2304 *pResOut = reserved;
2305 return rc;
2306}
2307
drh6b9d6dd2008-12-03 19:34:47 +00002308/*
drh308c2a52010-05-14 11:30:18 +00002309** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002310** of the following:
2311**
2312** (1) SHARED_LOCK
2313** (2) RESERVED_LOCK
2314** (3) PENDING_LOCK
2315** (4) EXCLUSIVE_LOCK
2316**
2317** Sometimes when requesting one lock state, additional lock states
2318** are inserted in between. The locking might fail on one of the later
2319** transitions leaving the lock state different from what it started but
2320** still short of its goal. The following chart shows the allowed
2321** transitions and the inserted intermediate states:
2322**
2323** UNLOCKED -> SHARED
2324** SHARED -> RESERVED
2325** SHARED -> (PENDING) -> EXCLUSIVE
2326** RESERVED -> (PENDING) -> EXCLUSIVE
2327** PENDING -> EXCLUSIVE
2328**
2329** flock() only really support EXCLUSIVE locks. We track intermediate
2330** lock states in the sqlite3_file structure, but all locks SHARED or
2331** above are really EXCLUSIVE locks and exclude all other processes from
2332** access the file.
2333**
2334** This routine will only increase a lock. Use the sqlite3OsUnlock()
2335** routine to lower a locking level.
2336*/
drh308c2a52010-05-14 11:30:18 +00002337static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002338 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002339 unixFile *pFile = (unixFile*)id;
2340
2341 assert( pFile );
2342
2343 /* if we already have a lock, it is exclusive.
2344 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002345 if (pFile->eFileLock > NO_LOCK) {
2346 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002347 return SQLITE_OK;
2348 }
2349
2350 /* grab an exclusive lock */
2351
drhff812312011-02-23 13:33:46 +00002352 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002353 int tErrno = errno;
2354 /* didn't get, must be busy */
2355 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2356 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002357 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002358 }
2359 } else {
2360 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002361 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002362 }
drh308c2a52010-05-14 11:30:18 +00002363 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2364 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002365#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2366 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2367 rc = SQLITE_BUSY;
2368 }
2369#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2370 return rc;
2371}
2372
drh6b9d6dd2008-12-03 19:34:47 +00002373
2374/*
drh308c2a52010-05-14 11:30:18 +00002375** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002376** must be either NO_LOCK or SHARED_LOCK.
2377**
2378** If the locking level of the file descriptor is already at or below
2379** the requested locking level, this routine is a no-op.
2380*/
drh308c2a52010-05-14 11:30:18 +00002381static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002382 unixFile *pFile = (unixFile*)id;
2383
2384 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002385 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2386 pFile->eFileLock, getpid()));
2387 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002388
2389 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002390 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002391 return SQLITE_OK;
2392 }
2393
2394 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002395 if (eFileLock==SHARED_LOCK) {
2396 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002397 return SQLITE_OK;
2398 }
2399
2400 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002401 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002402#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002403 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002404#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002405 return SQLITE_IOERR_UNLOCK;
2406 }else{
drh308c2a52010-05-14 11:30:18 +00002407 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002408 return SQLITE_OK;
2409 }
2410}
2411
2412/*
2413** Close a file.
2414*/
2415static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002416 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002417 if( id ){
2418 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002419 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002420 }
drh5a05be12012-10-09 18:51:44 +00002421 return rc;
drh734c9862008-11-28 15:37:20 +00002422}
2423
2424#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2425
2426/******************* End of the flock lock implementation *********************
2427******************************************************************************/
2428
2429/******************************************************************************
2430************************ Begin Named Semaphore Locking ************************
2431**
2432** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002433**
2434** Semaphore locking is like dot-lock and flock in that it really only
2435** supports EXCLUSIVE locking. Only a single process can read or write
2436** the database file at a time. This reduces potential concurrency, but
2437** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002438*/
2439#if OS_VXWORKS
2440
drh6b9d6dd2008-12-03 19:34:47 +00002441/*
2442** This routine checks if there is a RESERVED lock held on the specified
2443** file by this or any other process. If such a lock is held, set *pResOut
2444** to a non-zero value otherwise *pResOut is set to zero. The return value
2445** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2446*/
drh8cd5b252015-03-02 22:06:43 +00002447static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002448 int rc = SQLITE_OK;
2449 int reserved = 0;
2450 unixFile *pFile = (unixFile*)id;
2451
2452 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2453
2454 assert( pFile );
2455
2456 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002457 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002458 reserved = 1;
2459 }
2460
2461 /* Otherwise see if some other process holds it. */
2462 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002463 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002464
2465 if( sem_trywait(pSem)==-1 ){
2466 int tErrno = errno;
2467 if( EAGAIN != tErrno ){
2468 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002469 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002470 } else {
2471 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002472 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002473 }
2474 }else{
2475 /* we could have it if we want it */
2476 sem_post(pSem);
2477 }
2478 }
drh308c2a52010-05-14 11:30:18 +00002479 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002480
2481 *pResOut = reserved;
2482 return rc;
2483}
2484
drh6b9d6dd2008-12-03 19:34:47 +00002485/*
drh308c2a52010-05-14 11:30:18 +00002486** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002487** of the following:
2488**
2489** (1) SHARED_LOCK
2490** (2) RESERVED_LOCK
2491** (3) PENDING_LOCK
2492** (4) EXCLUSIVE_LOCK
2493**
2494** Sometimes when requesting one lock state, additional lock states
2495** are inserted in between. The locking might fail on one of the later
2496** transitions leaving the lock state different from what it started but
2497** still short of its goal. The following chart shows the allowed
2498** transitions and the inserted intermediate states:
2499**
2500** UNLOCKED -> SHARED
2501** SHARED -> RESERVED
2502** SHARED -> (PENDING) -> EXCLUSIVE
2503** RESERVED -> (PENDING) -> EXCLUSIVE
2504** PENDING -> EXCLUSIVE
2505**
2506** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2507** lock states in the sqlite3_file structure, but all locks SHARED or
2508** above are really EXCLUSIVE locks and exclude all other processes from
2509** access the file.
2510**
2511** This routine will only increase a lock. Use the sqlite3OsUnlock()
2512** routine to lower a locking level.
2513*/
drh8cd5b252015-03-02 22:06:43 +00002514static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002515 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002516 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002517 int rc = SQLITE_OK;
2518
2519 /* if we already have a lock, it is exclusive.
2520 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002521 if (pFile->eFileLock > NO_LOCK) {
2522 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002523 rc = SQLITE_OK;
2524 goto sem_end_lock;
2525 }
2526
2527 /* lock semaphore now but bail out when already locked. */
2528 if( sem_trywait(pSem)==-1 ){
2529 rc = SQLITE_BUSY;
2530 goto sem_end_lock;
2531 }
2532
2533 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002534 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002535
2536 sem_end_lock:
2537 return rc;
2538}
2539
drh6b9d6dd2008-12-03 19:34:47 +00002540/*
drh308c2a52010-05-14 11:30:18 +00002541** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002542** must be either NO_LOCK or SHARED_LOCK.
2543**
2544** If the locking level of the file descriptor is already at or below
2545** the requested locking level, this routine is a no-op.
2546*/
drh8cd5b252015-03-02 22:06:43 +00002547static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002548 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002549 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002550
2551 assert( pFile );
2552 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002553 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002554 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002555 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002556
2557 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002558 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002559 return SQLITE_OK;
2560 }
2561
2562 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002563 if (eFileLock==SHARED_LOCK) {
2564 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002565 return SQLITE_OK;
2566 }
2567
2568 /* no, really unlock. */
2569 if ( sem_post(pSem)==-1 ) {
2570 int rc, tErrno = errno;
2571 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2572 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002573 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002574 }
2575 return rc;
2576 }
drh308c2a52010-05-14 11:30:18 +00002577 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002578 return SQLITE_OK;
2579}
2580
2581/*
2582 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002583 */
drh8cd5b252015-03-02 22:06:43 +00002584static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002585 if( id ){
2586 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002587 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002588 assert( pFile );
2589 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002590 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002591 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002592 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002593 }
2594 return SQLITE_OK;
2595}
2596
2597#endif /* OS_VXWORKS */
2598/*
2599** Named semaphore locking is only available on VxWorks.
2600**
2601*************** End of the named semaphore lock implementation ****************
2602******************************************************************************/
2603
2604
2605/******************************************************************************
2606*************************** Begin AFP Locking *********************************
2607**
2608** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2609** on Apple Macintosh computers - both OS9 and OSX.
2610**
2611** Third-party implementations of AFP are available. But this code here
2612** only works on OSX.
2613*/
2614
drhd2cb50b2009-01-09 21:41:17 +00002615#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002616/*
2617** The afpLockingContext structure contains all afp lock specific state
2618*/
drhbfe66312006-10-03 17:40:40 +00002619typedef struct afpLockingContext afpLockingContext;
2620struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002621 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002622 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002623};
2624
2625struct ByteRangeLockPB2
2626{
2627 unsigned long long offset; /* offset to first byte to lock */
2628 unsigned long long length; /* nbr of bytes to lock */
2629 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2630 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2631 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2632 int fd; /* file desc to assoc this lock with */
2633};
2634
drhfd131da2007-08-07 17:13:03 +00002635#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002636
drh6b9d6dd2008-12-03 19:34:47 +00002637/*
2638** This is a utility for setting or clearing a bit-range lock on an
2639** AFP filesystem.
2640**
2641** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2642*/
2643static int afpSetLock(
2644 const char *path, /* Name of the file to be locked or unlocked */
2645 unixFile *pFile, /* Open file descriptor on path */
2646 unsigned long long offset, /* First byte to be locked */
2647 unsigned long long length, /* Number of bytes to lock */
2648 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002649){
drh6b9d6dd2008-12-03 19:34:47 +00002650 struct ByteRangeLockPB2 pb;
2651 int err;
drhbfe66312006-10-03 17:40:40 +00002652
2653 pb.unLockFlag = setLockFlag ? 0 : 1;
2654 pb.startEndFlag = 0;
2655 pb.offset = offset;
2656 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002657 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002658
drh308c2a52010-05-14 11:30:18 +00002659 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002660 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002661 offset, length));
drhbfe66312006-10-03 17:40:40 +00002662 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2663 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002664 int rc;
2665 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002666 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2667 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002668#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2669 rc = SQLITE_BUSY;
2670#else
drh734c9862008-11-28 15:37:20 +00002671 rc = sqliteErrorFromPosixError(tErrno,
2672 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002673#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002674 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002675 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002676 }
2677 return rc;
drhbfe66312006-10-03 17:40:40 +00002678 } else {
aswift5b1a2562008-08-22 00:22:35 +00002679 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002680 }
2681}
2682
drh6b9d6dd2008-12-03 19:34:47 +00002683/*
2684** This routine checks if there is a RESERVED lock held on the specified
2685** file by this or any other process. If such a lock is held, set *pResOut
2686** to a non-zero value otherwise *pResOut is set to zero. The return value
2687** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2688*/
danielk1977e339d652008-06-28 11:23:00 +00002689static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002690 int rc = SQLITE_OK;
2691 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002692 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002693 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002694
aswift5b1a2562008-08-22 00:22:35 +00002695 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2696
2697 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002698 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002699 if( context->reserved ){
2700 *pResOut = 1;
2701 return SQLITE_OK;
2702 }
drh8af6c222010-05-14 12:43:01 +00002703 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002704
2705 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002706 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002707 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002708 }
2709
2710 /* Otherwise see if some other process holds it.
2711 */
aswift5b1a2562008-08-22 00:22:35 +00002712 if( !reserved ){
2713 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002714 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002715 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002716 /* if we succeeded in taking the reserved lock, unlock it to restore
2717 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002718 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002719 } else {
2720 /* if we failed to get the lock then someone else must have it */
2721 reserved = 1;
2722 }
2723 if( IS_LOCK_ERROR(lrc) ){
2724 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002725 }
2726 }
drhbfe66312006-10-03 17:40:40 +00002727
drh7ed97b92010-01-20 13:07:21 +00002728 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002729 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002730
2731 *pResOut = reserved;
2732 return rc;
drhbfe66312006-10-03 17:40:40 +00002733}
2734
drh6b9d6dd2008-12-03 19:34:47 +00002735/*
drh308c2a52010-05-14 11:30:18 +00002736** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002737** of the following:
2738**
2739** (1) SHARED_LOCK
2740** (2) RESERVED_LOCK
2741** (3) PENDING_LOCK
2742** (4) EXCLUSIVE_LOCK
2743**
2744** Sometimes when requesting one lock state, additional lock states
2745** are inserted in between. The locking might fail on one of the later
2746** transitions leaving the lock state different from what it started but
2747** still short of its goal. The following chart shows the allowed
2748** transitions and the inserted intermediate states:
2749**
2750** UNLOCKED -> SHARED
2751** SHARED -> RESERVED
2752** SHARED -> (PENDING) -> EXCLUSIVE
2753** RESERVED -> (PENDING) -> EXCLUSIVE
2754** PENDING -> EXCLUSIVE
2755**
2756** This routine will only increase a lock. Use the sqlite3OsUnlock()
2757** routine to lower a locking level.
2758*/
drh308c2a52010-05-14 11:30:18 +00002759static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002760 int rc = SQLITE_OK;
2761 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002762 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002763 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002764
2765 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002766 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2767 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002768 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002769
drhbfe66312006-10-03 17:40:40 +00002770 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002771 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002772 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002773 */
drh308c2a52010-05-14 11:30:18 +00002774 if( pFile->eFileLock>=eFileLock ){
2775 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2776 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002777 return SQLITE_OK;
2778 }
2779
2780 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002781 ** (1) We never move from unlocked to anything higher than shared lock.
2782 ** (2) SQLite never explicitly requests a pendig lock.
2783 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002784 */
drh308c2a52010-05-14 11:30:18 +00002785 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2786 assert( eFileLock!=PENDING_LOCK );
2787 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002788
drh8af6c222010-05-14 12:43:01 +00002789 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002790 */
drh6c7d5c52008-11-21 20:32:33 +00002791 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002792 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002793
2794 /* If some thread using this PID has a lock via a different unixFile*
2795 ** handle that precludes the requested lock, return BUSY.
2796 */
drh8af6c222010-05-14 12:43:01 +00002797 if( (pFile->eFileLock!=pInode->eFileLock &&
2798 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002799 ){
2800 rc = SQLITE_BUSY;
2801 goto afp_end_lock;
2802 }
2803
2804 /* If a SHARED lock is requested, and some thread using this PID already
2805 ** has a SHARED or RESERVED lock, then increment reference counts and
2806 ** return SQLITE_OK.
2807 */
drh308c2a52010-05-14 11:30:18 +00002808 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002809 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002810 assert( eFileLock==SHARED_LOCK );
2811 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002812 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002813 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002814 pInode->nShared++;
2815 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002816 goto afp_end_lock;
2817 }
drhbfe66312006-10-03 17:40:40 +00002818
2819 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002820 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2821 ** be released.
2822 */
drh308c2a52010-05-14 11:30:18 +00002823 if( eFileLock==SHARED_LOCK
2824 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002825 ){
2826 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002827 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002828 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002829 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002830 goto afp_end_lock;
2831 }
2832 }
2833
2834 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002835 ** operating system calls for the specified lock.
2836 */
drh308c2a52010-05-14 11:30:18 +00002837 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002838 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002839 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002840
drh8af6c222010-05-14 12:43:01 +00002841 assert( pInode->nShared==0 );
2842 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002843
2844 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002845 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002846 /* note that the quality of the randomness doesn't matter that much */
2847 lk = random();
drh8af6c222010-05-14 12:43:01 +00002848 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002849 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002850 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002851 if( IS_LOCK_ERROR(lrc1) ){
2852 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002853 }
aswift5b1a2562008-08-22 00:22:35 +00002854 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002855 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002856
aswift5b1a2562008-08-22 00:22:35 +00002857 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002858 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002859 rc = lrc1;
2860 goto afp_end_lock;
2861 } else if( IS_LOCK_ERROR(lrc2) ){
2862 rc = lrc2;
2863 goto afp_end_lock;
2864 } else if( lrc1 != SQLITE_OK ) {
2865 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002866 } else {
drh308c2a52010-05-14 11:30:18 +00002867 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002868 pInode->nLock++;
2869 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002870 }
drh8af6c222010-05-14 12:43:01 +00002871 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002872 /* We are trying for an exclusive lock but another thread in this
2873 ** same process is still holding a shared lock. */
2874 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002875 }else{
2876 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2877 ** assumed that there is a SHARED or greater lock on the file
2878 ** already.
2879 */
2880 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002881 assert( 0!=pFile->eFileLock );
2882 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002883 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002884 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002885 if( !failed ){
2886 context->reserved = 1;
2887 }
drhbfe66312006-10-03 17:40:40 +00002888 }
drh308c2a52010-05-14 11:30:18 +00002889 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002890 /* Acquire an EXCLUSIVE lock */
2891
2892 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002893 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002894 */
drh6b9d6dd2008-12-03 19:34:47 +00002895 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002896 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002897 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002898 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002899 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002900 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002901 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002902 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002903 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2904 ** a critical I/O error
2905 */
2906 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2907 SQLITE_IOERR_LOCK;
2908 goto afp_end_lock;
2909 }
2910 }else{
aswift5b1a2562008-08-22 00:22:35 +00002911 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002912 }
2913 }
aswift5b1a2562008-08-22 00:22:35 +00002914 if( failed ){
2915 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002916 }
2917 }
2918
2919 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002920 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002921 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002922 }else if( eFileLock==EXCLUSIVE_LOCK ){
2923 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002924 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002925 }
2926
2927afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002928 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002929 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2930 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002931 return rc;
2932}
2933
2934/*
drh308c2a52010-05-14 11:30:18 +00002935** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002936** must be either NO_LOCK or SHARED_LOCK.
2937**
2938** If the locking level of the file descriptor is already at or below
2939** the requested locking level, this routine is a no-op.
2940*/
drh308c2a52010-05-14 11:30:18 +00002941static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002942 int rc = SQLITE_OK;
2943 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002944 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002945 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2946 int skipShared = 0;
2947#ifdef SQLITE_TEST
2948 int h = pFile->h;
2949#endif
drhbfe66312006-10-03 17:40:40 +00002950
2951 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002952 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002953 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002954 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002955
drh308c2a52010-05-14 11:30:18 +00002956 assert( eFileLock<=SHARED_LOCK );
2957 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002958 return SQLITE_OK;
2959 }
drh6c7d5c52008-11-21 20:32:33 +00002960 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002961 pInode = pFile->pInode;
2962 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002963 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002964 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002965 SimulateIOErrorBenign(1);
2966 SimulateIOError( h=(-1) )
2967 SimulateIOErrorBenign(0);
2968
drhd3d8c042012-05-29 17:02:40 +00002969#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002970 /* When reducing a lock such that other processes can start
2971 ** reading the database file again, make sure that the
2972 ** transaction counter was updated if any part of the database
2973 ** file changed. If the transaction counter is not updated,
2974 ** other connections to the same file might not realize that
2975 ** the file has changed and hence might not know to flush their
2976 ** cache. The use of a stale cache can lead to database corruption.
2977 */
2978 assert( pFile->inNormalWrite==0
2979 || pFile->dbUpdate==0
2980 || pFile->transCntrChng==1 );
2981 pFile->inNormalWrite = 0;
2982#endif
aswiftaebf4132008-11-21 00:10:35 +00002983
drh308c2a52010-05-14 11:30:18 +00002984 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002985 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002986 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002987 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002988 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002989 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2990 } else {
2991 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002992 }
2993 }
drh308c2a52010-05-14 11:30:18 +00002994 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002995 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002996 }
drh308c2a52010-05-14 11:30:18 +00002997 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002998 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2999 if( !rc ){
3000 context->reserved = 0;
3001 }
aswiftaebf4132008-11-21 00:10:35 +00003002 }
drh8af6c222010-05-14 12:43:01 +00003003 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3004 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003005 }
aswiftaebf4132008-11-21 00:10:35 +00003006 }
drh308c2a52010-05-14 11:30:18 +00003007 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003008
drh7ed97b92010-01-20 13:07:21 +00003009 /* Decrement the shared lock counter. Release the lock using an
3010 ** OS call only when all threads in this same process have released
3011 ** the lock.
3012 */
drh8af6c222010-05-14 12:43:01 +00003013 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3014 pInode->nShared--;
3015 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003016 SimulateIOErrorBenign(1);
3017 SimulateIOError( h=(-1) )
3018 SimulateIOErrorBenign(0);
3019 if( !skipShared ){
3020 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3021 }
3022 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003023 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003024 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003025 }
3026 }
3027 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003028 pInode->nLock--;
3029 assert( pInode->nLock>=0 );
3030 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003031 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003032 }
3033 }
drhbfe66312006-10-03 17:40:40 +00003034 }
drh7ed97b92010-01-20 13:07:21 +00003035
drh6c7d5c52008-11-21 20:32:33 +00003036 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003037 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003038 return rc;
3039}
3040
3041/*
drh339eb0b2008-03-07 15:34:11 +00003042** Close a file & cleanup AFP specific locking context
3043*/
danielk1977e339d652008-06-28 11:23:00 +00003044static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003045 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003046 if( id ){
3047 unixFile *pFile = (unixFile*)id;
3048 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003049 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003050 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003051 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003052 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003053 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003054 ** the last lock is cleared.
3055 */
dan08da86a2009-08-21 17:18:03 +00003056 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003057 }
danb0ac3e32010-06-16 10:55:42 +00003058 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003059 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003060 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003061 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003062 }
drh7ed97b92010-01-20 13:07:21 +00003063 return rc;
drhbfe66312006-10-03 17:40:40 +00003064}
3065
drhd2cb50b2009-01-09 21:41:17 +00003066#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003067/*
3068** The code above is the AFP lock implementation. The code is specific
3069** to MacOSX and does not work on other unix platforms. No alternative
3070** is available. If you don't compile for a mac, then the "unix-afp"
3071** VFS is not available.
3072**
3073********************* End of the AFP lock implementation **********************
3074******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003075
drh7ed97b92010-01-20 13:07:21 +00003076/******************************************************************************
3077*************************** Begin NFS Locking ********************************/
3078
3079#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3080/*
drh308c2a52010-05-14 11:30:18 +00003081 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003082 ** must be either NO_LOCK or SHARED_LOCK.
3083 **
3084 ** If the locking level of the file descriptor is already at or below
3085 ** the requested locking level, this routine is a no-op.
3086 */
drh308c2a52010-05-14 11:30:18 +00003087static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003088 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003089}
3090
3091#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3092/*
3093** The code above is the NFS lock implementation. The code is specific
3094** to MacOSX and does not work on other unix platforms. No alternative
3095** is available.
3096**
3097********************* End of the NFS lock implementation **********************
3098******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003099
3100/******************************************************************************
3101**************** Non-locking sqlite3_file methods *****************************
3102**
3103** The next division contains implementations for all methods of the
3104** sqlite3_file object other than the locking methods. The locking
3105** methods were defined in divisions above (one locking method per
3106** division). Those methods that are common to all locking modes
3107** are gather together into this division.
3108*/
drhbfe66312006-10-03 17:40:40 +00003109
3110/*
drh734c9862008-11-28 15:37:20 +00003111** Seek to the offset passed as the second argument, then read cnt
3112** bytes into pBuf. Return the number of bytes actually read.
3113**
3114** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3115** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3116** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003117** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003118** See tickets #2741 and #2681.
3119**
3120** To avoid stomping the errno value on a failed read the lastErrno value
3121** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003122*/
drh734c9862008-11-28 15:37:20 +00003123static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3124 int got;
drh58024642011-11-07 18:16:00 +00003125 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003126#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003127 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003128#endif
drh734c9862008-11-28 15:37:20 +00003129 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003130 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003131 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003132 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003133 do{
drh734c9862008-11-28 15:37:20 +00003134#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003135 got = osPread(id->h, pBuf, cnt, offset);
3136 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003137#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003138 got = osPread64(id->h, pBuf, cnt, offset);
3139 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003140#else
drh58024642011-11-07 18:16:00 +00003141 newOffset = lseek(id->h, offset, SEEK_SET);
3142 SimulateIOError( newOffset-- );
3143 if( newOffset!=offset ){
3144 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003145 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003146 }else{
drh4bf66fd2015-02-19 02:43:02 +00003147 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003148 }
3149 return -1;
drh734c9862008-11-28 15:37:20 +00003150 }
drh58024642011-11-07 18:16:00 +00003151 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003152#endif
drh58024642011-11-07 18:16:00 +00003153 if( got==cnt ) break;
3154 if( got<0 ){
3155 if( errno==EINTR ){ got = 1; continue; }
3156 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003157 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003158 break;
3159 }else if( got>0 ){
3160 cnt -= got;
3161 offset += got;
3162 prior += got;
3163 pBuf = (void*)(got + (char*)pBuf);
3164 }
3165 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003166 TIMER_END;
drh58024642011-11-07 18:16:00 +00003167 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3168 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3169 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003170}
3171
3172/*
drh734c9862008-11-28 15:37:20 +00003173** Read data from a file into a buffer. Return SQLITE_OK if all
3174** bytes were read successfully and SQLITE_IOERR if anything goes
3175** wrong.
drh339eb0b2008-03-07 15:34:11 +00003176*/
drh734c9862008-11-28 15:37:20 +00003177static int unixRead(
3178 sqlite3_file *id,
3179 void *pBuf,
3180 int amt,
3181 sqlite3_int64 offset
3182){
dan08da86a2009-08-21 17:18:03 +00003183 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003184 int got;
3185 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003186 assert( offset>=0 );
3187 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003188
dan08da86a2009-08-21 17:18:03 +00003189 /* If this is a database file (not a journal, master-journal or temp
3190 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003191#if 0
dane946c392009-08-22 11:39:46 +00003192 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003193 || offset>=PENDING_BYTE+512
3194 || offset+amt<=PENDING_BYTE
3195 );
dan7c246102010-04-12 19:00:29 +00003196#endif
drh08c6d442009-02-09 17:34:07 +00003197
drh9b4c59f2013-04-15 17:03:42 +00003198#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003199 /* Deal with as much of this read request as possible by transfering
3200 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003201 if( offset<pFile->mmapSize ){
3202 if( offset+amt <= pFile->mmapSize ){
3203 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3204 return SQLITE_OK;
3205 }else{
3206 int nCopy = pFile->mmapSize - offset;
3207 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3208 pBuf = &((u8 *)pBuf)[nCopy];
3209 amt -= nCopy;
3210 offset += nCopy;
3211 }
3212 }
drh6e0b6d52013-04-09 16:19:20 +00003213#endif
danf23da962013-03-23 21:00:41 +00003214
dan08da86a2009-08-21 17:18:03 +00003215 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003216 if( got==amt ){
3217 return SQLITE_OK;
3218 }else if( got<0 ){
3219 /* lastErrno set by seekAndRead */
3220 return SQLITE_IOERR_READ;
3221 }else{
drh4bf66fd2015-02-19 02:43:02 +00003222 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003223 /* Unread parts of the buffer must be zero-filled */
3224 memset(&((char*)pBuf)[got], 0, amt-got);
3225 return SQLITE_IOERR_SHORT_READ;
3226 }
3227}
3228
3229/*
dan47a2b4a2013-04-26 16:09:29 +00003230** Attempt to seek the file-descriptor passed as the first argument to
3231** absolute offset iOff, then attempt to write nBuf bytes of data from
3232** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3233** return the actual number of bytes written (which may be less than
3234** nBuf).
3235*/
3236static int seekAndWriteFd(
3237 int fd, /* File descriptor to write to */
3238 i64 iOff, /* File offset to begin writing at */
3239 const void *pBuf, /* Copy data from this buffer to the file */
3240 int nBuf, /* Size of buffer pBuf in bytes */
3241 int *piErrno /* OUT: Error number if error occurs */
3242){
3243 int rc = 0; /* Value returned by system call */
3244
3245 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003246 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003247 nBuf &= 0x1ffff;
3248 TIMER_START;
3249
3250#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003251 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003252#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003253 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003254#else
3255 do{
3256 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3257 SimulateIOError( iSeek-- );
3258
3259 if( iSeek!=iOff ){
3260 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3261 return -1;
3262 }
3263 rc = osWrite(fd, pBuf, nBuf);
3264 }while( rc<0 && errno==EINTR );
3265#endif
3266
3267 TIMER_END;
3268 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3269
3270 if( rc<0 && piErrno ) *piErrno = errno;
3271 return rc;
3272}
3273
3274
3275/*
drh734c9862008-11-28 15:37:20 +00003276** Seek to the offset in id->offset then read cnt bytes into pBuf.
3277** Return the number of bytes actually read. Update the offset.
3278**
3279** To avoid stomping the errno value on a failed write the lastErrno value
3280** is set before returning.
3281*/
3282static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003283 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003284}
3285
3286
3287/*
3288** Write data from a buffer into a file. Return SQLITE_OK on success
3289** or some other error code on failure.
3290*/
3291static int unixWrite(
3292 sqlite3_file *id,
3293 const void *pBuf,
3294 int amt,
3295 sqlite3_int64 offset
3296){
dan08da86a2009-08-21 17:18:03 +00003297 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003298 int wrote = 0;
3299 assert( id );
3300 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003301
dan08da86a2009-08-21 17:18:03 +00003302 /* If this is a database file (not a journal, master-journal or temp
3303 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003304#if 0
dane946c392009-08-22 11:39:46 +00003305 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003306 || offset>=PENDING_BYTE+512
3307 || offset+amt<=PENDING_BYTE
3308 );
dan7c246102010-04-12 19:00:29 +00003309#endif
drh08c6d442009-02-09 17:34:07 +00003310
drhd3d8c042012-05-29 17:02:40 +00003311#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003312 /* If we are doing a normal write to a database file (as opposed to
3313 ** doing a hot-journal rollback or a write to some file other than a
3314 ** normal database file) then record the fact that the database
3315 ** has changed. If the transaction counter is modified, record that
3316 ** fact too.
3317 */
dan08da86a2009-08-21 17:18:03 +00003318 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003319 pFile->dbUpdate = 1; /* The database has been modified */
3320 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003321 int rc;
drh8f941bc2009-01-14 23:03:40 +00003322 char oldCntr[4];
3323 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003324 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003325 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003326 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003327 pFile->transCntrChng = 1; /* The transaction counter has changed */
3328 }
3329 }
3330 }
3331#endif
3332
drh9b4c59f2013-04-15 17:03:42 +00003333#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003334 /* Deal with as much of this write request as possible by transfering
3335 ** data from the memory mapping using memcpy(). */
3336 if( offset<pFile->mmapSize ){
3337 if( offset+amt <= pFile->mmapSize ){
3338 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3339 return SQLITE_OK;
3340 }else{
3341 int nCopy = pFile->mmapSize - offset;
3342 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3343 pBuf = &((u8 *)pBuf)[nCopy];
3344 amt -= nCopy;
3345 offset += nCopy;
3346 }
3347 }
drh6e0b6d52013-04-09 16:19:20 +00003348#endif
danf23da962013-03-23 21:00:41 +00003349
dan08da86a2009-08-21 17:18:03 +00003350 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003351 amt -= wrote;
3352 offset += wrote;
3353 pBuf = &((char*)pBuf)[wrote];
3354 }
3355 SimulateIOError(( wrote=(-1), amt=1 ));
3356 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003357
drh734c9862008-11-28 15:37:20 +00003358 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003359 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003360 /* lastErrno set by seekAndWrite */
3361 return SQLITE_IOERR_WRITE;
3362 }else{
drh4bf66fd2015-02-19 02:43:02 +00003363 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003364 return SQLITE_FULL;
3365 }
3366 }
dan6e09d692010-07-27 18:34:15 +00003367
drh734c9862008-11-28 15:37:20 +00003368 return SQLITE_OK;
3369}
3370
3371#ifdef SQLITE_TEST
3372/*
3373** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003374** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003375*/
3376int sqlite3_sync_count = 0;
3377int sqlite3_fullsync_count = 0;
3378#endif
3379
3380/*
drh89240432009-03-25 01:06:01 +00003381** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003382** Others do no. To be safe, we will stick with the (slightly slower)
3383** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003384** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003385*/
drhf7a4a1b2015-01-10 18:02:45 +00003386#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003387# define fdatasync fsync
3388#endif
3389
3390/*
3391** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3392** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3393** only available on Mac OS X. But that could change.
3394*/
3395#ifdef F_FULLFSYNC
3396# define HAVE_FULLFSYNC 1
3397#else
3398# define HAVE_FULLFSYNC 0
3399#endif
3400
3401
3402/*
3403** The fsync() system call does not work as advertised on many
3404** unix systems. The following procedure is an attempt to make
3405** it work better.
3406**
3407** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3408** for testing when we want to run through the test suite quickly.
3409** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3410** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3411** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003412**
3413** SQLite sets the dataOnly flag if the size of the file is unchanged.
3414** The idea behind dataOnly is that it should only write the file content
3415** to disk, not the inode. We only set dataOnly if the file size is
3416** unchanged since the file size is part of the inode. However,
3417** Ted Ts'o tells us that fdatasync() will also write the inode if the
3418** file size has changed. The only real difference between fdatasync()
3419** and fsync(), Ted tells us, is that fdatasync() will not flush the
3420** inode if the mtime or owner or other inode attributes have changed.
3421** We only care about the file size, not the other file attributes, so
3422** as far as SQLite is concerned, an fdatasync() is always adequate.
3423** So, we always use fdatasync() if it is available, regardless of
3424** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003425*/
3426static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003427 int rc;
drh734c9862008-11-28 15:37:20 +00003428
3429 /* The following "ifdef/elif/else/" block has the same structure as
3430 ** the one below. It is replicated here solely to avoid cluttering
3431 ** up the real code with the UNUSED_PARAMETER() macros.
3432 */
3433#ifdef SQLITE_NO_SYNC
3434 UNUSED_PARAMETER(fd);
3435 UNUSED_PARAMETER(fullSync);
3436 UNUSED_PARAMETER(dataOnly);
3437#elif HAVE_FULLFSYNC
3438 UNUSED_PARAMETER(dataOnly);
3439#else
3440 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003441 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003442#endif
3443
3444 /* Record the number of times that we do a normal fsync() and
3445 ** FULLSYNC. This is used during testing to verify that this procedure
3446 ** gets called with the correct arguments.
3447 */
3448#ifdef SQLITE_TEST
3449 if( fullSync ) sqlite3_fullsync_count++;
3450 sqlite3_sync_count++;
3451#endif
3452
3453 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3454 ** no-op
3455 */
3456#ifdef SQLITE_NO_SYNC
3457 rc = SQLITE_OK;
3458#elif HAVE_FULLFSYNC
3459 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003460 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003461 }else{
3462 rc = 1;
3463 }
3464 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003465 ** It shouldn't be possible for fullfsync to fail on the local
3466 ** file system (on OSX), so failure indicates that FULLFSYNC
3467 ** isn't supported for this file system. So, attempt an fsync
3468 ** and (for now) ignore the overhead of a superfluous fcntl call.
3469 ** It'd be better to detect fullfsync support once and avoid
3470 ** the fcntl call every time sync is called.
3471 */
drh734c9862008-11-28 15:37:20 +00003472 if( rc ) rc = fsync(fd);
3473
drh7ed97b92010-01-20 13:07:21 +00003474#elif defined(__APPLE__)
3475 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3476 ** so currently we default to the macro that redefines fdatasync to fsync
3477 */
3478 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003479#else
drh0b647ff2009-03-21 14:41:04 +00003480 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003481#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003482 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003483 rc = fsync(fd);
3484 }
drh0b647ff2009-03-21 14:41:04 +00003485#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003486#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3487
3488 if( OS_VXWORKS && rc!= -1 ){
3489 rc = 0;
3490 }
chw97185482008-11-17 08:05:31 +00003491 return rc;
drhbfe66312006-10-03 17:40:40 +00003492}
3493
drh734c9862008-11-28 15:37:20 +00003494/*
drh0059eae2011-08-08 23:48:40 +00003495** Open a file descriptor to the directory containing file zFilename.
3496** If successful, *pFd is set to the opened file descriptor and
3497** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3498** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3499** value.
3500**
drh90315a22011-08-10 01:52:12 +00003501** The directory file descriptor is used for only one thing - to
3502** fsync() a directory to make sure file creation and deletion events
3503** are flushed to disk. Such fsyncs are not needed on newer
3504** journaling filesystems, but are required on older filesystems.
3505**
3506** This routine can be overridden using the xSetSysCall interface.
3507** The ability to override this routine was added in support of the
3508** chromium sandbox. Opening a directory is a security risk (we are
3509** told) so making it overrideable allows the chromium sandbox to
3510** replace this routine with a harmless no-op. To make this routine
3511** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3512** *pFd set to a negative number.
3513**
drh0059eae2011-08-08 23:48:40 +00003514** If SQLITE_OK is returned, the caller is responsible for closing
3515** the file descriptor *pFd using close().
3516*/
3517static int openDirectory(const char *zFilename, int *pFd){
3518 int ii;
3519 int fd = -1;
3520 char zDirname[MAX_PATHNAME+1];
3521
3522 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3523 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3524 if( ii>0 ){
3525 zDirname[ii] = '\0';
3526 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3527 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003528 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3529 }
3530 }
3531 *pFd = fd;
3532 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3533}
3534
3535/*
drh734c9862008-11-28 15:37:20 +00003536** Make sure all writes to a particular file are committed to disk.
3537**
3538** If dataOnly==0 then both the file itself and its metadata (file
3539** size, access time, etc) are synced. If dataOnly!=0 then only the
3540** file data is synced.
3541**
3542** Under Unix, also make sure that the directory entry for the file
3543** has been created by fsync-ing the directory that contains the file.
3544** If we do not do this and we encounter a power failure, the directory
3545** entry for the journal might not exist after we reboot. The next
3546** SQLite to access the file will not know that the journal exists (because
3547** the directory entry for the journal was never created) and the transaction
3548** will not roll back - possibly leading to database corruption.
3549*/
3550static int unixSync(sqlite3_file *id, int flags){
3551 int rc;
3552 unixFile *pFile = (unixFile*)id;
3553
3554 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3555 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3556
3557 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3558 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3559 || (flags&0x0F)==SQLITE_SYNC_FULL
3560 );
3561
3562 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3563 ** line is to test that doing so does not cause any problems.
3564 */
3565 SimulateDiskfullError( return SQLITE_FULL );
3566
3567 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003568 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003569 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3570 SimulateIOError( rc=1 );
3571 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003572 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003573 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003574 }
drh0059eae2011-08-08 23:48:40 +00003575
3576 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003577 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003578 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003579 */
3580 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3581 int dirfd;
3582 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003583 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003584 rc = osOpenDirectory(pFile->zPath, &dirfd);
3585 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003586 full_fsync(dirfd, 0, 0);
3587 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003588 }else if( rc==SQLITE_CANTOPEN ){
3589 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003590 }
drh0059eae2011-08-08 23:48:40 +00003591 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003592 }
3593 return rc;
3594}
3595
3596/*
3597** Truncate an open file to a specified size
3598*/
3599static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003600 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003601 int rc;
dan6e09d692010-07-27 18:34:15 +00003602 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003603 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003604
3605 /* If the user has configured a chunk-size for this file, truncate the
3606 ** file so that it consists of an integer number of chunks (i.e. the
3607 ** actual file size after the operation may be larger than the requested
3608 ** size).
3609 */
drhb8af4b72012-04-05 20:04:39 +00003610 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003611 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3612 }
3613
dan2ee53412014-09-06 16:49:40 +00003614 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003615 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003616 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003617 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003618 }else{
drhd3d8c042012-05-29 17:02:40 +00003619#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003620 /* If we are doing a normal write to a database file (as opposed to
3621 ** doing a hot-journal rollback or a write to some file other than a
3622 ** normal database file) and we truncate the file to zero length,
3623 ** that effectively updates the change counter. This might happen
3624 ** when restoring a database using the backup API from a zero-length
3625 ** source.
3626 */
dan6e09d692010-07-27 18:34:15 +00003627 if( pFile->inNormalWrite && nByte==0 ){
3628 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003629 }
danf23da962013-03-23 21:00:41 +00003630#endif
danc0003312013-03-22 17:46:11 +00003631
mistachkine98844f2013-08-24 00:59:24 +00003632#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003633 /* If the file was just truncated to a size smaller than the currently
3634 ** mapped region, reduce the effective mapping size as well. SQLite will
3635 ** use read() and write() to access data beyond this point from now on.
3636 */
3637 if( nByte<pFile->mmapSize ){
3638 pFile->mmapSize = nByte;
3639 }
mistachkine98844f2013-08-24 00:59:24 +00003640#endif
drh3313b142009-11-06 04:13:18 +00003641
drh734c9862008-11-28 15:37:20 +00003642 return SQLITE_OK;
3643 }
3644}
3645
3646/*
3647** Determine the current size of a file in bytes
3648*/
3649static int unixFileSize(sqlite3_file *id, i64 *pSize){
3650 int rc;
3651 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003652 assert( id );
3653 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003654 SimulateIOError( rc=1 );
3655 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003656 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003657 return SQLITE_IOERR_FSTAT;
3658 }
3659 *pSize = buf.st_size;
3660
drh8af6c222010-05-14 12:43:01 +00003661 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003662 ** writes a single byte into that file in order to work around a bug
3663 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3664 ** layers, we need to report this file size as zero even though it is
3665 ** really 1. Ticket #3260.
3666 */
3667 if( *pSize==1 ) *pSize = 0;
3668
3669
3670 return SQLITE_OK;
3671}
3672
drhd2cb50b2009-01-09 21:41:17 +00003673#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003674/*
3675** Handler for proxy-locking file-control verbs. Defined below in the
3676** proxying locking division.
3677*/
3678static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003679#endif
drh715ff302008-12-03 22:32:44 +00003680
dan502019c2010-07-28 14:26:17 +00003681/*
3682** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003683** file-control operation. Enlarge the database to nBytes in size
3684** (rounded up to the next chunk-size). If the database is already
3685** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003686*/
3687static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003688 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003689 i64 nSize; /* Required file size */
3690 struct stat buf; /* Used to hold return values of fstat() */
3691
drh4bf66fd2015-02-19 02:43:02 +00003692 if( osFstat(pFile->h, &buf) ){
3693 return SQLITE_IOERR_FSTAT;
3694 }
dan502019c2010-07-28 14:26:17 +00003695
3696 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3697 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003698
dan502019c2010-07-28 14:26:17 +00003699#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003700 /* The code below is handling the return value of osFallocate()
3701 ** correctly. posix_fallocate() is defined to "returns zero on success,
3702 ** or an error number on failure". See the manpage for details. */
3703 int err;
drhff812312011-02-23 13:33:46 +00003704 do{
dan661d71a2011-03-30 19:08:03 +00003705 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3706 }while( err==EINTR );
3707 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003708#else
dan592bf7f2014-12-30 19:58:31 +00003709 /* If the OS does not have posix_fallocate(), fake it. Write a
3710 ** single byte to the last byte in each block that falls entirely
3711 ** within the extended region. Then, if required, a single byte
3712 ** at offset (nSize-1), to set the size of the file correctly.
3713 ** This is a similar technique to that used by glibc on systems
3714 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003715 */
3716 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003717 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003718 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003719
dan502019c2010-07-28 14:26:17 +00003720 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003721 assert( iWrite>=buf.st_size );
3722 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3723 assert( ((iWrite+1)%nBlk)==0 );
3724 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003725 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003726 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003727 }
danef3d66c2015-01-06 21:31:47 +00003728 if( nWrite==0 || (nSize%nBlk) ){
3729 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003730 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003731 }
dan502019c2010-07-28 14:26:17 +00003732#endif
3733 }
3734 }
3735
mistachkine98844f2013-08-24 00:59:24 +00003736#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003737 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003738 int rc;
3739 if( pFile->szChunk<=0 ){
3740 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003741 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003742 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3743 }
3744 }
3745
3746 rc = unixMapfile(pFile, nByte);
3747 return rc;
3748 }
mistachkine98844f2013-08-24 00:59:24 +00003749#endif
danf23da962013-03-23 21:00:41 +00003750
dan502019c2010-07-28 14:26:17 +00003751 return SQLITE_OK;
3752}
danielk1977ad94b582007-08-20 06:44:22 +00003753
danielk1977e3026632004-06-22 11:29:02 +00003754/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003755** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003756** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3757**
3758** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3759*/
3760static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3761 if( *pArg<0 ){
3762 *pArg = (pFile->ctrlFlags & mask)!=0;
3763 }else if( (*pArg)==0 ){
3764 pFile->ctrlFlags &= ~mask;
3765 }else{
3766 pFile->ctrlFlags |= mask;
3767 }
3768}
3769
drh696b33e2012-12-06 19:01:42 +00003770/* Forward declaration */
3771static int unixGetTempname(int nBuf, char *zBuf);
3772
drhf12b3f62011-12-21 14:42:29 +00003773/*
drh9e33c2c2007-08-31 18:34:59 +00003774** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003775*/
drhcc6bb3e2007-08-31 16:11:35 +00003776static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003777 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003778 switch( op ){
3779 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003780 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003781 return SQLITE_OK;
3782 }
drh4bf66fd2015-02-19 02:43:02 +00003783 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003784 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003785 return SQLITE_OK;
3786 }
dan6e09d692010-07-27 18:34:15 +00003787 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003788 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003789 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003790 }
drh9ff27ec2010-05-19 19:26:05 +00003791 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003792 int rc;
3793 SimulateIOErrorBenign(1);
3794 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3795 SimulateIOErrorBenign(0);
3796 return rc;
drhf0b190d2011-07-26 16:03:07 +00003797 }
3798 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003799 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3800 return SQLITE_OK;
3801 }
drhcb15f352011-12-23 01:04:17 +00003802 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3803 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003804 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003805 }
drhde60fc22011-12-14 17:53:36 +00003806 case SQLITE_FCNTL_VFSNAME: {
3807 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3808 return SQLITE_OK;
3809 }
drh696b33e2012-12-06 19:01:42 +00003810 case SQLITE_FCNTL_TEMPFILENAME: {
3811 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3812 if( zTFile ){
3813 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3814 *(char**)pArg = zTFile;
3815 }
3816 return SQLITE_OK;
3817 }
drhb959a012013-12-07 12:29:22 +00003818 case SQLITE_FCNTL_HAS_MOVED: {
3819 *(int*)pArg = fileHasMoved(pFile);
3820 return SQLITE_OK;
3821 }
mistachkine98844f2013-08-24 00:59:24 +00003822#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003823 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003824 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003825 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003826 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3827 newLimit = sqlite3GlobalConfig.mxMmap;
3828 }
3829 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003830 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003831 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003832 if( pFile->mmapSize>0 ){
3833 unixUnmapfile(pFile);
3834 rc = unixMapfile(pFile, -1);
3835 }
danbcb8a862013-04-08 15:30:41 +00003836 }
drh34e258c2013-05-23 01:40:53 +00003837 return rc;
danb2d3de32013-03-14 18:34:37 +00003838 }
mistachkine98844f2013-08-24 00:59:24 +00003839#endif
drhd3d8c042012-05-29 17:02:40 +00003840#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003841 /* The pager calls this method to signal that it has done
3842 ** a rollback and that the database is therefore unchanged and
3843 ** it hence it is OK for the transaction change counter to be
3844 ** unchanged.
3845 */
3846 case SQLITE_FCNTL_DB_UNCHANGED: {
3847 ((unixFile*)id)->dbUpdate = 0;
3848 return SQLITE_OK;
3849 }
3850#endif
drhd2cb50b2009-01-09 21:41:17 +00003851#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003852 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3853 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003854 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003855 }
drhd2cb50b2009-01-09 21:41:17 +00003856#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003857 }
drh0b52b7d2011-01-26 19:46:22 +00003858 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003859}
3860
3861/*
danielk1977a3d4c882007-03-23 10:08:38 +00003862** Return the sector size in bytes of the underlying block device for
3863** the specified file. This is almost always 512 bytes, but may be
3864** larger for some devices.
3865**
3866** SQLite code assumes this function cannot fail. It also assumes that
3867** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003868** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003869** same for both.
3870*/
drh537dddf2012-10-26 13:46:24 +00003871#ifndef __QNXNTO__
3872static int unixSectorSize(sqlite3_file *NotUsed){
3873 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003874 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003875}
drh537dddf2012-10-26 13:46:24 +00003876#endif
3877
3878/*
3879** The following version of unixSectorSize() is optimized for QNX.
3880*/
3881#ifdef __QNXNTO__
3882#include <sys/dcmd_blk.h>
3883#include <sys/statvfs.h>
3884static int unixSectorSize(sqlite3_file *id){
3885 unixFile *pFile = (unixFile*)id;
3886 if( pFile->sectorSize == 0 ){
3887 struct statvfs fsInfo;
3888
3889 /* Set defaults for non-supported filesystems */
3890 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3891 pFile->deviceCharacteristics = 0;
3892 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3893 return pFile->sectorSize;
3894 }
3895
3896 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3897 pFile->sectorSize = fsInfo.f_bsize;
3898 pFile->deviceCharacteristics =
3899 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3900 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3901 ** the write succeeds */
3902 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3903 ** so it is ordered */
3904 0;
3905 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3906 pFile->sectorSize = fsInfo.f_bsize;
3907 pFile->deviceCharacteristics =
3908 /* etfs cluster size writes are atomic */
3909 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3910 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3911 ** the write succeeds */
3912 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3913 ** so it is ordered */
3914 0;
3915 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3916 pFile->sectorSize = fsInfo.f_bsize;
3917 pFile->deviceCharacteristics =
3918 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3919 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3920 ** the write succeeds */
3921 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3922 ** so it is ordered */
3923 0;
3924 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3925 pFile->sectorSize = fsInfo.f_bsize;
3926 pFile->deviceCharacteristics =
3927 /* full bitset of atomics from max sector size and smaller */
3928 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3929 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3930 ** so it is ordered */
3931 0;
3932 }else if( strstr(fsInfo.f_basetype, "dos") ){
3933 pFile->sectorSize = fsInfo.f_bsize;
3934 pFile->deviceCharacteristics =
3935 /* full bitset of atomics from max sector size and smaller */
3936 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3937 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3938 ** so it is ordered */
3939 0;
3940 }else{
3941 pFile->deviceCharacteristics =
3942 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3943 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3944 ** the write succeeds */
3945 0;
3946 }
3947 }
3948 /* Last chance verification. If the sector size isn't a multiple of 512
3949 ** then it isn't valid.*/
3950 if( pFile->sectorSize % 512 != 0 ){
3951 pFile->deviceCharacteristics = 0;
3952 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3953 }
3954 return pFile->sectorSize;
3955}
3956#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003957
danielk197790949c22007-08-17 16:50:38 +00003958/*
drhf12b3f62011-12-21 14:42:29 +00003959** Return the device characteristics for the file.
3960**
drhcb15f352011-12-23 01:04:17 +00003961** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003962** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003963** file system does not always provide powersafe overwrites. (In other
3964** words, after a power-loss event, parts of the file that were never
3965** written might end up being altered.) However, non-PSOW behavior is very,
3966** very rare. And asserting PSOW makes a large reduction in the amount
3967** of required I/O for journaling, since a lot of padding is eliminated.
3968** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3969** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003970*/
drhf12b3f62011-12-21 14:42:29 +00003971static int unixDeviceCharacteristics(sqlite3_file *id){
3972 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003973 int rc = 0;
3974#ifdef __QNXNTO__
3975 if( p->sectorSize==0 ) unixSectorSize(id);
3976 rc = p->deviceCharacteristics;
3977#endif
drhcb15f352011-12-23 01:04:17 +00003978 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003979 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003980 }
drh537dddf2012-10-26 13:46:24 +00003981 return rc;
danielk197762079062007-08-15 17:08:46 +00003982}
3983
dan702eec12014-06-23 10:04:58 +00003984#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003985
dan702eec12014-06-23 10:04:58 +00003986/*
3987** Return the system page size.
3988**
3989** This function should not be called directly by other code in this file.
3990** Instead, it should be called via macro osGetpagesize().
3991*/
3992static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003993#if OS_VXWORKS
3994 return 1024;
3995#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003996 return getpagesize();
3997#else
3998 return (int)sysconf(_SC_PAGESIZE);
3999#endif
4000}
4001
4002#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4003
4004#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004005
4006/*
drhd91c68f2010-05-14 14:52:25 +00004007** Object used to represent an shared memory buffer.
4008**
4009** When multiple threads all reference the same wal-index, each thread
4010** has its own unixShm object, but they all point to a single instance
4011** of this unixShmNode object. In other words, each wal-index is opened
4012** only once per process.
4013**
4014** Each unixShmNode object is connected to a single unixInodeInfo object.
4015** We could coalesce this object into unixInodeInfo, but that would mean
4016** every open file that does not use shared memory (in other words, most
4017** open files) would have to carry around this extra information. So
4018** the unixInodeInfo object contains a pointer to this unixShmNode object
4019** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004020**
4021** unixMutexHeld() must be true when creating or destroying
4022** this object or while reading or writing the following fields:
4023**
4024** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004025**
4026** The following fields are read-only after the object is created:
4027**
4028** fid
4029** zFilename
4030**
drhd91c68f2010-05-14 14:52:25 +00004031** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004032** unixMutexHeld() is true when reading or writing any other field
4033** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004034*/
drhd91c68f2010-05-14 14:52:25 +00004035struct unixShmNode {
4036 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004037 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004038 char *zFilename; /* Name of the mmapped file */
4039 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004040 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004041 u16 nRegion; /* Size of array apRegion */
4042 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004043 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004044 int nRef; /* Number of unixShm objects pointing to this */
4045 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004046#ifdef SQLITE_DEBUG
4047 u8 exclMask; /* Mask of exclusive locks held */
4048 u8 sharedMask; /* Mask of shared locks held */
4049 u8 nextShmId; /* Next available unixShm.id value */
4050#endif
4051};
4052
4053/*
drhd9e5c4f2010-05-12 18:01:39 +00004054** Structure used internally by this VFS to record the state of an
4055** open shared memory connection.
4056**
drhd91c68f2010-05-14 14:52:25 +00004057** The following fields are initialized when this object is created and
4058** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004059**
drhd91c68f2010-05-14 14:52:25 +00004060** unixShm.pFile
4061** unixShm.id
4062**
4063** All other fields are read/write. The unixShm.pFile->mutex must be held
4064** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004065*/
4066struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004067 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4068 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004069 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004070 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004071 u16 sharedMask; /* Mask of shared locks held */
4072 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004073};
4074
4075/*
drhd9e5c4f2010-05-12 18:01:39 +00004076** Constants used for locking
4077*/
drhbd9676c2010-06-23 17:58:38 +00004078#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004079#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004080
drhd9e5c4f2010-05-12 18:01:39 +00004081/*
drh73b64e42010-05-30 19:55:15 +00004082** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004083**
4084** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4085** otherwise.
4086*/
4087static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004088 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4089 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004090 int ofst, /* First byte of the locking range */
4091 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004092){
4093 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004094 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004095
drhd91c68f2010-05-14 14:52:25 +00004096 /* Access to the unixShmNode object is serialized by the caller */
4097 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004098
drh73b64e42010-05-30 19:55:15 +00004099 /* Shared locks never span more than one byte */
4100 assert( n==1 || lockType!=F_RDLCK );
4101
4102 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004103 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004104
drh3cb93392011-03-12 18:10:44 +00004105 if( pShmNode->h>=0 ){
4106 /* Initialize the locking parameters */
4107 memset(&f, 0, sizeof(f));
4108 f.l_type = lockType;
4109 f.l_whence = SEEK_SET;
4110 f.l_start = ofst;
4111 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004112
drh3cb93392011-03-12 18:10:44 +00004113 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4114 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4115 }
drhd9e5c4f2010-05-12 18:01:39 +00004116
4117 /* Update the global lock state and do debug tracing */
4118#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004119 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004120 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004121 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004122 if( rc==SQLITE_OK ){
4123 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004124 OSTRACE(("unlock %d ok", ofst));
4125 pShmNode->exclMask &= ~mask;
4126 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004127 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004128 OSTRACE(("read-lock %d ok", ofst));
4129 pShmNode->exclMask &= ~mask;
4130 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004131 }else{
4132 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004133 OSTRACE(("write-lock %d ok", ofst));
4134 pShmNode->exclMask |= mask;
4135 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004136 }
4137 }else{
4138 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004139 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004140 }else if( lockType==F_RDLCK ){
4141 OSTRACE(("read-lock failed"));
4142 }else{
4143 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004144 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004145 }
4146 }
drh20e1f082010-05-31 16:10:12 +00004147 OSTRACE((" - afterwards %03x,%03x\n",
4148 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004149 }
drhd9e5c4f2010-05-12 18:01:39 +00004150#endif
4151
4152 return rc;
4153}
4154
dan781e34c2014-03-20 08:59:47 +00004155/*
dan781e34c2014-03-20 08:59:47 +00004156** Return the minimum number of 32KB shm regions that should be mapped at
4157** a time, assuming that each mapping must be an integer multiple of the
4158** current system page-size.
4159**
4160** Usually, this is 1. The exception seems to be systems that are configured
4161** to use 64KB pages - in this case each mapping must cover at least two
4162** shm regions.
4163*/
4164static int unixShmRegionPerMap(void){
4165 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004166 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004167 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4168 if( pgsz<shmsz ) return 1;
4169 return pgsz/shmsz;
4170}
drhd9e5c4f2010-05-12 18:01:39 +00004171
4172/*
drhd91c68f2010-05-14 14:52:25 +00004173** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004174**
4175** This is not a VFS shared-memory method; it is a utility function called
4176** by VFS shared-memory methods.
4177*/
drhd91c68f2010-05-14 14:52:25 +00004178static void unixShmPurge(unixFile *pFd){
4179 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004180 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004181 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004182 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004183 int i;
drhd91c68f2010-05-14 14:52:25 +00004184 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004185 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004186 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004187 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004188 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004189 }else{
4190 sqlite3_free(p->apRegion[i]);
4191 }
dan13a3cb82010-06-11 19:04:21 +00004192 }
dan18801912010-06-14 14:07:50 +00004193 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004194 if( p->h>=0 ){
4195 robust_close(pFd, p->h, __LINE__);
4196 p->h = -1;
4197 }
drhd91c68f2010-05-14 14:52:25 +00004198 p->pInode->pShmNode = 0;
4199 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004200 }
4201}
4202
4203/*
danda9fe0c2010-07-13 18:44:03 +00004204** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004205** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004206**
drh7234c6d2010-06-19 15:10:09 +00004207** The file used to implement shared-memory is in the same directory
4208** as the open database file and has the same name as the open database
4209** file with the "-shm" suffix added. For example, if the database file
4210** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004211** for shared memory will be called "/home/user1/config.db-shm".
4212**
4213** Another approach to is to use files in /dev/shm or /dev/tmp or an
4214** some other tmpfs mount. But if a file in a different directory
4215** from the database file is used, then differing access permissions
4216** or a chroot() might cause two different processes on the same
4217** database to end up using different files for shared memory -
4218** meaning that their memory would not really be shared - resulting
4219** in database corruption. Nevertheless, this tmpfs file usage
4220** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4221** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4222** option results in an incompatible build of SQLite; builds of SQLite
4223** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4224** same database file at the same time, database corruption will likely
4225** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4226** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004227**
4228** When opening a new shared-memory file, if no other instances of that
4229** file are currently open, in this process or in other processes, then
4230** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004231**
4232** If the original database file (pDbFd) is using the "unix-excl" VFS
4233** that means that an exclusive lock is held on the database file and
4234** that no other processes are able to read or write the database. In
4235** that case, we do not really need shared memory. No shared memory
4236** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004237*/
danda9fe0c2010-07-13 18:44:03 +00004238static int unixOpenSharedMemory(unixFile *pDbFd){
4239 struct unixShm *p = 0; /* The connection to be opened */
4240 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4241 int rc; /* Result code */
4242 unixInodeInfo *pInode; /* The inode of fd */
4243 char *zShmFilename; /* Name of the file used for SHM */
4244 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004245
danda9fe0c2010-07-13 18:44:03 +00004246 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004247 p = sqlite3_malloc( sizeof(*p) );
4248 if( p==0 ) return SQLITE_NOMEM;
4249 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004250 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004251
danda9fe0c2010-07-13 18:44:03 +00004252 /* Check to see if a unixShmNode object already exists. Reuse an existing
4253 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004254 */
4255 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004256 pInode = pDbFd->pInode;
4257 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004258 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004259 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004260#ifndef SQLITE_SHM_DIRECTORY
4261 const char *zBasePath = pDbFd->zPath;
4262#endif
danddb0ac42010-07-14 14:48:58 +00004263
4264 /* Call fstat() to figure out the permissions on the database file. If
4265 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004266 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004267 */
drh3cb93392011-03-12 18:10:44 +00004268 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004269 rc = SQLITE_IOERR_FSTAT;
4270 goto shm_open_err;
4271 }
4272
drha4ced192010-07-15 18:32:40 +00004273#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004274 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004275#else
drh4bf66fd2015-02-19 02:43:02 +00004276 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004277#endif
drh7234c6d2010-06-19 15:10:09 +00004278 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004279 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004280 rc = SQLITE_NOMEM;
4281 goto shm_open_err;
4282 }
drh9cb5a0d2012-01-05 21:19:54 +00004283 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004284 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004285#ifdef SQLITE_SHM_DIRECTORY
4286 sqlite3_snprintf(nShmFilename, zShmFilename,
4287 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4288 (u32)sStat.st_ino, (u32)sStat.st_dev);
4289#else
drh4bf66fd2015-02-19 02:43:02 +00004290 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004291 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004292#endif
drhd91c68f2010-05-14 14:52:25 +00004293 pShmNode->h = -1;
4294 pDbFd->pInode->pShmNode = pShmNode;
4295 pShmNode->pInode = pDbFd->pInode;
4296 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4297 if( pShmNode->mutex==0 ){
4298 rc = SQLITE_NOMEM;
4299 goto shm_open_err;
4300 }
drhd9e5c4f2010-05-12 18:01:39 +00004301
drh3cb93392011-03-12 18:10:44 +00004302 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004303 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004304 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004305 openFlags = O_RDONLY;
4306 pShmNode->isReadonly = 1;
4307 }
4308 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004309 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004310 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4311 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004312 }
drhac7c3ac2012-02-11 19:23:48 +00004313
4314 /* If this process is running as root, make sure that the SHM file
4315 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004316 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004317 */
drhed466822012-05-31 13:10:49 +00004318 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004319
4320 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004321 ** If not, truncate the file to zero length.
4322 */
4323 rc = SQLITE_OK;
4324 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4325 if( robust_ftruncate(pShmNode->h, 0) ){
4326 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004327 }
4328 }
drh66dfec8b2011-06-01 20:01:49 +00004329 if( rc==SQLITE_OK ){
4330 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4331 }
4332 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004333 }
drhd9e5c4f2010-05-12 18:01:39 +00004334 }
4335
drhd91c68f2010-05-14 14:52:25 +00004336 /* Make the new connection a child of the unixShmNode */
4337 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004338#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004339 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004340#endif
drhd91c68f2010-05-14 14:52:25 +00004341 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004342 pDbFd->pShm = p;
4343 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004344
4345 /* The reference count on pShmNode has already been incremented under
4346 ** the cover of the unixEnterMutex() mutex and the pointer from the
4347 ** new (struct unixShm) object to the pShmNode has been set. All that is
4348 ** left to do is to link the new object into the linked list starting
4349 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4350 ** mutex.
4351 */
4352 sqlite3_mutex_enter(pShmNode->mutex);
4353 p->pNext = pShmNode->pFirst;
4354 pShmNode->pFirst = p;
4355 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004356 return SQLITE_OK;
4357
4358 /* Jump here on any error */
4359shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004360 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004361 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004362 unixLeaveMutex();
4363 return rc;
4364}
4365
4366/*
danda9fe0c2010-07-13 18:44:03 +00004367** This function is called to obtain a pointer to region iRegion of the
4368** shared-memory associated with the database file fd. Shared-memory regions
4369** are numbered starting from zero. Each shared-memory region is szRegion
4370** bytes in size.
4371**
4372** If an error occurs, an error code is returned and *pp is set to NULL.
4373**
4374** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4375** region has not been allocated (by any client, including one running in a
4376** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4377** bExtend is non-zero and the requested shared-memory region has not yet
4378** been allocated, it is allocated by this function.
4379**
4380** If the shared-memory region has already been allocated or is allocated by
4381** this call as described above, then it is mapped into this processes
4382** address space (if it is not already), *pp is set to point to the mapped
4383** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004384*/
danda9fe0c2010-07-13 18:44:03 +00004385static int unixShmMap(
4386 sqlite3_file *fd, /* Handle open on database file */
4387 int iRegion, /* Region to retrieve */
4388 int szRegion, /* Size of regions */
4389 int bExtend, /* True to extend file if necessary */
4390 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004391){
danda9fe0c2010-07-13 18:44:03 +00004392 unixFile *pDbFd = (unixFile*)fd;
4393 unixShm *p;
4394 unixShmNode *pShmNode;
4395 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004396 int nShmPerMap = unixShmRegionPerMap();
4397 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004398
danda9fe0c2010-07-13 18:44:03 +00004399 /* If the shared-memory file has not yet been opened, open it now. */
4400 if( pDbFd->pShm==0 ){
4401 rc = unixOpenSharedMemory(pDbFd);
4402 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004403 }
drhd9e5c4f2010-05-12 18:01:39 +00004404
danda9fe0c2010-07-13 18:44:03 +00004405 p = pDbFd->pShm;
4406 pShmNode = p->pShmNode;
4407 sqlite3_mutex_enter(pShmNode->mutex);
4408 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004409 assert( pShmNode->pInode==pDbFd->pInode );
4410 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4411 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004412
dan781e34c2014-03-20 08:59:47 +00004413 /* Minimum number of regions required to be mapped. */
4414 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4415
4416 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004417 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004418 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004419 struct stat sStat; /* Used by fstat() */
4420
4421 pShmNode->szRegion = szRegion;
4422
drh3cb93392011-03-12 18:10:44 +00004423 if( pShmNode->h>=0 ){
4424 /* The requested region is not mapped into this processes address space.
4425 ** Check to see if it has been allocated (i.e. if the wal-index file is
4426 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004427 */
drh3cb93392011-03-12 18:10:44 +00004428 if( osFstat(pShmNode->h, &sStat) ){
4429 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004430 goto shmpage_out;
4431 }
drh3cb93392011-03-12 18:10:44 +00004432
4433 if( sStat.st_size<nByte ){
4434 /* The requested memory region does not exist. If bExtend is set to
4435 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004436 */
dan47a2b4a2013-04-26 16:09:29 +00004437 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004438 goto shmpage_out;
4439 }
dan47a2b4a2013-04-26 16:09:29 +00004440
4441 /* Alternatively, if bExtend is true, extend the file. Do this by
4442 ** writing a single byte to the end of each (OS) page being
4443 ** allocated or extended. Technically, we need only write to the
4444 ** last page in order to extend the file. But writing to all new
4445 ** pages forces the OS to allocate them immediately, which reduces
4446 ** the chances of SIGBUS while accessing the mapped region later on.
4447 */
4448 else{
4449 static const int pgsz = 4096;
4450 int iPg;
4451
4452 /* Write to the last byte of each newly allocated or extended page */
4453 assert( (nByte % pgsz)==0 );
4454 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4455 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4456 const char *zFile = pShmNode->zFilename;
4457 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4458 goto shmpage_out;
4459 }
4460 }
drh3cb93392011-03-12 18:10:44 +00004461 }
4462 }
danda9fe0c2010-07-13 18:44:03 +00004463 }
4464
4465 /* Map the requested memory region into this processes address space. */
4466 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004467 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004468 );
4469 if( !apNew ){
4470 rc = SQLITE_IOERR_NOMEM;
4471 goto shmpage_out;
4472 }
4473 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004474 while( pShmNode->nRegion<nReqRegion ){
4475 int nMap = szRegion*nShmPerMap;
4476 int i;
drh3cb93392011-03-12 18:10:44 +00004477 void *pMem;
4478 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004479 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004480 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004481 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004482 );
4483 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004484 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004485 goto shmpage_out;
4486 }
4487 }else{
4488 pMem = sqlite3_malloc(szRegion);
4489 if( pMem==0 ){
4490 rc = SQLITE_NOMEM;
4491 goto shmpage_out;
4492 }
4493 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004494 }
dan781e34c2014-03-20 08:59:47 +00004495
4496 for(i=0; i<nShmPerMap; i++){
4497 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4498 }
4499 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004500 }
4501 }
4502
4503shmpage_out:
4504 if( pShmNode->nRegion>iRegion ){
4505 *pp = pShmNode->apRegion[iRegion];
4506 }else{
4507 *pp = 0;
4508 }
drh66dfec8b2011-06-01 20:01:49 +00004509 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004510 sqlite3_mutex_leave(pShmNode->mutex);
4511 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004512}
4513
4514/*
drhd9e5c4f2010-05-12 18:01:39 +00004515** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004516**
4517** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4518** different here than in posix. In xShmLock(), one can go from unlocked
4519** to shared and back or from unlocked to exclusive and back. But one may
4520** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004521*/
4522static int unixShmLock(
4523 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004524 int ofst, /* First lock to acquire or release */
4525 int n, /* Number of locks to acquire or release */
4526 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004527){
drh73b64e42010-05-30 19:55:15 +00004528 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4529 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4530 unixShm *pX; /* For looping over all siblings */
4531 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4532 int rc = SQLITE_OK; /* Result code */
4533 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004534
drhd91c68f2010-05-14 14:52:25 +00004535 assert( pShmNode==pDbFd->pInode->pShmNode );
4536 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004537 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004538 assert( n>=1 );
4539 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4540 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4541 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4542 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4543 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004544 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4545 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004546
drhc99597c2010-05-31 01:41:15 +00004547 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004548 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004549 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004550 if( flags & SQLITE_SHM_UNLOCK ){
4551 u16 allMask = 0; /* Mask of locks held by siblings */
4552
4553 /* See if any siblings hold this same lock */
4554 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4555 if( pX==p ) continue;
4556 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4557 allMask |= pX->sharedMask;
4558 }
4559
4560 /* Unlock the system-level locks */
4561 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004562 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004563 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004564 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004565 }
drh73b64e42010-05-30 19:55:15 +00004566
4567 /* Undo the local locks */
4568 if( rc==SQLITE_OK ){
4569 p->exclMask &= ~mask;
4570 p->sharedMask &= ~mask;
4571 }
4572 }else if( flags & SQLITE_SHM_SHARED ){
4573 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4574
4575 /* Find out which shared locks are already held by sibling connections.
4576 ** If any sibling already holds an exclusive lock, go ahead and return
4577 ** SQLITE_BUSY.
4578 */
4579 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004580 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004581 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004582 break;
4583 }
4584 allShared |= pX->sharedMask;
4585 }
4586
4587 /* Get shared locks at the system level, if necessary */
4588 if( rc==SQLITE_OK ){
4589 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004590 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004591 }else{
drh73b64e42010-05-30 19:55:15 +00004592 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004593 }
drhd9e5c4f2010-05-12 18:01:39 +00004594 }
drh73b64e42010-05-30 19:55:15 +00004595
4596 /* Get the local shared locks */
4597 if( rc==SQLITE_OK ){
4598 p->sharedMask |= mask;
4599 }
4600 }else{
4601 /* Make sure no sibling connections hold locks that will block this
4602 ** lock. If any do, return SQLITE_BUSY right away.
4603 */
4604 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004605 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4606 rc = SQLITE_BUSY;
4607 break;
4608 }
4609 }
4610
4611 /* Get the exclusive locks at the system level. Then if successful
4612 ** also mark the local connection as being locked.
4613 */
4614 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004615 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004616 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004617 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004618 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004619 }
drhd9e5c4f2010-05-12 18:01:39 +00004620 }
4621 }
drhd91c68f2010-05-14 14:52:25 +00004622 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004623 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4624 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004625 return rc;
4626}
4627
drh286a2882010-05-20 23:51:06 +00004628/*
4629** Implement a memory barrier or memory fence on shared memory.
4630**
4631** All loads and stores begun before the barrier must complete before
4632** any load or store begun after the barrier.
4633*/
4634static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004635 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004636){
drhff828942010-06-26 21:34:06 +00004637 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004638 unixEnterMutex();
4639 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004640}
4641
dan18801912010-06-14 14:07:50 +00004642/*
danda9fe0c2010-07-13 18:44:03 +00004643** Close a connection to shared-memory. Delete the underlying
4644** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004645**
4646** If there is no shared memory associated with the connection then this
4647** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004648*/
danda9fe0c2010-07-13 18:44:03 +00004649static int unixShmUnmap(
4650 sqlite3_file *fd, /* The underlying database file */
4651 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004652){
danda9fe0c2010-07-13 18:44:03 +00004653 unixShm *p; /* The connection to be closed */
4654 unixShmNode *pShmNode; /* The underlying shared-memory file */
4655 unixShm **pp; /* For looping over sibling connections */
4656 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004657
danda9fe0c2010-07-13 18:44:03 +00004658 pDbFd = (unixFile*)fd;
4659 p = pDbFd->pShm;
4660 if( p==0 ) return SQLITE_OK;
4661 pShmNode = p->pShmNode;
4662
4663 assert( pShmNode==pDbFd->pInode->pShmNode );
4664 assert( pShmNode->pInode==pDbFd->pInode );
4665
4666 /* Remove connection p from the set of connections associated
4667 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004668 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004669 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4670 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004671
danda9fe0c2010-07-13 18:44:03 +00004672 /* Free the connection p */
4673 sqlite3_free(p);
4674 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004675 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004676
4677 /* If pShmNode->nRef has reached 0, then close the underlying
4678 ** shared-memory file, too */
4679 unixEnterMutex();
4680 assert( pShmNode->nRef>0 );
4681 pShmNode->nRef--;
4682 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004683 if( deleteFlag && pShmNode->h>=0 ){
4684 osUnlink(pShmNode->zFilename);
4685 }
danda9fe0c2010-07-13 18:44:03 +00004686 unixShmPurge(pDbFd);
4687 }
4688 unixLeaveMutex();
4689
4690 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004691}
drh286a2882010-05-20 23:51:06 +00004692
danda9fe0c2010-07-13 18:44:03 +00004693
drhd9e5c4f2010-05-12 18:01:39 +00004694#else
drh6b017cc2010-06-14 18:01:46 +00004695# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004696# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004697# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004698# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004699#endif /* #ifndef SQLITE_OMIT_WAL */
4700
mistachkine98844f2013-08-24 00:59:24 +00004701#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004702/*
danaef49d72013-03-25 16:28:54 +00004703** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004704*/
danf23da962013-03-23 21:00:41 +00004705static void unixUnmapfile(unixFile *pFd){
4706 assert( pFd->nFetchOut==0 );
4707 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004708 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004709 pFd->pMapRegion = 0;
4710 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004711 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004712 }
4713}
dan5d8a1372013-03-19 19:28:06 +00004714
danaef49d72013-03-25 16:28:54 +00004715/*
dane6ecd662013-04-01 17:56:59 +00004716** Attempt to set the size of the memory mapping maintained by file
4717** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4718**
4719** If successful, this function sets the following variables:
4720**
4721** unixFile.pMapRegion
4722** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004723** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004724**
4725** If unsuccessful, an error message is logged via sqlite3_log() and
4726** the three variables above are zeroed. In this case SQLite should
4727** continue accessing the database using the xRead() and xWrite()
4728** methods.
4729*/
4730static void unixRemapfile(
4731 unixFile *pFd, /* File descriptor object */
4732 i64 nNew /* Required mapping size */
4733){
dan4ff7bc42013-04-02 12:04:09 +00004734 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004735 int h = pFd->h; /* File descriptor open on db file */
4736 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004737 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004738 u8 *pNew = 0; /* Location of new mapping */
4739 int flags = PROT_READ; /* Flags to pass to mmap() */
4740
4741 assert( pFd->nFetchOut==0 );
4742 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004743 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004744 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004745 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004746 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004747
4748 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4749
4750 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004751#if HAVE_MREMAP
4752 i64 nReuse = pFd->mmapSize;
4753#else
danbc760632014-03-20 09:42:09 +00004754 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004755 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004756#endif
dane6ecd662013-04-01 17:56:59 +00004757 u8 *pReq = &pOrig[nReuse];
4758
4759 /* Unmap any pages of the existing mapping that cannot be reused. */
4760 if( nReuse!=nOrig ){
4761 osMunmap(pReq, nOrig-nReuse);
4762 }
4763
4764#if HAVE_MREMAP
4765 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004766 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004767#else
4768 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4769 if( pNew!=MAP_FAILED ){
4770 if( pNew!=pReq ){
4771 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004772 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004773 }else{
4774 pNew = pOrig;
4775 }
4776 }
4777#endif
4778
dan48ccef82013-04-02 20:55:01 +00004779 /* The attempt to extend the existing mapping failed. Free it. */
4780 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004781 osMunmap(pOrig, nReuse);
4782 }
4783 }
4784
4785 /* If pNew is still NULL, try to create an entirely new mapping. */
4786 if( pNew==0 ){
4787 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004788 }
4789
dan4ff7bc42013-04-02 12:04:09 +00004790 if( pNew==MAP_FAILED ){
4791 pNew = 0;
4792 nNew = 0;
4793 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4794
4795 /* If the mmap() above failed, assume that all subsequent mmap() calls
4796 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4797 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004798 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004799 }
dane6ecd662013-04-01 17:56:59 +00004800 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004801 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004802}
4803
4804/*
danaef49d72013-03-25 16:28:54 +00004805** Memory map or remap the file opened by file-descriptor pFd (if the file
4806** is already mapped, the existing mapping is replaced by the new). Or, if
4807** there already exists a mapping for this file, and there are still
4808** outstanding xFetch() references to it, this function is a no-op.
4809**
4810** If parameter nByte is non-negative, then it is the requested size of
4811** the mapping to create. Otherwise, if nByte is less than zero, then the
4812** requested size is the size of the file on disk. The actual size of the
4813** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004814** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004815**
4816** SQLITE_OK is returned if no error occurs (even if the mapping is not
4817** recreated as a result of outstanding references) or an SQLite error
4818** code otherwise.
4819*/
danf23da962013-03-23 21:00:41 +00004820static int unixMapfile(unixFile *pFd, i64 nByte){
4821 i64 nMap = nByte;
4822 int rc;
daneb97b292013-03-20 14:26:59 +00004823
danf23da962013-03-23 21:00:41 +00004824 assert( nMap>=0 || pFd->nFetchOut==0 );
4825 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4826
4827 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004828 struct stat statbuf; /* Low-level file information */
4829 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004830 if( rc!=SQLITE_OK ){
4831 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004832 }
drh3044b512014-06-16 16:41:52 +00004833 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004834 }
drh9b4c59f2013-04-15 17:03:42 +00004835 if( nMap>pFd->mmapSizeMax ){
4836 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004837 }
4838
danf23da962013-03-23 21:00:41 +00004839 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004840 if( nMap>0 ){
4841 unixRemapfile(pFd, nMap);
4842 }else{
danb7e3a322013-03-25 20:30:13 +00004843 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004844 }
4845 }
4846
danf23da962013-03-23 21:00:41 +00004847 return SQLITE_OK;
4848}
mistachkine98844f2013-08-24 00:59:24 +00004849#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004850
danaef49d72013-03-25 16:28:54 +00004851/*
4852** If possible, return a pointer to a mapping of file fd starting at offset
4853** iOff. The mapping must be valid for at least nAmt bytes.
4854**
4855** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4856** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4857** Finally, if an error does occur, return an SQLite error code. The final
4858** value of *pp is undefined in this case.
4859**
4860** If this function does return a pointer, the caller must eventually
4861** release the reference by calling unixUnfetch().
4862*/
danf23da962013-03-23 21:00:41 +00004863static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004864#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004865 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004866#endif
danf23da962013-03-23 21:00:41 +00004867 *pp = 0;
4868
drh9b4c59f2013-04-15 17:03:42 +00004869#if SQLITE_MAX_MMAP_SIZE>0
4870 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004871 if( pFd->pMapRegion==0 ){
4872 int rc = unixMapfile(pFd, -1);
4873 if( rc!=SQLITE_OK ) return rc;
4874 }
4875 if( pFd->mmapSize >= iOff+nAmt ){
4876 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4877 pFd->nFetchOut++;
4878 }
4879 }
drh6e0b6d52013-04-09 16:19:20 +00004880#endif
danf23da962013-03-23 21:00:41 +00004881 return SQLITE_OK;
4882}
4883
danaef49d72013-03-25 16:28:54 +00004884/*
dandf737fe2013-03-25 17:00:24 +00004885** If the third argument is non-NULL, then this function releases a
4886** reference obtained by an earlier call to unixFetch(). The second
4887** argument passed to this function must be the same as the corresponding
4888** argument that was passed to the unixFetch() invocation.
4889**
4890** Or, if the third argument is NULL, then this function is being called
4891** to inform the VFS layer that, according to POSIX, any existing mapping
4892** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004893*/
dandf737fe2013-03-25 17:00:24 +00004894static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004895#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004896 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004897 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004898
danaef49d72013-03-25 16:28:54 +00004899 /* If p==0 (unmap the entire file) then there must be no outstanding
4900 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4901 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004902 assert( (p==0)==(pFd->nFetchOut==0) );
4903
dandf737fe2013-03-25 17:00:24 +00004904 /* If p!=0, it must match the iOff value. */
4905 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4906
danf23da962013-03-23 21:00:41 +00004907 if( p ){
4908 pFd->nFetchOut--;
4909 }else{
4910 unixUnmapfile(pFd);
4911 }
4912
4913 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004914#else
4915 UNUSED_PARAMETER(fd);
4916 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004917 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004918#endif
danf23da962013-03-23 21:00:41 +00004919 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004920}
4921
4922/*
drh734c9862008-11-28 15:37:20 +00004923** Here ends the implementation of all sqlite3_file methods.
4924**
4925********************** End sqlite3_file Methods *******************************
4926******************************************************************************/
4927
4928/*
drh6b9d6dd2008-12-03 19:34:47 +00004929** This division contains definitions of sqlite3_io_methods objects that
4930** implement various file locking strategies. It also contains definitions
4931** of "finder" functions. A finder-function is used to locate the appropriate
4932** sqlite3_io_methods object for a particular database file. The pAppData
4933** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4934** the correct finder-function for that VFS.
4935**
4936** Most finder functions return a pointer to a fixed sqlite3_io_methods
4937** object. The only interesting finder-function is autolockIoFinder, which
4938** looks at the filesystem type and tries to guess the best locking
4939** strategy from that.
4940**
peter.d.reid60ec9142014-09-06 16:39:46 +00004941** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004942**
4943** (1) The real finder-function named "FImpt()".
4944**
dane946c392009-08-22 11:39:46 +00004945** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004946**
4947**
4948** A pointer to the F pointer is used as the pAppData value for VFS
4949** objects. We have to do this instead of letting pAppData point
4950** directly at the finder-function since C90 rules prevent a void*
4951** from be cast into a function pointer.
4952**
drh6b9d6dd2008-12-03 19:34:47 +00004953**
drh7708e972008-11-29 00:56:52 +00004954** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004955**
drh7708e972008-11-29 00:56:52 +00004956** * A constant sqlite3_io_methods object call METHOD that has locking
4957** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4958**
4959** * An I/O method finder function called FINDER that returns a pointer
4960** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004961*/
drhe6d41732015-02-21 00:49:00 +00004962#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004963static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004964 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004965 CLOSE, /* xClose */ \
4966 unixRead, /* xRead */ \
4967 unixWrite, /* xWrite */ \
4968 unixTruncate, /* xTruncate */ \
4969 unixSync, /* xSync */ \
4970 unixFileSize, /* xFileSize */ \
4971 LOCK, /* xLock */ \
4972 UNLOCK, /* xUnlock */ \
4973 CKLOCK, /* xCheckReservedLock */ \
4974 unixFileControl, /* xFileControl */ \
4975 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004976 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004977 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004978 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004979 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004980 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004981 unixFetch, /* xFetch */ \
4982 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004983}; \
drh0c2694b2009-09-03 16:23:44 +00004984static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4985 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004986 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004987} \
drh0c2694b2009-09-03 16:23:44 +00004988static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004989 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004990
4991/*
4992** Here are all of the sqlite3_io_methods objects for each of the
4993** locking strategies. Functions that return pointers to these methods
4994** are also created.
4995*/
4996IOMETHODS(
4997 posixIoFinder, /* Finder function name */
4998 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004999 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005000 unixClose, /* xClose method */
5001 unixLock, /* xLock method */
5002 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005003 unixCheckReservedLock, /* xCheckReservedLock method */
5004 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005005)
drh7708e972008-11-29 00:56:52 +00005006IOMETHODS(
5007 nolockIoFinder, /* Finder function name */
5008 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005009 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005010 nolockClose, /* xClose method */
5011 nolockLock, /* xLock method */
5012 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005013 nolockCheckReservedLock, /* xCheckReservedLock method */
5014 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005015)
drh7708e972008-11-29 00:56:52 +00005016IOMETHODS(
5017 dotlockIoFinder, /* Finder function name */
5018 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005019 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005020 dotlockClose, /* xClose method */
5021 dotlockLock, /* xLock method */
5022 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005023 dotlockCheckReservedLock, /* xCheckReservedLock method */
5024 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005025)
drh7708e972008-11-29 00:56:52 +00005026
chw78a13182009-04-07 05:35:03 +00005027#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005028IOMETHODS(
5029 flockIoFinder, /* Finder function name */
5030 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005031 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005032 flockClose, /* xClose method */
5033 flockLock, /* xLock method */
5034 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005035 flockCheckReservedLock, /* xCheckReservedLock method */
5036 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005037)
drh7708e972008-11-29 00:56:52 +00005038#endif
5039
drh6c7d5c52008-11-21 20:32:33 +00005040#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005041IOMETHODS(
5042 semIoFinder, /* Finder function name */
5043 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005044 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005045 semXClose, /* xClose method */
5046 semXLock, /* xLock method */
5047 semXUnlock, /* xUnlock method */
5048 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005049 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005050)
aswiftaebf4132008-11-21 00:10:35 +00005051#endif
drh7708e972008-11-29 00:56:52 +00005052
drhd2cb50b2009-01-09 21:41:17 +00005053#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005054IOMETHODS(
5055 afpIoFinder, /* Finder function name */
5056 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005057 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005058 afpClose, /* xClose method */
5059 afpLock, /* xLock method */
5060 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005061 afpCheckReservedLock, /* xCheckReservedLock method */
5062 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005063)
drh715ff302008-12-03 22:32:44 +00005064#endif
5065
5066/*
5067** The proxy locking method is a "super-method" in the sense that it
5068** opens secondary file descriptors for the conch and lock files and
5069** it uses proxy, dot-file, AFP, and flock() locking methods on those
5070** secondary files. For this reason, the division that implements
5071** proxy locking is located much further down in the file. But we need
5072** to go ahead and define the sqlite3_io_methods and finder function
5073** for proxy locking here. So we forward declare the I/O methods.
5074*/
drhd2cb50b2009-01-09 21:41:17 +00005075#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005076static int proxyClose(sqlite3_file*);
5077static int proxyLock(sqlite3_file*, int);
5078static int proxyUnlock(sqlite3_file*, int);
5079static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005080IOMETHODS(
5081 proxyIoFinder, /* Finder function name */
5082 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005083 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005084 proxyClose, /* xClose method */
5085 proxyLock, /* xLock method */
5086 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005087 proxyCheckReservedLock, /* xCheckReservedLock method */
5088 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005089)
aswiftaebf4132008-11-21 00:10:35 +00005090#endif
drh7708e972008-11-29 00:56:52 +00005091
drh7ed97b92010-01-20 13:07:21 +00005092/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5093#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5094IOMETHODS(
5095 nfsIoFinder, /* Finder function name */
5096 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005097 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005098 unixClose, /* xClose method */
5099 unixLock, /* xLock method */
5100 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005101 unixCheckReservedLock, /* xCheckReservedLock method */
5102 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005103)
5104#endif
drh7708e972008-11-29 00:56:52 +00005105
drhd2cb50b2009-01-09 21:41:17 +00005106#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005107/*
drh6b9d6dd2008-12-03 19:34:47 +00005108** This "finder" function attempts to determine the best locking strategy
5109** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005110** object that implements that strategy.
5111**
5112** This is for MacOSX only.
5113*/
drh1875f7a2008-12-08 18:19:17 +00005114static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005115 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005116 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005117){
5118 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005119 const char *zFilesystem; /* Filesystem type name */
5120 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005121 } aMap[] = {
5122 { "hfs", &posixIoMethods },
5123 { "ufs", &posixIoMethods },
5124 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005125 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005126 { "webdav", &nolockIoMethods },
5127 { 0, 0 }
5128 };
5129 int i;
5130 struct statfs fsInfo;
5131 struct flock lockInfo;
5132
5133 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005134 /* If filePath==NULL that means we are dealing with a transient file
5135 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005136 return &nolockIoMethods;
5137 }
5138 if( statfs(filePath, &fsInfo) != -1 ){
5139 if( fsInfo.f_flags & MNT_RDONLY ){
5140 return &nolockIoMethods;
5141 }
5142 for(i=0; aMap[i].zFilesystem; i++){
5143 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5144 return aMap[i].pMethods;
5145 }
5146 }
5147 }
5148
5149 /* Default case. Handles, amongst others, "nfs".
5150 ** Test byte-range lock using fcntl(). If the call succeeds,
5151 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005152 */
drh7708e972008-11-29 00:56:52 +00005153 lockInfo.l_len = 1;
5154 lockInfo.l_start = 0;
5155 lockInfo.l_whence = SEEK_SET;
5156 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005157 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005158 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5159 return &nfsIoMethods;
5160 } else {
5161 return &posixIoMethods;
5162 }
drh7708e972008-11-29 00:56:52 +00005163 }else{
5164 return &dotlockIoMethods;
5165 }
5166}
drh0c2694b2009-09-03 16:23:44 +00005167static const sqlite3_io_methods
5168 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005169
drhd2cb50b2009-01-09 21:41:17 +00005170#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005171
chw78a13182009-04-07 05:35:03 +00005172#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5173/*
5174** This "finder" function attempts to determine the best locking strategy
5175** for the database file "filePath". It then returns the sqlite3_io_methods
5176** object that implements that strategy.
5177**
5178** This is for VXWorks only.
5179*/
5180static const sqlite3_io_methods *autolockIoFinderImpl(
5181 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005182 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005183){
5184 struct flock lockInfo;
5185
5186 if( !filePath ){
5187 /* If filePath==NULL that means we are dealing with a transient file
5188 ** that does not need to be locked. */
5189 return &nolockIoMethods;
5190 }
5191
5192 /* Test if fcntl() is supported and use POSIX style locks.
5193 ** Otherwise fall back to the named semaphore method.
5194 */
5195 lockInfo.l_len = 1;
5196 lockInfo.l_start = 0;
5197 lockInfo.l_whence = SEEK_SET;
5198 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005199 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005200 return &posixIoMethods;
5201 }else{
5202 return &semIoMethods;
5203 }
5204}
drh0c2694b2009-09-03 16:23:44 +00005205static const sqlite3_io_methods
5206 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005207
5208#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5209
drh7708e972008-11-29 00:56:52 +00005210/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005211** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005212*/
drh0c2694b2009-09-03 16:23:44 +00005213typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005214
aswiftaebf4132008-11-21 00:10:35 +00005215
drh734c9862008-11-28 15:37:20 +00005216/****************************************************************************
5217**************************** sqlite3_vfs methods ****************************
5218**
5219** This division contains the implementation of methods on the
5220** sqlite3_vfs object.
5221*/
5222
danielk1977a3d4c882007-03-23 10:08:38 +00005223/*
danielk1977e339d652008-06-28 11:23:00 +00005224** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005225*/
5226static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005227 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005228 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005229 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005230 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005231 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005232){
drh7708e972008-11-29 00:56:52 +00005233 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005234 unixFile *pNew = (unixFile *)pId;
5235 int rc = SQLITE_OK;
5236
drh8af6c222010-05-14 12:43:01 +00005237 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005238
dan00157392010-10-05 11:33:15 +00005239 /* Usually the path zFilename should not be a relative pathname. The
5240 ** exception is when opening the proxy "conch" file in builds that
5241 ** include the special Apple locking styles.
5242 */
dan00157392010-10-05 11:33:15 +00005243#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005244 assert( zFilename==0 || zFilename[0]=='/'
5245 || pVfs->pAppData==(void*)&autolockIoFinder );
5246#else
5247 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005248#endif
dan00157392010-10-05 11:33:15 +00005249
drhb07028f2011-10-14 21:49:18 +00005250 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005251 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005252
drh308c2a52010-05-14 11:30:18 +00005253 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005254 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005255 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005256 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005257 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005258#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005259 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005260#endif
drhc02a43a2012-01-10 23:18:38 +00005261 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5262 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005263 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005264 }
drh503a6862013-03-01 01:07:17 +00005265 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005266 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005267 }
drh339eb0b2008-03-07 15:34:11 +00005268
drh6c7d5c52008-11-21 20:32:33 +00005269#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005270 pNew->pId = vxworksFindFileId(zFilename);
5271 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005272 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005273 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005274 }
5275#endif
5276
drhc02a43a2012-01-10 23:18:38 +00005277 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005278 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005279 }else{
drh0c2694b2009-09-03 16:23:44 +00005280 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005281#if SQLITE_ENABLE_LOCKING_STYLE
5282 /* Cache zFilename in the locking context (AFP and dotlock override) for
5283 ** proxyLock activation is possible (remote proxy is based on db name)
5284 ** zFilename remains valid until file is closed, to support */
5285 pNew->lockingContext = (void*)zFilename;
5286#endif
drhda0e7682008-07-30 15:27:54 +00005287 }
danielk1977e339d652008-06-28 11:23:00 +00005288
drh7ed97b92010-01-20 13:07:21 +00005289 if( pLockingStyle == &posixIoMethods
5290#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5291 || pLockingStyle == &nfsIoMethods
5292#endif
5293 ){
drh7708e972008-11-29 00:56:52 +00005294 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005295 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005296 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005297 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005298 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005299 ** in two scenarios:
5300 **
5301 ** (a) A call to fstat() failed.
5302 ** (b) A malloc failed.
5303 **
5304 ** Scenario (b) may only occur if the process is holding no other
5305 ** file descriptors open on the same file. If there were other file
5306 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005307 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005308 ** handle h - as it is guaranteed that no posix locks will be released
5309 ** by doing so.
5310 **
5311 ** If scenario (a) caused the error then things are not so safe. The
5312 ** implicit assumption here is that if fstat() fails, things are in
5313 ** such bad shape that dropping a lock or two doesn't matter much.
5314 */
drh0e9365c2011-03-02 02:08:13 +00005315 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005316 h = -1;
5317 }
drh7708e972008-11-29 00:56:52 +00005318 unixLeaveMutex();
5319 }
danielk1977e339d652008-06-28 11:23:00 +00005320
drhd2cb50b2009-01-09 21:41:17 +00005321#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005322 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005323 /* AFP locking uses the file path so it needs to be included in
5324 ** the afpLockingContext.
5325 */
5326 afpLockingContext *pCtx;
5327 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5328 if( pCtx==0 ){
5329 rc = SQLITE_NOMEM;
5330 }else{
5331 /* NB: zFilename exists and remains valid until the file is closed
5332 ** according to requirement F11141. So we do not need to make a
5333 ** copy of the filename. */
5334 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005335 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005336 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005337 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005338 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005339 if( rc!=SQLITE_OK ){
5340 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005341 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005342 h = -1;
5343 }
drh7708e972008-11-29 00:56:52 +00005344 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005345 }
drh7708e972008-11-29 00:56:52 +00005346 }
5347#endif
danielk1977e339d652008-06-28 11:23:00 +00005348
drh7708e972008-11-29 00:56:52 +00005349 else if( pLockingStyle == &dotlockIoMethods ){
5350 /* Dotfile locking uses the file path so it needs to be included in
5351 ** the dotlockLockingContext
5352 */
5353 char *zLockFile;
5354 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005355 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005356 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005357 zLockFile = (char *)sqlite3_malloc(nFilename);
5358 if( zLockFile==0 ){
5359 rc = SQLITE_NOMEM;
5360 }else{
5361 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005362 }
drh7708e972008-11-29 00:56:52 +00005363 pNew->lockingContext = zLockFile;
5364 }
danielk1977e339d652008-06-28 11:23:00 +00005365
drh6c7d5c52008-11-21 20:32:33 +00005366#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005367 else if( pLockingStyle == &semIoMethods ){
5368 /* Named semaphore locking uses the file path so it needs to be
5369 ** included in the semLockingContext
5370 */
5371 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005372 rc = findInodeInfo(pNew, &pNew->pInode);
5373 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5374 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005375 int n;
drh2238dcc2009-08-27 17:56:20 +00005376 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005377 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005378 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005379 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005380 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5381 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005382 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005383 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005384 }
chw97185482008-11-17 08:05:31 +00005385 }
drh7708e972008-11-29 00:56:52 +00005386 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005387 }
drh7708e972008-11-29 00:56:52 +00005388#endif
aswift5b1a2562008-08-22 00:22:35 +00005389
drh4bf66fd2015-02-19 02:43:02 +00005390 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005391#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005392 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005393 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005394 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005395 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005396 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005397 }
chw97185482008-11-17 08:05:31 +00005398#endif
danielk1977e339d652008-06-28 11:23:00 +00005399 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005400 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005401 }else{
drh7708e972008-11-29 00:56:52 +00005402 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005403 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005404 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005405 }
danielk1977e339d652008-06-28 11:23:00 +00005406 return rc;
drh054889e2005-11-30 03:20:31 +00005407}
drh9c06c952005-11-26 00:25:00 +00005408
danielk1977ad94b582007-08-20 06:44:22 +00005409/*
drh8b3cf822010-06-01 21:02:51 +00005410** Return the name of a directory in which to put temporary files.
5411** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005412*/
drh7234c6d2010-06-19 15:10:09 +00005413static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005414 static const char *azDirs[] = {
5415 0,
aswiftaebf4132008-11-21 00:10:35 +00005416 0,
mistachkind95a3d32013-08-30 21:52:38 +00005417 0,
danielk197717b90b52008-06-06 11:11:25 +00005418 "/var/tmp",
5419 "/usr/tmp",
5420 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005421 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005422 };
drh8b3cf822010-06-01 21:02:51 +00005423 unsigned int i;
5424 struct stat buf;
5425 const char *zDir = 0;
5426
5427 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005428 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5429 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005430 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005431 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005432 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005433 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005434 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005435 break;
5436 }
5437 return zDir;
5438}
5439
5440/*
5441** Create a temporary file name in zBuf. zBuf must be allocated
5442** by the calling process and must be big enough to hold at least
5443** pVfs->mxPathname bytes.
5444*/
5445static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005446 static const unsigned char zChars[] =
5447 "abcdefghijklmnopqrstuvwxyz"
5448 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5449 "0123456789";
drh41022642008-11-21 00:24:42 +00005450 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005451 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005452
5453 /* It's odd to simulate an io-error here, but really this is just
5454 ** using the io-error infrastructure to test that SQLite handles this
5455 ** function failing.
5456 */
5457 SimulateIOError( return SQLITE_IOERR );
5458
drh7234c6d2010-06-19 15:10:09 +00005459 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005460 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005461
5462 /* Check that the output buffer is large enough for the temporary file
5463 ** name. If it is not, return SQLITE_ERROR.
5464 */
drhc02a43a2012-01-10 23:18:38 +00005465 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005466 return SQLITE_ERROR;
5467 }
5468
5469 do{
drhc02a43a2012-01-10 23:18:38 +00005470 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005471 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005472 sqlite3_randomness(15, &zBuf[j]);
5473 for(i=0; i<15; i++, j++){
5474 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5475 }
5476 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005477 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005478 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005479 return SQLITE_OK;
5480}
5481
drhd2cb50b2009-01-09 21:41:17 +00005482#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005483/*
5484** Routine to transform a unixFile into a proxy-locking unixFile.
5485** Implementation in the proxy-lock division, but used by unixOpen()
5486** if SQLITE_PREFER_PROXY_LOCKING is defined.
5487*/
5488static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005489#endif
drhc66d5b62008-12-03 22:48:32 +00005490
dan08da86a2009-08-21 17:18:03 +00005491/*
5492** Search for an unused file descriptor that was opened on the database
5493** file (not a journal or master-journal file) identified by pathname
5494** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5495** argument to this function.
5496**
5497** Such a file descriptor may exist if a database connection was closed
5498** but the associated file descriptor could not be closed because some
5499** other file descriptor open on the same file is holding a file-lock.
5500** Refer to comments in the unixClose() function and the lengthy comment
5501** describing "Posix Advisory Locking" at the start of this file for
5502** further details. Also, ticket #4018.
5503**
5504** If a suitable file descriptor is found, then it is returned. If no
5505** such file descriptor is located, -1 is returned.
5506*/
dane946c392009-08-22 11:39:46 +00005507static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5508 UnixUnusedFd *pUnused = 0;
5509
5510 /* Do not search for an unused file descriptor on vxworks. Not because
5511 ** vxworks would not benefit from the change (it might, we're not sure),
5512 ** but because no way to test it is currently available. It is better
5513 ** not to risk breaking vxworks support for the sake of such an obscure
5514 ** feature. */
5515#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005516 struct stat sStat; /* Results of stat() call */
5517
5518 /* A stat() call may fail for various reasons. If this happens, it is
5519 ** almost certain that an open() call on the same path will also fail.
5520 ** For this reason, if an error occurs in the stat() call here, it is
5521 ** ignored and -1 is returned. The caller will try to open a new file
5522 ** descriptor on the same path, fail, and return an error to SQLite.
5523 **
5524 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005525 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005526 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005527 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005528
5529 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005530 pInode = inodeList;
5531 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5532 || pInode->fileId.ino!=sStat.st_ino) ){
5533 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005534 }
drh8af6c222010-05-14 12:43:01 +00005535 if( pInode ){
dane946c392009-08-22 11:39:46 +00005536 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005537 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005538 pUnused = *pp;
5539 if( pUnused ){
5540 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005541 }
5542 }
5543 unixLeaveMutex();
5544 }
dane946c392009-08-22 11:39:46 +00005545#endif /* if !OS_VXWORKS */
5546 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005547}
danielk197717b90b52008-06-06 11:11:25 +00005548
5549/*
danddb0ac42010-07-14 14:48:58 +00005550** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005551** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005552** and a value suitable for passing as the third argument to open(2) is
5553** written to *pMode. If an IO error occurs, an SQLite error code is
5554** returned and the value of *pMode is not modified.
5555**
peter.d.reid60ec9142014-09-06 16:39:46 +00005556** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005557** an indication to robust_open() to create the file using
5558** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5559** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005560** this function queries the file-system for the permissions on the
5561** corresponding database file and sets *pMode to this value. Whenever
5562** possible, WAL and journal files are created using the same permissions
5563** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005564**
5565** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5566** original filename is unavailable. But 8_3_NAMES is only used for
5567** FAT filesystems and permissions do not matter there, so just use
5568** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005569*/
5570static int findCreateFileMode(
5571 const char *zPath, /* Path of file (possibly) being created */
5572 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005573 mode_t *pMode, /* OUT: Permissions to open file with */
5574 uid_t *pUid, /* OUT: uid to set on the file */
5575 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005576){
5577 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005578 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005579 *pUid = 0;
5580 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005581 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005582 char zDb[MAX_PATHNAME+1]; /* Database file path */
5583 int nDb; /* Number of valid bytes in zDb */
5584 struct stat sStat; /* Output of stat() on database file */
5585
dana0c989d2010-11-05 18:07:37 +00005586 /* zPath is a path to a WAL or journal file. The following block derives
5587 ** the path to the associated database file from zPath. This block handles
5588 ** the following naming conventions:
5589 **
5590 ** "<path to db>-journal"
5591 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005592 ** "<path to db>-journalNN"
5593 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005594 **
drhd337c5b2011-10-20 18:23:35 +00005595 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005596 ** used by the test_multiplex.c module.
5597 */
5598 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005599#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005600 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005601 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005602#else
5603 while( zPath[nDb]!='-' ){
5604 assert( nDb>0 );
5605 assert( zPath[nDb]!='\n' );
5606 nDb--;
5607 }
5608#endif
danddb0ac42010-07-14 14:48:58 +00005609 memcpy(zDb, zPath, nDb);
5610 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005611
drh58384f12011-07-28 00:14:45 +00005612 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005613 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005614 *pUid = sStat.st_uid;
5615 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005616 }else{
5617 rc = SQLITE_IOERR_FSTAT;
5618 }
5619 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5620 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005621 }
5622 return rc;
5623}
5624
5625/*
danielk1977ad94b582007-08-20 06:44:22 +00005626** Open the file zPath.
5627**
danielk1977b4b47412007-08-17 15:53:36 +00005628** Previously, the SQLite OS layer used three functions in place of this
5629** one:
5630**
5631** sqlite3OsOpenReadWrite();
5632** sqlite3OsOpenReadOnly();
5633** sqlite3OsOpenExclusive();
5634**
5635** These calls correspond to the following combinations of flags:
5636**
5637** ReadWrite() -> (READWRITE | CREATE)
5638** ReadOnly() -> (READONLY)
5639** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5640**
5641** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5642** true, the file was configured to be automatically deleted when the
5643** file handle closed. To achieve the same effect using this new
5644** interface, add the DELETEONCLOSE flag to those specified above for
5645** OpenExclusive().
5646*/
5647static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005648 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5649 const char *zPath, /* Pathname of file to be opened */
5650 sqlite3_file *pFile, /* The file descriptor to be filled in */
5651 int flags, /* Input flags to control the opening */
5652 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005653){
dan08da86a2009-08-21 17:18:03 +00005654 unixFile *p = (unixFile *)pFile;
5655 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005656 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005657 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005658 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005659 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005660 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005661
5662 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5663 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5664 int isCreate = (flags & SQLITE_OPEN_CREATE);
5665 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5666 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005667#if SQLITE_ENABLE_LOCKING_STYLE
5668 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5669#endif
drh3d4435b2011-08-26 20:55:50 +00005670#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5671 struct statfs fsInfo;
5672#endif
danielk1977b4b47412007-08-17 15:53:36 +00005673
danielk1977fee2d252007-08-18 10:59:19 +00005674 /* If creating a master or main-file journal, this function will open
5675 ** a file-descriptor on the directory too. The first time unixSync()
5676 ** is called the directory file descriptor will be fsync()ed and close()d.
5677 */
drh0059eae2011-08-08 23:48:40 +00005678 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005679 eType==SQLITE_OPEN_MASTER_JOURNAL
5680 || eType==SQLITE_OPEN_MAIN_JOURNAL
5681 || eType==SQLITE_OPEN_WAL
5682 ));
danielk1977fee2d252007-08-18 10:59:19 +00005683
danielk197717b90b52008-06-06 11:11:25 +00005684 /* If argument zPath is a NULL pointer, this function is required to open
5685 ** a temporary file. Use this buffer to store the file name in.
5686 */
drhc02a43a2012-01-10 23:18:38 +00005687 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005688 const char *zName = zPath;
5689
danielk1977fee2d252007-08-18 10:59:19 +00005690 /* Check the following statements are true:
5691 **
5692 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5693 ** (b) if CREATE is set, then READWRITE must also be set, and
5694 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005695 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005696 */
danielk1977b4b47412007-08-17 15:53:36 +00005697 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005698 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005699 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005700 assert(isDelete==0 || isCreate);
5701
danddb0ac42010-07-14 14:48:58 +00005702 /* The main DB, main journal, WAL file and master journal are never
5703 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005704 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5705 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5706 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005707 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005708
danielk1977fee2d252007-08-18 10:59:19 +00005709 /* Assert that the upper layer has set one of the "file-type" flags. */
5710 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5711 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5712 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005713 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005714 );
5715
drhb00d8622014-01-01 15:18:36 +00005716 /* Detect a pid change and reset the PRNG. There is a race condition
5717 ** here such that two or more threads all trying to open databases at
5718 ** the same instant might all reset the PRNG. But multiple resets
5719 ** are harmless.
5720 */
5721 if( randomnessPid!=getpid() ){
5722 randomnessPid = getpid();
5723 sqlite3_randomness(0,0);
5724 }
5725
dan08da86a2009-08-21 17:18:03 +00005726 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005727
dan08da86a2009-08-21 17:18:03 +00005728 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005729 UnixUnusedFd *pUnused;
5730 pUnused = findReusableFd(zName, flags);
5731 if( pUnused ){
5732 fd = pUnused->fd;
5733 }else{
dan6aa657f2009-08-24 18:57:58 +00005734 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005735 if( !pUnused ){
5736 return SQLITE_NOMEM;
5737 }
5738 }
5739 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005740
5741 /* Database filenames are double-zero terminated if they are not
5742 ** URIs with parameters. Hence, they can always be passed into
5743 ** sqlite3_uri_parameter(). */
5744 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5745
dan08da86a2009-08-21 17:18:03 +00005746 }else if( !zName ){
5747 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005748 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005749 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005750 if( rc!=SQLITE_OK ){
5751 return rc;
5752 }
5753 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005754
5755 /* Generated temporary filenames are always double-zero terminated
5756 ** for use by sqlite3_uri_parameter(). */
5757 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005758 }
5759
dan08da86a2009-08-21 17:18:03 +00005760 /* Determine the value of the flags parameter passed to POSIX function
5761 ** open(). These must be calculated even if open() is not called, as
5762 ** they may be stored as part of the file handle and used by the
5763 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005764 if( isReadonly ) openFlags |= O_RDONLY;
5765 if( isReadWrite ) openFlags |= O_RDWR;
5766 if( isCreate ) openFlags |= O_CREAT;
5767 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5768 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005769
danielk1977b4b47412007-08-17 15:53:36 +00005770 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005771 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005772 uid_t uid; /* Userid for the file */
5773 gid_t gid; /* Groupid for the file */
5774 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005775 if( rc!=SQLITE_OK ){
5776 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005777 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005778 return rc;
5779 }
drhad4f1e52011-03-04 15:43:57 +00005780 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005781 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005782 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5783 /* Failed to open the file for read/write access. Try read-only. */
5784 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005785 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005786 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005787 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005788 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005789 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005790 }
5791 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005792 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005793 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005794 }
drhac7c3ac2012-02-11 19:23:48 +00005795
5796 /* If this process is running as root and if creating a new rollback
5797 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005798 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005799 */
5800 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005801 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005802 }
danielk1977b4b47412007-08-17 15:53:36 +00005803 }
dan08da86a2009-08-21 17:18:03 +00005804 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005805 if( pOutFlags ){
5806 *pOutFlags = flags;
5807 }
5808
dane946c392009-08-22 11:39:46 +00005809 if( p->pUnused ){
5810 p->pUnused->fd = fd;
5811 p->pUnused->flags = flags;
5812 }
5813
danielk1977b4b47412007-08-17 15:53:36 +00005814 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005815#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005816 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005817#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5818 zPath = sqlite3_mprintf("%s", zName);
5819 if( zPath==0 ){
5820 robust_close(p, fd, __LINE__);
5821 return SQLITE_NOMEM;
5822 }
chw97185482008-11-17 08:05:31 +00005823#else
drh036ac7f2011-08-08 23:18:05 +00005824 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005825#endif
danielk1977b4b47412007-08-17 15:53:36 +00005826 }
drh41022642008-11-21 00:24:42 +00005827#if SQLITE_ENABLE_LOCKING_STYLE
5828 else{
dan08da86a2009-08-21 17:18:03 +00005829 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005830 }
5831#endif
5832
drhda0e7682008-07-30 15:27:54 +00005833 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005834
drh7ed97b92010-01-20 13:07:21 +00005835
5836#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005837 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005838 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005839 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005840 return SQLITE_IOERR_ACCESS;
5841 }
5842 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5843 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5844 }
drh4bf66fd2015-02-19 02:43:02 +00005845 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5846 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5847 }
drh7ed97b92010-01-20 13:07:21 +00005848#endif
drhc02a43a2012-01-10 23:18:38 +00005849
5850 /* Set up appropriate ctrlFlags */
5851 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5852 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5853 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5854 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5855 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5856
drh7ed97b92010-01-20 13:07:21 +00005857#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005858#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005859 isAutoProxy = 1;
5860#endif
5861 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005862 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5863 int useProxy = 0;
5864
dan08da86a2009-08-21 17:18:03 +00005865 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5866 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005867 if( envforce!=NULL ){
5868 useProxy = atoi(envforce)>0;
5869 }else{
aswiftaebf4132008-11-21 00:10:35 +00005870 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5871 }
5872 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005873 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005874 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005875 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005876 if( rc!=SQLITE_OK ){
5877 /* Use unixClose to clean up the resources added in fillInUnixFile
5878 ** and clear all the structure's references. Specifically,
5879 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5880 */
5881 unixClose(pFile);
5882 return rc;
5883 }
aswiftaebf4132008-11-21 00:10:35 +00005884 }
dane946c392009-08-22 11:39:46 +00005885 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005886 }
5887 }
5888#endif
5889
drhc02a43a2012-01-10 23:18:38 +00005890 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5891
dane946c392009-08-22 11:39:46 +00005892open_finished:
5893 if( rc!=SQLITE_OK ){
5894 sqlite3_free(p->pUnused);
5895 }
5896 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005897}
5898
dane946c392009-08-22 11:39:46 +00005899
danielk1977b4b47412007-08-17 15:53:36 +00005900/*
danielk1977fee2d252007-08-18 10:59:19 +00005901** Delete the file at zPath. If the dirSync argument is true, fsync()
5902** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005903*/
drh6b9d6dd2008-12-03 19:34:47 +00005904static int unixDelete(
5905 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5906 const char *zPath, /* Name of file to be deleted */
5907 int dirSync /* If true, fsync() directory after deleting file */
5908){
danielk1977fee2d252007-08-18 10:59:19 +00005909 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005910 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005911 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005912 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005913 if( errno==ENOENT
5914#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005915 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005916#endif
5917 ){
dan9fc5b4a2012-11-09 20:17:26 +00005918 rc = SQLITE_IOERR_DELETE_NOENT;
5919 }else{
drhb4308162012-11-09 21:40:02 +00005920 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005921 }
drhb4308162012-11-09 21:40:02 +00005922 return rc;
drh5d4feff2010-07-14 01:45:22 +00005923 }
danielk1977d39fa702008-10-16 13:27:40 +00005924#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005925 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005926 int fd;
drh90315a22011-08-10 01:52:12 +00005927 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005928 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005929#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005930 if( fsync(fd)==-1 )
5931#else
5932 if( fsync(fd) )
5933#endif
5934 {
dane18d4952011-02-21 11:46:24 +00005935 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005936 }
drh0e9365c2011-03-02 02:08:13 +00005937 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005938 }else if( rc==SQLITE_CANTOPEN ){
5939 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005940 }
5941 }
danielk1977d138dd82008-10-15 16:02:48 +00005942#endif
danielk1977fee2d252007-08-18 10:59:19 +00005943 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005944}
5945
danielk197790949c22007-08-17 16:50:38 +00005946/*
mistachkin48864df2013-03-21 21:20:32 +00005947** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005948** test performed depends on the value of flags:
5949**
5950** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5951** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5952** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5953**
5954** Otherwise return 0.
5955*/
danielk1977861f7452008-06-05 11:39:11 +00005956static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005957 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5958 const char *zPath, /* Path of the file to examine */
5959 int flags, /* What do we want to learn about the zPath file? */
5960 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005961){
rse25c0d1a2007-09-20 08:38:14 +00005962 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005963 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005964 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005965 switch( flags ){
5966 case SQLITE_ACCESS_EXISTS:
5967 amode = F_OK;
5968 break;
5969 case SQLITE_ACCESS_READWRITE:
5970 amode = W_OK|R_OK;
5971 break;
drh50d3f902007-08-27 21:10:36 +00005972 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005973 amode = R_OK;
5974 break;
5975
5976 default:
5977 assert(!"Invalid flags argument");
5978 }
drh99ab3b12011-03-02 15:09:07 +00005979 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005980 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5981 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005982 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005983 *pResOut = 0;
5984 }
5985 }
danielk1977861f7452008-06-05 11:39:11 +00005986 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005987}
5988
danielk1977b4b47412007-08-17 15:53:36 +00005989
5990/*
5991** Turn a relative pathname into a full pathname. The relative path
5992** is stored as a nul-terminated string in the buffer pointed to by
5993** zPath.
5994**
5995** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5996** (in this case, MAX_PATHNAME bytes). The full-path is written to
5997** this buffer before returning.
5998*/
danielk1977adfb9b02007-09-17 07:02:56 +00005999static int unixFullPathname(
6000 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6001 const char *zPath, /* Possibly relative input path */
6002 int nOut, /* Size of output buffer in bytes */
6003 char *zOut /* Output buffer */
6004){
danielk1977843e65f2007-09-01 16:16:15 +00006005
6006 /* It's odd to simulate an io-error here, but really this is just
6007 ** using the io-error infrastructure to test that SQLite handles this
6008 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006009 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006010 */
6011 SimulateIOError( return SQLITE_ERROR );
6012
drh153c62c2007-08-24 03:51:33 +00006013 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006014 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006015
drh3c7f2dc2007-12-06 13:26:20 +00006016 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00006017 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00006018 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006019 }else{
6020 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00006021 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006022 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006023 }
drhea678832008-12-10 19:26:22 +00006024 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00006025 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006026 }
6027 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006028}
6029
drh0ccebe72005-06-07 22:22:50 +00006030
drh761df872006-12-21 01:29:22 +00006031#ifndef SQLITE_OMIT_LOAD_EXTENSION
6032/*
6033** Interfaces for opening a shared library, finding entry points
6034** within the shared library, and closing the shared library.
6035*/
6036#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006037static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6038 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006039 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6040}
danielk197795c8a542007-09-01 06:51:27 +00006041
6042/*
6043** SQLite calls this function immediately after a call to unixDlSym() or
6044** unixDlOpen() fails (returns a null pointer). If a more detailed error
6045** message is available, it is written to zBufOut. If no error message
6046** is available, zBufOut is left unmodified and SQLite uses a default
6047** error message.
6048*/
danielk1977397d65f2008-11-19 11:35:39 +00006049static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006050 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006051 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006052 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006053 zErr = dlerror();
6054 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006055 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006056 }
drh6c7d5c52008-11-21 20:32:33 +00006057 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006058}
drh1875f7a2008-12-08 18:19:17 +00006059static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6060 /*
6061 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6062 ** cast into a pointer to a function. And yet the library dlsym() routine
6063 ** returns a void* which is really a pointer to a function. So how do we
6064 ** use dlsym() with -pedantic-errors?
6065 **
6066 ** Variable x below is defined to be a pointer to a function taking
6067 ** parameters void* and const char* and returning a pointer to a function.
6068 ** We initialize x by assigning it a pointer to the dlsym() function.
6069 ** (That assignment requires a cast.) Then we call the function that
6070 ** x points to.
6071 **
6072 ** This work-around is unlikely to work correctly on any system where
6073 ** you really cannot cast a function pointer into void*. But then, on the
6074 ** other hand, dlsym() will not work on such a system either, so we have
6075 ** not really lost anything.
6076 */
6077 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006078 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006079 x = (void(*(*)(void*,const char*))(void))dlsym;
6080 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006081}
danielk1977397d65f2008-11-19 11:35:39 +00006082static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6083 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006084 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006085}
danielk1977b4b47412007-08-17 15:53:36 +00006086#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6087 #define unixDlOpen 0
6088 #define unixDlError 0
6089 #define unixDlSym 0
6090 #define unixDlClose 0
6091#endif
6092
6093/*
danielk197790949c22007-08-17 16:50:38 +00006094** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006095*/
danielk1977397d65f2008-11-19 11:35:39 +00006096static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6097 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006098 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006099
drhbbd42a62004-05-22 17:41:58 +00006100 /* We have to initialize zBuf to prevent valgrind from reporting
6101 ** errors. The reports issued by valgrind are incorrect - we would
6102 ** prefer that the randomness be increased by making use of the
6103 ** uninitialized space in zBuf - but valgrind errors tend to worry
6104 ** some users. Rather than argue, it seems easier just to initialize
6105 ** the whole array and silence valgrind, even if that means less randomness
6106 ** in the random seed.
6107 **
6108 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006109 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006110 ** tests repeatable.
6111 */
danielk1977b4b47412007-08-17 15:53:36 +00006112 memset(zBuf, 0, nBuf);
drhb00d8622014-01-01 15:18:36 +00006113 randomnessPid = getpid();
drhbbd42a62004-05-22 17:41:58 +00006114#if !defined(SQLITE_TEST)
6115 {
drhb00d8622014-01-01 15:18:36 +00006116 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006117 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006118 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006119 time_t t;
6120 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006121 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006122 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6123 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6124 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006125 }else{
drhc18b4042012-02-10 03:10:27 +00006126 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006127 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006128 }
drhbbd42a62004-05-22 17:41:58 +00006129 }
6130#endif
drh72cbd072008-10-14 17:58:38 +00006131 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006132}
6133
danielk1977b4b47412007-08-17 15:53:36 +00006134
drhbbd42a62004-05-22 17:41:58 +00006135/*
6136** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006137** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006138** The return value is the number of microseconds of sleep actually
6139** requested from the underlying operating system, a number which
6140** might be greater than or equal to the argument, but not less
6141** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006142*/
danielk1977397d65f2008-11-19 11:35:39 +00006143static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006144#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006145 struct timespec sp;
6146
6147 sp.tv_sec = microseconds / 1000000;
6148 sp.tv_nsec = (microseconds % 1000000) * 1000;
6149 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006150 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006151 return microseconds;
6152#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006153 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006154 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006155 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006156#else
danielk1977b4b47412007-08-17 15:53:36 +00006157 int seconds = (microseconds+999999)/1000000;
6158 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006159 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006160 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006161#endif
drh88f474a2006-01-02 20:00:12 +00006162}
6163
6164/*
drh6b9d6dd2008-12-03 19:34:47 +00006165** The following variable, if set to a non-zero value, is interpreted as
6166** the number of seconds since 1970 and is used to set the result of
6167** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006168*/
6169#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006170int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006171#endif
6172
6173/*
drhb7e8ea22010-05-03 14:32:30 +00006174** Find the current time (in Universal Coordinated Time). Write into *piNow
6175** the current time and date as a Julian Day number times 86_400_000. In
6176** other words, write into *piNow the number of milliseconds since the Julian
6177** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6178** proleptic Gregorian calendar.
6179**
drh31702252011-10-12 23:13:43 +00006180** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6181** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006182*/
6183static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6184 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006185 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006186#if defined(NO_GETTOD)
6187 time_t t;
6188 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006189 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006190#elif OS_VXWORKS
6191 struct timespec sNow;
6192 clock_gettime(CLOCK_REALTIME, &sNow);
6193 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6194#else
6195 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006196 if( gettimeofday(&sNow, 0)==0 ){
6197 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6198 }else{
6199 rc = SQLITE_ERROR;
6200 }
drhb7e8ea22010-05-03 14:32:30 +00006201#endif
6202
6203#ifdef SQLITE_TEST
6204 if( sqlite3_current_time ){
6205 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6206 }
6207#endif
6208 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006209 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006210}
6211
6212/*
drhbbd42a62004-05-22 17:41:58 +00006213** Find the current time (in Universal Coordinated Time). Write the
6214** current time and date as a Julian Day number into *prNow and
6215** return 0. Return 1 if the time and date cannot be found.
6216*/
danielk1977397d65f2008-11-19 11:35:39 +00006217static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006218 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006219 int rc;
drhff828942010-06-26 21:34:06 +00006220 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006221 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006222 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006223 return rc;
drhbbd42a62004-05-22 17:41:58 +00006224}
danielk1977b4b47412007-08-17 15:53:36 +00006225
drh6b9d6dd2008-12-03 19:34:47 +00006226/*
6227** We added the xGetLastError() method with the intention of providing
6228** better low-level error messages when operating-system problems come up
6229** during SQLite operation. But so far, none of that has been implemented
6230** in the core. So this routine is never called. For now, it is merely
6231** a place-holder.
6232*/
danielk1977397d65f2008-11-19 11:35:39 +00006233static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6234 UNUSED_PARAMETER(NotUsed);
6235 UNUSED_PARAMETER(NotUsed2);
6236 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006237 return 0;
6238}
6239
drhf2424c52010-04-26 00:04:55 +00006240
6241/*
drh734c9862008-11-28 15:37:20 +00006242************************ End of sqlite3_vfs methods ***************************
6243******************************************************************************/
6244
drh715ff302008-12-03 22:32:44 +00006245/******************************************************************************
6246************************** Begin Proxy Locking ********************************
6247**
6248** Proxy locking is a "uber-locking-method" in this sense: It uses the
6249** other locking methods on secondary lock files. Proxy locking is a
6250** meta-layer over top of the primitive locking implemented above. For
6251** this reason, the division that implements of proxy locking is deferred
6252** until late in the file (here) after all of the other I/O methods have
6253** been defined - so that the primitive locking methods are available
6254** as services to help with the implementation of proxy locking.
6255**
6256****
6257**
6258** The default locking schemes in SQLite use byte-range locks on the
6259** database file to coordinate safe, concurrent access by multiple readers
6260** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6261** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6262** as POSIX read & write locks over fixed set of locations (via fsctl),
6263** on AFP and SMB only exclusive byte-range locks are available via fsctl
6264** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6265** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6266** address in the shared range is taken for a SHARED lock, the entire
6267** shared range is taken for an EXCLUSIVE lock):
6268**
drhf2f105d2012-08-20 15:53:54 +00006269** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006270** RESERVED_BYTE 0x40000001
6271** SHARED_RANGE 0x40000002 -> 0x40000200
6272**
6273** This works well on the local file system, but shows a nearly 100x
6274** slowdown in read performance on AFP because the AFP client disables
6275** the read cache when byte-range locks are present. Enabling the read
6276** cache exposes a cache coherency problem that is present on all OS X
6277** supported network file systems. NFS and AFP both observe the
6278** close-to-open semantics for ensuring cache coherency
6279** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6280** address the requirements for concurrent database access by multiple
6281** readers and writers
6282** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6283**
6284** To address the performance and cache coherency issues, proxy file locking
6285** changes the way database access is controlled by limiting access to a
6286** single host at a time and moving file locks off of the database file
6287** and onto a proxy file on the local file system.
6288**
6289**
6290** Using proxy locks
6291** -----------------
6292**
6293** C APIs
6294**
drh4bf66fd2015-02-19 02:43:02 +00006295** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006296** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006297** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6298** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006299**
6300**
6301** SQL pragmas
6302**
6303** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6304** PRAGMA [database.]lock_proxy_file
6305**
6306** Specifying ":auto:" means that if there is a conch file with a matching
6307** host ID in it, the proxy path in the conch file will be used, otherwise
6308** a proxy path based on the user's temp dir
6309** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6310** actual proxy file name is generated from the name and path of the
6311** database file. For example:
6312**
6313** For database path "/Users/me/foo.db"
6314** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6315**
6316** Once a lock proxy is configured for a database connection, it can not
6317** be removed, however it may be switched to a different proxy path via
6318** the above APIs (assuming the conch file is not being held by another
6319** connection or process).
6320**
6321**
6322** How proxy locking works
6323** -----------------------
6324**
6325** Proxy file locking relies primarily on two new supporting files:
6326**
6327** * conch file to limit access to the database file to a single host
6328** at a time
6329**
6330** * proxy file to act as a proxy for the advisory locks normally
6331** taken on the database
6332**
6333** The conch file - to use a proxy file, sqlite must first "hold the conch"
6334** by taking an sqlite-style shared lock on the conch file, reading the
6335** contents and comparing the host's unique host ID (see below) and lock
6336** proxy path against the values stored in the conch. The conch file is
6337** stored in the same directory as the database file and the file name
6338** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006339** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006340** host ID and/or proxy path, then the lock is escalated to an exclusive
6341** lock and the conch file contents is updated with the host ID and proxy
6342** path and the lock is downgraded to a shared lock again. If the conch
6343** is held by another process (with a shared lock), the exclusive lock
6344** will fail and SQLITE_BUSY is returned.
6345**
6346** The proxy file - a single-byte file used for all advisory file locks
6347** normally taken on the database file. This allows for safe sharing
6348** of the database file for multiple readers and writers on the same
6349** host (the conch ensures that they all use the same local lock file).
6350**
drh715ff302008-12-03 22:32:44 +00006351** Requesting the lock proxy does not immediately take the conch, it is
6352** only taken when the first request to lock database file is made.
6353** This matches the semantics of the traditional locking behavior, where
6354** opening a connection to a database file does not take a lock on it.
6355** The shared lock and an open file descriptor are maintained until
6356** the connection to the database is closed.
6357**
6358** The proxy file and the lock file are never deleted so they only need
6359** to be created the first time they are used.
6360**
6361** Configuration options
6362** ---------------------
6363**
6364** SQLITE_PREFER_PROXY_LOCKING
6365**
6366** Database files accessed on non-local file systems are
6367** automatically configured for proxy locking, lock files are
6368** named automatically using the same logic as
6369** PRAGMA lock_proxy_file=":auto:"
6370**
6371** SQLITE_PROXY_DEBUG
6372**
6373** Enables the logging of error messages during host id file
6374** retrieval and creation
6375**
drh715ff302008-12-03 22:32:44 +00006376** LOCKPROXYDIR
6377**
6378** Overrides the default directory used for lock proxy files that
6379** are named automatically via the ":auto:" setting
6380**
6381** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6382**
6383** Permissions to use when creating a directory for storing the
6384** lock proxy files, only used when LOCKPROXYDIR is not set.
6385**
6386**
6387** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6388** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6389** force proxy locking to be used for every database file opened, and 0
6390** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006391** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006392** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6393*/
6394
6395/*
6396** Proxy locking is only available on MacOSX
6397*/
drhd2cb50b2009-01-09 21:41:17 +00006398#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006399
drh715ff302008-12-03 22:32:44 +00006400/*
6401** The proxyLockingContext has the path and file structures for the remote
6402** and local proxy files in it
6403*/
6404typedef struct proxyLockingContext proxyLockingContext;
6405struct proxyLockingContext {
6406 unixFile *conchFile; /* Open conch file */
6407 char *conchFilePath; /* Name of the conch file */
6408 unixFile *lockProxy; /* Open proxy lock file */
6409 char *lockProxyPath; /* Name of the proxy lock file */
6410 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006411 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006412 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006413 void *oldLockingContext; /* Original lockingcontext to restore on close */
6414 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6415};
6416
drh7ed97b92010-01-20 13:07:21 +00006417/*
6418** The proxy lock file path for the database at dbPath is written into lPath,
6419** which must point to valid, writable memory large enough for a maxLen length
6420** file path.
drh715ff302008-12-03 22:32:44 +00006421*/
drh715ff302008-12-03 22:32:44 +00006422static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6423 int len;
6424 int dbLen;
6425 int i;
6426
6427#ifdef LOCKPROXYDIR
6428 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6429#else
6430# ifdef _CS_DARWIN_USER_TEMP_DIR
6431 {
drh7ed97b92010-01-20 13:07:21 +00006432 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006433 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6434 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006435 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006436 }
drh7ed97b92010-01-20 13:07:21 +00006437 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006438 }
6439# else
6440 len = strlcpy(lPath, "/tmp/", maxLen);
6441# endif
6442#endif
6443
6444 if( lPath[len-1]!='/' ){
6445 len = strlcat(lPath, "/", maxLen);
6446 }
6447
6448 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006449 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006450 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006451 char c = dbPath[i];
6452 lPath[i+len] = (c=='/')?'_':c;
6453 }
6454 lPath[i+len]='\0';
6455 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006456 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006457 return SQLITE_OK;
6458}
6459
drh7ed97b92010-01-20 13:07:21 +00006460/*
6461 ** Creates the lock file and any missing directories in lockPath
6462 */
6463static int proxyCreateLockPath(const char *lockPath){
6464 int i, len;
6465 char buf[MAXPATHLEN];
6466 int start = 0;
6467
6468 assert(lockPath!=NULL);
6469 /* try to create all the intermediate directories */
6470 len = (int)strlen(lockPath);
6471 buf[0] = lockPath[0];
6472 for( i=1; i<len; i++ ){
6473 if( lockPath[i] == '/' && (i - start > 0) ){
6474 /* only mkdir if leaf dir != "." or "/" or ".." */
6475 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6476 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6477 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006478 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006479 int err=errno;
6480 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006481 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006482 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006483 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006484 return err;
6485 }
6486 }
6487 }
6488 start=i+1;
6489 }
6490 buf[i] = lockPath[i];
6491 }
drh308c2a52010-05-14 11:30:18 +00006492 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006493 return 0;
6494}
6495
drh715ff302008-12-03 22:32:44 +00006496/*
6497** Create a new VFS file descriptor (stored in memory obtained from
6498** sqlite3_malloc) and open the file named "path" in the file descriptor.
6499**
6500** The caller is responsible not only for closing the file descriptor
6501** but also for freeing the memory associated with the file descriptor.
6502*/
drh7ed97b92010-01-20 13:07:21 +00006503static int proxyCreateUnixFile(
6504 const char *path, /* path for the new unixFile */
6505 unixFile **ppFile, /* unixFile created and returned by ref */
6506 int islockfile /* if non zero missing dirs will be created */
6507) {
6508 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006509 unixFile *pNew;
6510 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006511 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006512 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006513 int terrno = 0;
6514 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006515
drh7ed97b92010-01-20 13:07:21 +00006516 /* 1. first try to open/create the file
6517 ** 2. if that fails, and this is a lock file (not-conch), try creating
6518 ** the parent directories and then try again.
6519 ** 3. if that fails, try to open the file read-only
6520 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6521 */
6522 pUnused = findReusableFd(path, openFlags);
6523 if( pUnused ){
6524 fd = pUnused->fd;
6525 }else{
6526 pUnused = sqlite3_malloc(sizeof(*pUnused));
6527 if( !pUnused ){
6528 return SQLITE_NOMEM;
6529 }
6530 }
6531 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006532 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006533 terrno = errno;
6534 if( fd<0 && errno==ENOENT && islockfile ){
6535 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006536 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006537 }
6538 }
6539 }
6540 if( fd<0 ){
6541 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006542 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006543 terrno = errno;
6544 }
6545 if( fd<0 ){
6546 if( islockfile ){
6547 return SQLITE_BUSY;
6548 }
6549 switch (terrno) {
6550 case EACCES:
6551 return SQLITE_PERM;
6552 case EIO:
6553 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6554 default:
drh9978c972010-02-23 17:36:32 +00006555 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006556 }
6557 }
6558
6559 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6560 if( pNew==NULL ){
6561 rc = SQLITE_NOMEM;
6562 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006563 }
6564 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006565 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006566 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006567 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006568 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006569 pUnused->fd = fd;
6570 pUnused->flags = openFlags;
6571 pNew->pUnused = pUnused;
6572
drhc02a43a2012-01-10 23:18:38 +00006573 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006574 if( rc==SQLITE_OK ){
6575 *ppFile = pNew;
6576 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006577 }
drh7ed97b92010-01-20 13:07:21 +00006578end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006579 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006580 sqlite3_free(pNew);
6581 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006582 return rc;
6583}
6584
drh7ed97b92010-01-20 13:07:21 +00006585#ifdef SQLITE_TEST
6586/* simulate multiple hosts by creating unique hostid file paths */
6587int sqlite3_hostid_num = 0;
6588#endif
6589
6590#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6591
drh0ab216a2010-07-02 17:10:40 +00006592/* Not always defined in the headers as it ought to be */
6593extern int gethostuuid(uuid_t id, const struct timespec *wait);
6594
drh7ed97b92010-01-20 13:07:21 +00006595/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6596** bytes of writable memory.
6597*/
6598static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006599 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6600 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh4bf66fd2015-02-19 02:43:02 +00006601# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
6602 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
drh29ecd8a2010-12-21 00:16:40 +00006603 {
drh4bf66fd2015-02-19 02:43:02 +00006604 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006605 if( gethostuuid(pHostID, &timeout) ){
6606 int err = errno;
6607 if( pError ){
6608 *pError = err;
6609 }
6610 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006611 }
drh7ed97b92010-01-20 13:07:21 +00006612 }
drh3d4435b2011-08-26 20:55:50 +00006613#else
6614 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006615#endif
drh7ed97b92010-01-20 13:07:21 +00006616#ifdef SQLITE_TEST
6617 /* simulate multiple hosts by creating unique hostid file paths */
6618 if( sqlite3_hostid_num != 0){
6619 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6620 }
6621#endif
6622
6623 return SQLITE_OK;
6624}
6625
6626/* The conch file contains the header, host id and lock file path
6627 */
6628#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6629#define PROXY_HEADERLEN 1 /* conch file header length */
6630#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6631#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6632
6633/*
6634** Takes an open conch file, copies the contents to a new path and then moves
6635** it back. The newly created file's file descriptor is assigned to the
6636** conch file structure and finally the original conch file descriptor is
6637** closed. Returns zero if successful.
6638*/
6639static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6640 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6641 unixFile *conchFile = pCtx->conchFile;
6642 char tPath[MAXPATHLEN];
6643 char buf[PROXY_MAXCONCHLEN];
6644 char *cPath = pCtx->conchFilePath;
6645 size_t readLen = 0;
6646 size_t pathLen = 0;
6647 char errmsg[64] = "";
6648 int fd = -1;
6649 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006650 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006651
6652 /* create a new path by replace the trailing '-conch' with '-break' */
6653 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6654 if( pathLen>MAXPATHLEN || pathLen<6 ||
6655 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006656 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006657 goto end_breaklock;
6658 }
6659 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006660 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006661 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006662 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006663 goto end_breaklock;
6664 }
6665 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006666 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006667 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006668 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006669 goto end_breaklock;
6670 }
drhe562be52011-03-02 18:01:10 +00006671 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006672 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006673 goto end_breaklock;
6674 }
6675 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006676 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006677 goto end_breaklock;
6678 }
6679 rc = 0;
6680 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006681 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006682 conchFile->h = fd;
6683 conchFile->openFlags = O_RDWR | O_CREAT;
6684
6685end_breaklock:
6686 if( rc ){
6687 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006688 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006689 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006690 }
6691 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6692 }
6693 return rc;
6694}
6695
6696/* Take the requested lock on the conch file and break a stale lock if the
6697** host id matches.
6698*/
6699static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6700 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6701 unixFile *conchFile = pCtx->conchFile;
6702 int rc = SQLITE_OK;
6703 int nTries = 0;
6704 struct timespec conchModTime;
6705
drh3d4435b2011-08-26 20:55:50 +00006706 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006707 do {
6708 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6709 nTries ++;
6710 if( rc==SQLITE_BUSY ){
6711 /* If the lock failed (busy):
6712 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6713 * 2nd try: fail if the mod time changed or host id is different, wait
6714 * 10 sec and try again
6715 * 3rd try: break the lock unless the mod time has changed.
6716 */
6717 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006718 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006719 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006720 return SQLITE_IOERR_LOCK;
6721 }
6722
6723 if( nTries==1 ){
6724 conchModTime = buf.st_mtimespec;
6725 usleep(500000); /* wait 0.5 sec and try the lock again*/
6726 continue;
6727 }
6728
6729 assert( nTries>1 );
6730 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6731 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6732 return SQLITE_BUSY;
6733 }
6734
6735 if( nTries==2 ){
6736 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006737 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006738 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006739 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006740 return SQLITE_IOERR_LOCK;
6741 }
6742 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6743 /* don't break the lock if the host id doesn't match */
6744 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6745 return SQLITE_BUSY;
6746 }
6747 }else{
6748 /* don't break the lock on short read or a version mismatch */
6749 return SQLITE_BUSY;
6750 }
6751 usleep(10000000); /* wait 10 sec and try the lock again */
6752 continue;
6753 }
6754
6755 assert( nTries==3 );
6756 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6757 rc = SQLITE_OK;
6758 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006759 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006760 }
6761 if( !rc ){
6762 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6763 }
6764 }
6765 }
6766 } while( rc==SQLITE_BUSY && nTries<3 );
6767
6768 return rc;
6769}
6770
6771/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006772** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6773** lockPath means that the lockPath in the conch file will be used if the
6774** host IDs match, or a new lock path will be generated automatically
6775** and written to the conch file.
6776*/
6777static int proxyTakeConch(unixFile *pFile){
6778 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6779
drh7ed97b92010-01-20 13:07:21 +00006780 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006781 return SQLITE_OK;
6782 }else{
6783 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006784 uuid_t myHostID;
6785 int pError = 0;
6786 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006787 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006788 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006789 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006790 int createConch = 0;
6791 int hostIdMatch = 0;
6792 int readLen = 0;
6793 int tryOldLockPath = 0;
6794 int forceNewLockPath = 0;
6795
drh308c2a52010-05-14 11:30:18 +00006796 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6797 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006798
drh7ed97b92010-01-20 13:07:21 +00006799 rc = proxyGetHostID(myHostID, &pError);
6800 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006801 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006802 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006803 }
drh7ed97b92010-01-20 13:07:21 +00006804 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006805 if( rc!=SQLITE_OK ){
6806 goto end_takeconch;
6807 }
drh7ed97b92010-01-20 13:07:21 +00006808 /* read the existing conch file */
6809 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6810 if( readLen<0 ){
6811 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006812 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006813 rc = SQLITE_IOERR_READ;
6814 goto end_takeconch;
6815 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6816 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6817 /* a short read or version format mismatch means we need to create a new
6818 ** conch file.
6819 */
6820 createConch = 1;
6821 }
6822 /* if the host id matches and the lock path already exists in the conch
6823 ** we'll try to use the path there, if we can't open that path, we'll
6824 ** retry with a new auto-generated path
6825 */
6826 do { /* in case we need to try again for an :auto: named lock file */
6827
6828 if( !createConch && !forceNewLockPath ){
6829 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6830 PROXY_HOSTIDLEN);
6831 /* if the conch has data compare the contents */
6832 if( !pCtx->lockProxyPath ){
6833 /* for auto-named local lock file, just check the host ID and we'll
6834 ** use the local lock file path that's already in there
6835 */
6836 if( hostIdMatch ){
6837 size_t pathLen = (readLen - PROXY_PATHINDEX);
6838
6839 if( pathLen>=MAXPATHLEN ){
6840 pathLen=MAXPATHLEN-1;
6841 }
6842 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6843 lockPath[pathLen] = 0;
6844 tempLockPath = lockPath;
6845 tryOldLockPath = 1;
6846 /* create a copy of the lock path if the conch is taken */
6847 goto end_takeconch;
6848 }
6849 }else if( hostIdMatch
6850 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6851 readLen-PROXY_PATHINDEX)
6852 ){
6853 /* conch host and lock path match */
6854 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006855 }
drh7ed97b92010-01-20 13:07:21 +00006856 }
6857
6858 /* if the conch isn't writable and doesn't match, we can't take it */
6859 if( (conchFile->openFlags&O_RDWR) == 0 ){
6860 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006861 goto end_takeconch;
6862 }
drh7ed97b92010-01-20 13:07:21 +00006863
6864 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006865 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006866 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6867 tempLockPath = lockPath;
6868 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006869 }
drh7ed97b92010-01-20 13:07:21 +00006870
6871 /* update conch with host and path (this will fail if other process
6872 ** has a shared lock already), if the host id matches, use the big
6873 ** stick.
drh715ff302008-12-03 22:32:44 +00006874 */
drh7ed97b92010-01-20 13:07:21 +00006875 futimes(conchFile->h, NULL);
6876 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006877 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006878 /* We are trying for an exclusive lock but another thread in this
6879 ** same process is still holding a shared lock. */
6880 rc = SQLITE_BUSY;
6881 } else {
6882 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006883 }
drh715ff302008-12-03 22:32:44 +00006884 }else{
drh4bf66fd2015-02-19 02:43:02 +00006885 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006886 }
drh7ed97b92010-01-20 13:07:21 +00006887 if( rc==SQLITE_OK ){
6888 char writeBuffer[PROXY_MAXCONCHLEN];
6889 int writeSize = 0;
6890
6891 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6892 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6893 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006894 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6895 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006896 }else{
6897 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6898 }
6899 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006900 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006901 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6902 fsync(conchFile->h);
6903 /* If we created a new conch file (not just updated the contents of a
6904 ** valid conch file), try to match the permissions of the database
6905 */
6906 if( rc==SQLITE_OK && createConch ){
6907 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006908 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006909 if( err==0 ){
6910 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6911 S_IROTH|S_IWOTH);
6912 /* try to match the database file R/W permissions, ignore failure */
6913#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006914 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006915#else
drhff812312011-02-23 13:33:46 +00006916 do{
drhe562be52011-03-02 18:01:10 +00006917 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006918 }while( rc==(-1) && errno==EINTR );
6919 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006920 int code = errno;
6921 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6922 cmode, code, strerror(code));
6923 } else {
6924 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6925 }
6926 }else{
6927 int code = errno;
6928 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6929 err, code, strerror(code));
6930#endif
6931 }
drh715ff302008-12-03 22:32:44 +00006932 }
6933 }
drh7ed97b92010-01-20 13:07:21 +00006934 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6935
6936 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006937 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006938 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006939 int fd;
drh7ed97b92010-01-20 13:07:21 +00006940 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006941 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006942 }
6943 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006944 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006945 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006946 if( fd>=0 ){
6947 pFile->h = fd;
6948 }else{
drh9978c972010-02-23 17:36:32 +00006949 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006950 during locking */
6951 }
6952 }
6953 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6954 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6955 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6956 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6957 /* we couldn't create the proxy lock file with the old lock file path
6958 ** so try again via auto-naming
6959 */
6960 forceNewLockPath = 1;
6961 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006962 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006963 }
6964 }
6965 if( rc==SQLITE_OK ){
6966 /* Need to make a copy of path if we extracted the value
6967 ** from the conch file or the path was allocated on the stack
6968 */
6969 if( tempLockPath ){
6970 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6971 if( !pCtx->lockProxyPath ){
6972 rc = SQLITE_NOMEM;
6973 }
6974 }
6975 }
6976 if( rc==SQLITE_OK ){
6977 pCtx->conchHeld = 1;
6978
6979 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6980 afpLockingContext *afpCtx;
6981 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6982 afpCtx->dbPath = pCtx->lockProxyPath;
6983 }
6984 } else {
6985 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6986 }
drh308c2a52010-05-14 11:30:18 +00006987 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6988 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006989 return rc;
drh308c2a52010-05-14 11:30:18 +00006990 } while (1); /* in case we need to retry the :auto: lock file -
6991 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006992 }
6993}
6994
6995/*
6996** If pFile holds a lock on a conch file, then release that lock.
6997*/
6998static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006999 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007000 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7001 unixFile *conchFile; /* Name of the conch file */
7002
7003 pCtx = (proxyLockingContext *)pFile->lockingContext;
7004 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007005 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007006 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00007007 getpid()));
drh7ed97b92010-01-20 13:07:21 +00007008 if( pCtx->conchHeld>0 ){
7009 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7010 }
drh715ff302008-12-03 22:32:44 +00007011 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007012 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7013 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007014 return rc;
7015}
7016
7017/*
7018** Given the name of a database file, compute the name of its conch file.
7019** Store the conch filename in memory obtained from sqlite3_malloc().
7020** Make *pConchPath point to the new name. Return SQLITE_OK on success
7021** or SQLITE_NOMEM if unable to obtain memory.
7022**
7023** The caller is responsible for ensuring that the allocated memory
7024** space is eventually freed.
7025**
7026** *pConchPath is set to NULL if a memory allocation error occurs.
7027*/
7028static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7029 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007030 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007031 char *conchPath; /* buffer in which to construct conch name */
7032
7033 /* Allocate space for the conch filename and initialize the name to
7034 ** the name of the original database file. */
7035 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
7036 if( conchPath==0 ){
7037 return SQLITE_NOMEM;
7038 }
7039 memcpy(conchPath, dbPath, len+1);
7040
7041 /* now insert a "." before the last / character */
7042 for( i=(len-1); i>=0; i-- ){
7043 if( conchPath[i]=='/' ){
7044 i++;
7045 break;
7046 }
7047 }
7048 conchPath[i]='.';
7049 while ( i<len ){
7050 conchPath[i+1]=dbPath[i];
7051 i++;
7052 }
7053
7054 /* append the "-conch" suffix to the file */
7055 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007056 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007057
7058 return SQLITE_OK;
7059}
7060
7061
7062/* Takes a fully configured proxy locking-style unix file and switches
7063** the local lock file path
7064*/
7065static int switchLockProxyPath(unixFile *pFile, const char *path) {
7066 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7067 char *oldPath = pCtx->lockProxyPath;
7068 int rc = SQLITE_OK;
7069
drh308c2a52010-05-14 11:30:18 +00007070 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007071 return SQLITE_BUSY;
7072 }
7073
7074 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7075 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7076 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7077 return SQLITE_OK;
7078 }else{
7079 unixFile *lockProxy = pCtx->lockProxy;
7080 pCtx->lockProxy=NULL;
7081 pCtx->conchHeld = 0;
7082 if( lockProxy!=NULL ){
7083 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7084 if( rc ) return rc;
7085 sqlite3_free(lockProxy);
7086 }
7087 sqlite3_free(oldPath);
7088 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7089 }
7090
7091 return rc;
7092}
7093
7094/*
7095** pFile is a file that has been opened by a prior xOpen call. dbPath
7096** is a string buffer at least MAXPATHLEN+1 characters in size.
7097**
7098** This routine find the filename associated with pFile and writes it
7099** int dbPath.
7100*/
7101static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007102#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007103 if( pFile->pMethod == &afpIoMethods ){
7104 /* afp style keeps a reference to the db path in the filePath field
7105 ** of the struct */
drhea678832008-12-10 19:26:22 +00007106 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007107 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7108 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007109 } else
drh715ff302008-12-03 22:32:44 +00007110#endif
7111 if( pFile->pMethod == &dotlockIoMethods ){
7112 /* dot lock style uses the locking context to store the dot lock
7113 ** file path */
7114 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7115 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7116 }else{
7117 /* all other styles use the locking context to store the db file path */
7118 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007119 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007120 }
7121 return SQLITE_OK;
7122}
7123
7124/*
7125** Takes an already filled in unix file and alters it so all file locking
7126** will be performed on the local proxy lock file. The following fields
7127** are preserved in the locking context so that they can be restored and
7128** the unix structure properly cleaned up at close time:
7129** ->lockingContext
7130** ->pMethod
7131*/
7132static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7133 proxyLockingContext *pCtx;
7134 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7135 char *lockPath=NULL;
7136 int rc = SQLITE_OK;
7137
drh308c2a52010-05-14 11:30:18 +00007138 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007139 return SQLITE_BUSY;
7140 }
7141 proxyGetDbPathForUnixFile(pFile, dbPath);
7142 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7143 lockPath=NULL;
7144 }else{
7145 lockPath=(char *)path;
7146 }
7147
drh308c2a52010-05-14 11:30:18 +00007148 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7149 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007150
7151 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7152 if( pCtx==0 ){
7153 return SQLITE_NOMEM;
7154 }
7155 memset(pCtx, 0, sizeof(*pCtx));
7156
7157 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7158 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007159 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7160 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7161 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7162 ** (c) the file system is read-only, then enable no-locking access.
7163 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7164 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7165 */
7166 struct statfs fsInfo;
7167 struct stat conchInfo;
7168 int goLockless = 0;
7169
drh99ab3b12011-03-02 15:09:07 +00007170 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007171 int err = errno;
7172 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7173 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7174 }
7175 }
7176 if( goLockless ){
7177 pCtx->conchHeld = -1; /* read only FS/ lockless */
7178 rc = SQLITE_OK;
7179 }
7180 }
drh715ff302008-12-03 22:32:44 +00007181 }
7182 if( rc==SQLITE_OK && lockPath ){
7183 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7184 }
7185
7186 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007187 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7188 if( pCtx->dbPath==NULL ){
7189 rc = SQLITE_NOMEM;
7190 }
7191 }
7192 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007193 /* all memory is allocated, proxys are created and assigned,
7194 ** switch the locking context and pMethod then return.
7195 */
drh715ff302008-12-03 22:32:44 +00007196 pCtx->oldLockingContext = pFile->lockingContext;
7197 pFile->lockingContext = pCtx;
7198 pCtx->pOldMethod = pFile->pMethod;
7199 pFile->pMethod = &proxyIoMethods;
7200 }else{
7201 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007202 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007203 sqlite3_free(pCtx->conchFile);
7204 }
drhd56b1212010-08-11 06:14:15 +00007205 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007206 sqlite3_free(pCtx->conchFilePath);
7207 sqlite3_free(pCtx);
7208 }
drh308c2a52010-05-14 11:30:18 +00007209 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7210 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007211 return rc;
7212}
7213
7214
7215/*
7216** This routine handles sqlite3_file_control() calls that are specific
7217** to proxy locking.
7218*/
7219static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7220 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007221 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007222 unixFile *pFile = (unixFile*)id;
7223 if( pFile->pMethod == &proxyIoMethods ){
7224 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7225 proxyTakeConch(pFile);
7226 if( pCtx->lockProxyPath ){
7227 *(const char **)pArg = pCtx->lockProxyPath;
7228 }else{
7229 *(const char **)pArg = ":auto: (not held)";
7230 }
7231 } else {
7232 *(const char **)pArg = NULL;
7233 }
7234 return SQLITE_OK;
7235 }
drh4bf66fd2015-02-19 02:43:02 +00007236 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007237 unixFile *pFile = (unixFile*)id;
7238 int rc = SQLITE_OK;
7239 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7240 if( pArg==NULL || (const char *)pArg==0 ){
7241 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007242 /* turn off proxy locking - not supported. If support is added for
7243 ** switching proxy locking mode off then it will need to fail if
7244 ** the journal mode is WAL mode.
7245 */
drh715ff302008-12-03 22:32:44 +00007246 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7247 }else{
7248 /* turn off proxy locking - already off - NOOP */
7249 rc = SQLITE_OK;
7250 }
7251 }else{
7252 const char *proxyPath = (const char *)pArg;
7253 if( isProxyStyle ){
7254 proxyLockingContext *pCtx =
7255 (proxyLockingContext*)pFile->lockingContext;
7256 if( !strcmp(pArg, ":auto:")
7257 || (pCtx->lockProxyPath &&
7258 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7259 ){
7260 rc = SQLITE_OK;
7261 }else{
7262 rc = switchLockProxyPath(pFile, proxyPath);
7263 }
7264 }else{
7265 /* turn on proxy file locking */
7266 rc = proxyTransformUnixFile(pFile, proxyPath);
7267 }
7268 }
7269 return rc;
7270 }
7271 default: {
7272 assert( 0 ); /* The call assures that only valid opcodes are sent */
7273 }
7274 }
7275 /*NOTREACHED*/
7276 return SQLITE_ERROR;
7277}
7278
7279/*
7280** Within this division (the proxying locking implementation) the procedures
7281** above this point are all utilities. The lock-related methods of the
7282** proxy-locking sqlite3_io_method object follow.
7283*/
7284
7285
7286/*
7287** This routine checks if there is a RESERVED lock held on the specified
7288** file by this or any other process. If such a lock is held, set *pResOut
7289** to a non-zero value otherwise *pResOut is set to zero. The return value
7290** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7291*/
7292static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7293 unixFile *pFile = (unixFile*)id;
7294 int rc = proxyTakeConch(pFile);
7295 if( rc==SQLITE_OK ){
7296 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007297 if( pCtx->conchHeld>0 ){
7298 unixFile *proxy = pCtx->lockProxy;
7299 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7300 }else{ /* conchHeld < 0 is lockless */
7301 pResOut=0;
7302 }
drh715ff302008-12-03 22:32:44 +00007303 }
7304 return rc;
7305}
7306
7307/*
drh308c2a52010-05-14 11:30:18 +00007308** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007309** of the following:
7310**
7311** (1) SHARED_LOCK
7312** (2) RESERVED_LOCK
7313** (3) PENDING_LOCK
7314** (4) EXCLUSIVE_LOCK
7315**
7316** Sometimes when requesting one lock state, additional lock states
7317** are inserted in between. The locking might fail on one of the later
7318** transitions leaving the lock state different from what it started but
7319** still short of its goal. The following chart shows the allowed
7320** transitions and the inserted intermediate states:
7321**
7322** UNLOCKED -> SHARED
7323** SHARED -> RESERVED
7324** SHARED -> (PENDING) -> EXCLUSIVE
7325** RESERVED -> (PENDING) -> EXCLUSIVE
7326** PENDING -> EXCLUSIVE
7327**
7328** This routine will only increase a lock. Use the sqlite3OsUnlock()
7329** routine to lower a locking level.
7330*/
drh308c2a52010-05-14 11:30:18 +00007331static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007332 unixFile *pFile = (unixFile*)id;
7333 int rc = proxyTakeConch(pFile);
7334 if( rc==SQLITE_OK ){
7335 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007336 if( pCtx->conchHeld>0 ){
7337 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007338 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7339 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007340 }else{
7341 /* conchHeld < 0 is lockless */
7342 }
drh715ff302008-12-03 22:32:44 +00007343 }
7344 return rc;
7345}
7346
7347
7348/*
drh308c2a52010-05-14 11:30:18 +00007349** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007350** must be either NO_LOCK or SHARED_LOCK.
7351**
7352** If the locking level of the file descriptor is already at or below
7353** the requested locking level, this routine is a no-op.
7354*/
drh308c2a52010-05-14 11:30:18 +00007355static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007356 unixFile *pFile = (unixFile*)id;
7357 int rc = proxyTakeConch(pFile);
7358 if( rc==SQLITE_OK ){
7359 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007360 if( pCtx->conchHeld>0 ){
7361 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007362 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7363 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007364 }else{
7365 /* conchHeld < 0 is lockless */
7366 }
drh715ff302008-12-03 22:32:44 +00007367 }
7368 return rc;
7369}
7370
7371/*
7372** Close a file that uses proxy locks.
7373*/
7374static int proxyClose(sqlite3_file *id) {
7375 if( id ){
7376 unixFile *pFile = (unixFile*)id;
7377 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7378 unixFile *lockProxy = pCtx->lockProxy;
7379 unixFile *conchFile = pCtx->conchFile;
7380 int rc = SQLITE_OK;
7381
7382 if( lockProxy ){
7383 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7384 if( rc ) return rc;
7385 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7386 if( rc ) return rc;
7387 sqlite3_free(lockProxy);
7388 pCtx->lockProxy = 0;
7389 }
7390 if( conchFile ){
7391 if( pCtx->conchHeld ){
7392 rc = proxyReleaseConch(pFile);
7393 if( rc ) return rc;
7394 }
7395 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7396 if( rc ) return rc;
7397 sqlite3_free(conchFile);
7398 }
drhd56b1212010-08-11 06:14:15 +00007399 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007400 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007401 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007402 /* restore the original locking context and pMethod then close it */
7403 pFile->lockingContext = pCtx->oldLockingContext;
7404 pFile->pMethod = pCtx->pOldMethod;
7405 sqlite3_free(pCtx);
7406 return pFile->pMethod->xClose(id);
7407 }
7408 return SQLITE_OK;
7409}
7410
7411
7412
drhd2cb50b2009-01-09 21:41:17 +00007413#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007414/*
7415** The proxy locking style is intended for use with AFP filesystems.
7416** And since AFP is only supported on MacOSX, the proxy locking is also
7417** restricted to MacOSX.
7418**
7419**
7420******************* End of the proxy lock implementation **********************
7421******************************************************************************/
7422
drh734c9862008-11-28 15:37:20 +00007423/*
danielk1977e339d652008-06-28 11:23:00 +00007424** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007425**
7426** This routine registers all VFS implementations for unix-like operating
7427** systems. This routine, and the sqlite3_os_end() routine that follows,
7428** should be the only routines in this file that are visible from other
7429** files.
drh6b9d6dd2008-12-03 19:34:47 +00007430**
7431** This routine is called once during SQLite initialization and by a
7432** single thread. The memory allocation and mutex subsystems have not
7433** necessarily been initialized when this routine is called, and so they
7434** should not be used.
drh153c62c2007-08-24 03:51:33 +00007435*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007436int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007437 /*
7438 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007439 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7440 ** to the "finder" function. (pAppData is a pointer to a pointer because
7441 ** silly C90 rules prohibit a void* from being cast to a function pointer
7442 ** and so we have to go through the intermediate pointer to avoid problems
7443 ** when compiling with -pedantic-errors on GCC.)
7444 **
7445 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007446 ** finder-function. The finder-function returns a pointer to the
7447 ** sqlite_io_methods object that implements the desired locking
7448 ** behaviors. See the division above that contains the IOMETHODS
7449 ** macro for addition information on finder-functions.
7450 **
7451 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7452 ** object. But the "autolockIoFinder" available on MacOSX does a little
7453 ** more than that; it looks at the filesystem type that hosts the
7454 ** database file and tries to choose an locking method appropriate for
7455 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007456 */
drh7708e972008-11-29 00:56:52 +00007457 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007458 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007459 sizeof(unixFile), /* szOsFile */ \
7460 MAX_PATHNAME, /* mxPathname */ \
7461 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007462 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007463 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007464 unixOpen, /* xOpen */ \
7465 unixDelete, /* xDelete */ \
7466 unixAccess, /* xAccess */ \
7467 unixFullPathname, /* xFullPathname */ \
7468 unixDlOpen, /* xDlOpen */ \
7469 unixDlError, /* xDlError */ \
7470 unixDlSym, /* xDlSym */ \
7471 unixDlClose, /* xDlClose */ \
7472 unixRandomness, /* xRandomness */ \
7473 unixSleep, /* xSleep */ \
7474 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007475 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007476 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007477 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007478 unixGetSystemCall, /* xGetSystemCall */ \
7479 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007480 }
7481
drh6b9d6dd2008-12-03 19:34:47 +00007482 /*
7483 ** All default VFSes for unix are contained in the following array.
7484 **
7485 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7486 ** by the SQLite core when the VFS is registered. So the following
7487 ** array cannot be const.
7488 */
danielk1977e339d652008-06-28 11:23:00 +00007489 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007490#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007491 UNIXVFS("unix", autolockIoFinder ),
7492#else
7493 UNIXVFS("unix", posixIoFinder ),
7494#endif
7495 UNIXVFS("unix-none", nolockIoFinder ),
7496 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007497 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007498#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007499 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007500#endif
7501#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007502 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007503#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007504 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007505#endif
chw78a13182009-04-07 05:35:03 +00007506#endif
drhd2cb50b2009-01-09 21:41:17 +00007507#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007508 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007509 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007510 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007511#endif
drh153c62c2007-08-24 03:51:33 +00007512 };
drh6b9d6dd2008-12-03 19:34:47 +00007513 unsigned int i; /* Loop counter */
7514
drh2aa5a002011-04-13 13:42:25 +00007515 /* Double-check that the aSyscall[] array has been constructed
7516 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007517 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007518
drh6b9d6dd2008-12-03 19:34:47 +00007519 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007520 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007521 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007522 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007523 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007524}
danielk1977e339d652008-06-28 11:23:00 +00007525
7526/*
drh6b9d6dd2008-12-03 19:34:47 +00007527** Shutdown the operating system interface.
7528**
7529** Some operating systems might need to do some cleanup in this routine,
7530** to release dynamically allocated objects. But not on unix.
7531** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007532*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007533int sqlite3_os_end(void){
7534 return SQLITE_OK;
7535}
drhdce8bdb2007-08-16 13:01:44 +00007536
danielk197729bafea2008-06-26 10:41:19 +00007537#endif /* SQLITE_OS_UNIX */