blob: 5f583402ab9aa0a42ee32ee4621358b8529f5409 [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/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** standard include files.
88*/
89#include <sys/types.h>
90#include <sys/stat.h>
91#include <fcntl.h>
92#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000093#include <time.h>
drh19e2d372005-08-29 23:00:03 +000094#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000095#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000096#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000097# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +000098#endif
drh1da88f02011-12-17 16:09:16 +000099
drh91be7dc2014-08-11 13:53:30 +0000100#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000101# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000102# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000103# include <semaphore.h>
104# include <limits.h>
105# else
drh9b35ea62008-11-29 02:20:26 +0000106# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000107# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000108# endif
drhbfe66312006-10-03 17:40:40 +0000109#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000110
drhf8b4d8c2010-03-05 13:53:22 +0000111#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000112# include <sys/mount.h>
113#endif
114
drhdbe4b882011-06-20 18:00:17 +0000115#ifdef HAVE_UTIME
116# include <utime.h>
117#endif
118
drh9cbe6352005-11-29 03:13:21 +0000119/*
drh7ed97b92010-01-20 13:07:21 +0000120** Allowed values of unixFile.fsFlags
121*/
122#define SQLITE_FSFLAGS_IS_MSDOS 0x1
123
124/*
drhf1a221e2006-01-15 17:27:17 +0000125** If we are to be thread-safe, include the pthreads header and define
126** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000127*/
drhd677b3d2007-08-20 22:48:41 +0000128#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000129# include <pthread.h>
130# define SQLITE_UNIX_THREADS 1
131#endif
132
133/*
134** Default permissions when creating a new file
135*/
136#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
137# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
138#endif
139
danielk1977b4b47412007-08-17 15:53:36 +0000140/*
drh5adc60b2012-04-14 13:25:11 +0000141** Default permissions when creating auto proxy dir
142*/
aswiftaebf4132008-11-21 00:10:35 +0000143#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
144# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
145#endif
146
147/*
danielk1977b4b47412007-08-17 15:53:36 +0000148** Maximum supported path-length.
149*/
150#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000151
drh734c9862008-11-28 15:37:20 +0000152/*
drh734c9862008-11-28 15:37:20 +0000153** Only set the lastErrno if the error code is a real error and not
154** a normal expected return code of SQLITE_BUSY or SQLITE_OK
155*/
156#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
157
drhd91c68f2010-05-14 14:52:25 +0000158/* Forward references */
159typedef struct unixShm unixShm; /* Connection shared memory */
160typedef struct unixShmNode unixShmNode; /* Shared memory instance */
161typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
162typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000163
164/*
dane946c392009-08-22 11:39:46 +0000165** Sometimes, after a file handle is closed by SQLite, the file descriptor
166** cannot be closed immediately. In these cases, instances of the following
167** structure are used to store the file descriptor while waiting for an
168** opportunity to either close or reuse it.
169*/
dane946c392009-08-22 11:39:46 +0000170struct UnixUnusedFd {
171 int fd; /* File descriptor to close */
172 int flags; /* Flags this file descriptor was opened with */
173 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
174};
175
176/*
drh9b35ea62008-11-29 02:20:26 +0000177** The unixFile structure is subclass of sqlite3_file specific to the unix
178** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000179*/
drh054889e2005-11-30 03:20:31 +0000180typedef struct unixFile unixFile;
181struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000182 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000183 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000184 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000185 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000186 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000187 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000188 int lastErrno; /* The unix errno from last I/O error */
189 void *lockingContext; /* Locking style specific state */
190 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000191 const char *zPath; /* Name of the file */
192 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000193 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000194#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000195 int nFetchOut; /* Number of outstanding xFetch refs */
196 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000197 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
198 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000199 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000200#endif
drh537dddf2012-10-26 13:46:24 +0000201#ifdef __QNXNTO__
202 int sectorSize; /* Device sector size */
203 int deviceCharacteristics; /* Precomputed device characteristics */
204#endif
drh08c6d442009-02-09 17:34:07 +0000205#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000206 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000207#endif
drh7ed97b92010-01-20 13:07:21 +0000208#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000209 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000210#endif
211#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000212 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000213#endif
drhd3d8c042012-05-29 17:02:40 +0000214#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000215 /* The next group of variables are used to track whether or not the
216 ** transaction counter in bytes 24-27 of database files are updated
217 ** whenever any part of the database changes. An assertion fault will
218 ** occur if a file is updated without also updating the transaction
219 ** counter. This test is made to avoid new problems similar to the
220 ** one described by ticket #3584.
221 */
222 unsigned char transCntrChng; /* True if the transaction counter changed */
223 unsigned char dbUpdate; /* True if any part of database file changed */
224 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000225
drh8f941bc2009-01-14 23:03:40 +0000226#endif
danf23da962013-03-23 21:00:41 +0000227
danielk1977967a4a12007-08-20 14:23:44 +0000228#ifdef SQLITE_TEST
229 /* In test mode, increase the size of this structure a bit so that
230 ** it is larger than the struct CrashFile defined in test6.c.
231 */
232 char aPadding[32];
233#endif
drh9cbe6352005-11-29 03:13:21 +0000234};
235
drhb00d8622014-01-01 15:18:36 +0000236/* This variable holds the process id (pid) from when the xRandomness()
237** method was called. If xOpen() is called from a different process id,
238** indicating that a fork() has occurred, the PRNG will be reset.
239*/
240static int randomnessPid = 0;
241
drh0ccebe72005-06-07 22:22:50 +0000242/*
drha7e61d82011-03-12 17:02:57 +0000243** Allowed values for the unixFile.ctrlFlags bitmask:
244*/
drhf0b190d2011-07-26 16:03:07 +0000245#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
246#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
247#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000248#ifndef SQLITE_DISABLE_DIRSYNC
249# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
250#else
251# define UNIXFILE_DIRSYNC 0x00
252#endif
drhcb15f352011-12-23 01:04:17 +0000253#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000254#define UNIXFILE_DELETE 0x20 /* Delete on close */
255#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
256#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhe6d41732015-02-21 00:49:00 +0000257#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
drha7e61d82011-03-12 17:02:57 +0000258
259/*
drh198bf392006-01-06 21:52:49 +0000260** Include code that is common to all os_*.c files
261*/
262#include "os_common.h"
263
264/*
drh0ccebe72005-06-07 22:22:50 +0000265** Define various macros that are missing from some systems.
266*/
drhbbd42a62004-05-22 17:41:58 +0000267#ifndef O_LARGEFILE
268# define O_LARGEFILE 0
269#endif
270#ifdef SQLITE_DISABLE_LFS
271# undef O_LARGEFILE
272# define O_LARGEFILE 0
273#endif
274#ifndef O_NOFOLLOW
275# define O_NOFOLLOW 0
276#endif
277#ifndef O_BINARY
278# define O_BINARY 0
279#endif
280
281/*
drh2b4b5962005-06-15 17:47:55 +0000282** The threadid macro resolves to the thread-id or to 0. Used for
283** testing and debugging only.
284*/
drhd677b3d2007-08-20 22:48:41 +0000285#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000286#define threadid pthread_self()
287#else
288#define threadid 0
289#endif
290
drh99ab3b12011-03-02 15:09:07 +0000291/*
dane6ecd662013-04-01 17:56:59 +0000292** HAVE_MREMAP defaults to true on Linux and false everywhere else.
293*/
294#if !defined(HAVE_MREMAP)
295# if defined(__linux__) && defined(_GNU_SOURCE)
296# define HAVE_MREMAP 1
297# else
298# define HAVE_MREMAP 0
299# endif
300#endif
301
302/*
dan2ee53412014-09-06 16:49:40 +0000303** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
304** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
305*/
306#ifdef __ANDROID__
307# define lseek lseek64
308#endif
309
310/*
drh9a3baf12011-04-25 18:01:27 +0000311** Different Unix systems declare open() in different ways. Same use
312** open(const char*,int,mode_t). Others use open(const char*,int,...).
313** The difference is important when using a pointer to the function.
314**
315** The safest way to deal with the problem is to always use this wrapper
316** which always has the same well-defined interface.
317*/
318static int posixOpen(const char *zFile, int flags, int mode){
319 return open(zFile, flags, mode);
320}
321
drhed466822012-05-31 13:10:49 +0000322/*
323** On some systems, calls to fchown() will trigger a message in a security
324** log if they come from non-root processes. So avoid calling fchown() if
325** we are not running as root.
326*/
327static int posixFchown(int fd, uid_t uid, gid_t gid){
drh91be7dc2014-08-11 13:53:30 +0000328#if OS_VXWORKS
329 return 0;
330#else
drhed466822012-05-31 13:10:49 +0000331 return geteuid() ? 0 : fchown(fd,uid,gid);
drh91be7dc2014-08-11 13:53:30 +0000332#endif
drhed466822012-05-31 13:10:49 +0000333}
334
drh90315a22011-08-10 01:52:12 +0000335/* Forward reference */
336static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000337static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000338
drh9a3baf12011-04-25 18:01:27 +0000339/*
drh99ab3b12011-03-02 15:09:07 +0000340** Many system calls are accessed through pointer-to-functions so that
341** they may be overridden at runtime to facilitate fault injection during
342** testing and sandboxing. The following array holds the names and pointers
343** to all overrideable system calls.
344*/
345static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000346 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000347 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
348 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000349} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000350 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
351#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000352
drh58ad5802011-03-23 22:02:23 +0000353 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000354#define osClose ((int(*)(int))aSyscall[1].pCurrent)
355
drh58ad5802011-03-23 22:02:23 +0000356 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000357#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
358
drh58ad5802011-03-23 22:02:23 +0000359 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000360#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
361
drh58ad5802011-03-23 22:02:23 +0000362 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000363#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
364
365/*
366** The DJGPP compiler environment looks mostly like Unix, but it
367** lacks the fcntl() system call. So redefine fcntl() to be something
368** that always succeeds. This means that locking does not occur under
369** DJGPP. But it is DOS - what did you expect?
370*/
371#ifdef __DJGPP__
372 { "fstat", 0, 0 },
373#define osFstat(a,b,c) 0
374#else
drh58ad5802011-03-23 22:02:23 +0000375 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000376#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
377#endif
378
drh58ad5802011-03-23 22:02:23 +0000379 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000380#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
381
drh58ad5802011-03-23 22:02:23 +0000382 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000383#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000384
drh58ad5802011-03-23 22:02:23 +0000385 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000386#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
387
drh91be7dc2014-08-11 13:53:30 +0000388#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh58ad5802011-03-23 22:02:23 +0000389 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000390#else
drh58ad5802011-03-23 22:02:23 +0000391 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000392#endif
393#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
394
395#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000396 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000397#else
drh58ad5802011-03-23 22:02:23 +0000398 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000399#endif
400#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
401
drh58ad5802011-03-23 22:02:23 +0000402 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000403#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
404
drh91be7dc2014-08-11 13:53:30 +0000405#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh58ad5802011-03-23 22:02:23 +0000406 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000407#else
drh58ad5802011-03-23 22:02:23 +0000408 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000409#endif
410#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
411 aSyscall[12].pCurrent)
412
413#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000414 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000415#else
drh58ad5802011-03-23 22:02:23 +0000416 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000417#endif
418#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
419 aSyscall[13].pCurrent)
420
drh58ad5802011-03-23 22:02:23 +0000421 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000422#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000423
424#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000425 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000426#else
drh58ad5802011-03-23 22:02:23 +0000427 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000428#endif
dan0fd7d862011-03-29 10:04:23 +0000429#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000430
drh036ac7f2011-08-08 23:18:05 +0000431 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
432#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
433
drh90315a22011-08-10 01:52:12 +0000434 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
435#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
436
drh9ef6bc42011-11-04 02:24:02 +0000437 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
438#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
439
440 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
441#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
442
drhed466822012-05-31 13:10:49 +0000443 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000444#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000445
dan4dd51442013-08-26 14:30:25 +0000446#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000447 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
448#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
449
drhd1ab8062013-03-25 20:50:25 +0000450 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
451#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
452
dane6ecd662013-04-01 17:56:59 +0000453#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000454 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
455#else
456 { "mremap", (sqlite3_syscall_ptr)0, 0 },
457#endif
458#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
danbc760632014-03-20 09:42:09 +0000459 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
460#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
461
dan702eec12014-06-23 10:04:58 +0000462#endif
463
drhe562be52011-03-02 18:01:10 +0000464}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000465
466/*
467** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000468** "unix" VFSes. Return SQLITE_OK opon successfully updating the
469** system call pointer, or SQLITE_NOTFOUND if there is no configurable
470** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000471*/
472static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000473 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
474 const char *zName, /* Name of system call to override */
475 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000476){
drh58ad5802011-03-23 22:02:23 +0000477 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000478 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000479
480 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000481 if( zName==0 ){
482 /* If no zName is given, restore all system calls to their default
483 ** settings and return NULL
484 */
dan51438a72011-04-02 17:00:47 +0000485 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000486 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
487 if( aSyscall[i].pDefault ){
488 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000489 }
490 }
491 }else{
492 /* If zName is specified, operate on only the one system call
493 ** specified.
494 */
495 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
496 if( strcmp(zName, aSyscall[i].zName)==0 ){
497 if( aSyscall[i].pDefault==0 ){
498 aSyscall[i].pDefault = aSyscall[i].pCurrent;
499 }
drh1df30962011-03-02 19:06:42 +0000500 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000501 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
502 aSyscall[i].pCurrent = pNewFunc;
503 break;
504 }
505 }
506 }
507 return rc;
508}
509
drh1df30962011-03-02 19:06:42 +0000510/*
511** Return the value of a system call. Return NULL if zName is not a
512** recognized system call name. NULL is also returned if the system call
513** is currently undefined.
514*/
drh58ad5802011-03-23 22:02:23 +0000515static sqlite3_syscall_ptr unixGetSystemCall(
516 sqlite3_vfs *pNotUsed,
517 const char *zName
518){
519 unsigned int i;
520
521 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000522 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
523 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
524 }
525 return 0;
526}
527
528/*
529** Return the name of the first system call after zName. If zName==NULL
530** then return the name of the first system call. Return NULL if zName
531** is the last system call or if zName is not the name of a valid
532** system call.
533*/
534static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000535 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000536
537 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000538 if( zName ){
539 for(i=0; i<ArraySize(aSyscall)-1; i++){
540 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000541 }
542 }
dan0fd7d862011-03-29 10:04:23 +0000543 for(i++; i<ArraySize(aSyscall); i++){
544 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000545 }
546 return 0;
547}
548
drhad4f1e52011-03-04 15:43:57 +0000549/*
drh77a3fdc2013-08-30 14:24:12 +0000550** Do not accept any file descriptor less than this value, in order to avoid
551** opening database file using file descriptors that are commonly used for
552** standard input, output, and error.
553*/
554#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
555# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
556#endif
557
558/*
drh8c815d12012-02-13 20:16:37 +0000559** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000560** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000561**
562** If the file creation mode "m" is 0 then set it to the default for
563** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
564** 0644) as modified by the system umask. If m is not 0, then
565** make the file creation mode be exactly m ignoring the umask.
566**
567** The m parameter will be non-zero only when creating -wal, -journal,
568** and -shm files. We want those files to have *exactly* the same
569** permissions as their original database, unadulterated by the umask.
570** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
571** transaction crashes and leaves behind hot journals, then any
572** process that is able to write to the database will also be able to
573** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000574*/
drh8c815d12012-02-13 20:16:37 +0000575static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000576 int fd;
drhe1186ab2013-01-04 20:45:13 +0000577 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000578 while(1){
drh5adc60b2012-04-14 13:25:11 +0000579#if defined(O_CLOEXEC)
580 fd = osOpen(z,f|O_CLOEXEC,m2);
581#else
582 fd = osOpen(z,f,m2);
583#endif
drh5128d002013-08-30 06:20:23 +0000584 if( fd<0 ){
585 if( errno==EINTR ) continue;
586 break;
587 }
drh77a3fdc2013-08-30 14:24:12 +0000588 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000589 osClose(fd);
590 sqlite3_log(SQLITE_WARNING,
591 "attempt to open \"%s\" as file descriptor %d", z, fd);
592 fd = -1;
593 if( osOpen("/dev/null", f, m)<0 ) break;
594 }
drhe1186ab2013-01-04 20:45:13 +0000595 if( fd>=0 ){
596 if( m!=0 ){
597 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000598 if( osFstat(fd, &statbuf)==0
599 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000600 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000601 ){
drhe1186ab2013-01-04 20:45:13 +0000602 osFchmod(fd, m);
603 }
604 }
drh5adc60b2012-04-14 13:25:11 +0000605#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000606 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000607#endif
drhe1186ab2013-01-04 20:45:13 +0000608 }
drh5adc60b2012-04-14 13:25:11 +0000609 return fd;
drhad4f1e52011-03-04 15:43:57 +0000610}
danielk197713adf8a2004-06-03 16:08:41 +0000611
drh107886a2008-11-21 22:21:50 +0000612/*
dan9359c7b2009-08-21 08:29:10 +0000613** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000614** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000615** vxworksFileId objects used by this file, all of which may be
616** shared by multiple threads.
617**
618** Function unixMutexHeld() is used to assert() that the global mutex
619** is held when required. This function is only used as part of assert()
620** statements. e.g.
621**
622** unixEnterMutex()
623** assert( unixMutexHeld() );
624** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000625*/
626static void unixEnterMutex(void){
627 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
628}
629static void unixLeaveMutex(void){
630 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
631}
dan9359c7b2009-08-21 08:29:10 +0000632#ifdef SQLITE_DEBUG
633static int unixMutexHeld(void) {
634 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
635}
636#endif
drh107886a2008-11-21 22:21:50 +0000637
drh734c9862008-11-28 15:37:20 +0000638
drh30ddce62011-10-15 00:16:30 +0000639#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000640/*
641** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000642** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000643** integer lock-type.
644*/
drh308c2a52010-05-14 11:30:18 +0000645static const char *azFileLock(int eFileLock){
646 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000647 case NO_LOCK: return "NONE";
648 case SHARED_LOCK: return "SHARED";
649 case RESERVED_LOCK: return "RESERVED";
650 case PENDING_LOCK: return "PENDING";
651 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000652 }
653 return "ERROR";
654}
655#endif
656
657#ifdef SQLITE_LOCK_TRACE
658/*
659** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000660**
drh734c9862008-11-28 15:37:20 +0000661** This routine is used for troubleshooting locks on multithreaded
662** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
663** command-line option on the compiler. This code is normally
664** turned off.
665*/
666static int lockTrace(int fd, int op, struct flock *p){
667 char *zOpName, *zType;
668 int s;
669 int savedErrno;
670 if( op==F_GETLK ){
671 zOpName = "GETLK";
672 }else if( op==F_SETLK ){
673 zOpName = "SETLK";
674 }else{
drh99ab3b12011-03-02 15:09:07 +0000675 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000676 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
677 return s;
678 }
679 if( p->l_type==F_RDLCK ){
680 zType = "RDLCK";
681 }else if( p->l_type==F_WRLCK ){
682 zType = "WRLCK";
683 }else if( p->l_type==F_UNLCK ){
684 zType = "UNLCK";
685 }else{
686 assert( 0 );
687 }
688 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000689 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000690 savedErrno = errno;
691 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
692 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
693 (int)p->l_pid, s);
694 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
695 struct flock l2;
696 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000697 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000698 if( l2.l_type==F_RDLCK ){
699 zType = "RDLCK";
700 }else if( l2.l_type==F_WRLCK ){
701 zType = "WRLCK";
702 }else if( l2.l_type==F_UNLCK ){
703 zType = "UNLCK";
704 }else{
705 assert( 0 );
706 }
707 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
708 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
709 }
710 errno = savedErrno;
711 return s;
712}
drh99ab3b12011-03-02 15:09:07 +0000713#undef osFcntl
714#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000715#endif /* SQLITE_LOCK_TRACE */
716
drhff812312011-02-23 13:33:46 +0000717/*
718** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000719**
drhe6d41732015-02-21 00:49:00 +0000720** All calls to ftruncate() within this file should be made through
721** this wrapper. On the Android platform, bypassing the logic below
722** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000723*/
drhff812312011-02-23 13:33:46 +0000724static int robust_ftruncate(int h, sqlite3_int64 sz){
725 int rc;
dan2ee53412014-09-06 16:49:40 +0000726#ifdef __ANDROID__
727 /* On Android, ftruncate() always uses 32-bit offsets, even if
728 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000729 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000730 ** such attempts. */
731 if( sz>(sqlite3_int64)0x7FFFFFFF ){
732 rc = SQLITE_OK;
733 }else
734#endif
drh99ab3b12011-03-02 15:09:07 +0000735 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000736 return rc;
737}
drh734c9862008-11-28 15:37:20 +0000738
739/*
740** This routine translates a standard POSIX errno code into something
741** useful to the clients of the sqlite3 functions. Specifically, it is
742** intended to translate a variety of "try again" errors into SQLITE_BUSY
743** and a variety of "please close the file descriptor NOW" errors into
744** SQLITE_IOERR
745**
746** Errors during initialization of locks, or file system support for locks,
747** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
748*/
749static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
750 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000751#if 0
752 /* At one point this code was not commented out. In theory, this branch
753 ** should never be hit, as this function should only be called after
754 ** a locking-related function (i.e. fcntl()) has returned non-zero with
755 ** the value of errno as the first argument. Since a system call has failed,
756 ** errno should be non-zero.
757 **
758 ** Despite this, if errno really is zero, we still don't want to return
759 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
760 ** propagated back to the caller. Commenting this branch out means errno==0
761 ** will be handled by the "default:" case below.
762 */
drh734c9862008-11-28 15:37:20 +0000763 case 0:
764 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000765#endif
766
drh734c9862008-11-28 15:37:20 +0000767 case EAGAIN:
768 case ETIMEDOUT:
769 case EBUSY:
770 case EINTR:
771 case ENOLCK:
772 /* random NFS retry error, unless during file system support
773 * introspection, in which it actually means what it says */
774 return SQLITE_BUSY;
775
776 case EACCES:
777 /* EACCES is like EAGAIN during locking operations, but not any other time*/
778 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000779 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
780 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
781 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000782 return SQLITE_BUSY;
783 }
784 /* else fall through */
785 case EPERM:
786 return SQLITE_PERM;
787
drh734c9862008-11-28 15:37:20 +0000788#if EOPNOTSUPP!=ENOTSUP
789 case EOPNOTSUPP:
790 /* something went terribly awry, unless during file system support
791 * introspection, in which it actually means what it says */
792#endif
793#ifdef ENOTSUP
794 case ENOTSUP:
795 /* invalid fd, unless during file system support introspection, in which
796 * it actually means what it says */
797#endif
798 case EIO:
799 case EBADF:
800 case EINVAL:
801 case ENOTCONN:
802 case ENODEV:
803 case ENXIO:
804 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000805#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000806 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000807#endif
drh734c9862008-11-28 15:37:20 +0000808 case ENOSYS:
809 /* these should force the client to close the file and reconnect */
810
811 default:
812 return sqliteIOErr;
813 }
814}
815
816
drh734c9862008-11-28 15:37:20 +0000817/******************************************************************************
818****************** Begin Unique File ID Utility Used By VxWorks ***************
819**
820** On most versions of unix, we can get a unique ID for a file by concatenating
821** the device number and the inode number. But this does not work on VxWorks.
822** On VxWorks, a unique file id must be based on the canonical filename.
823**
824** A pointer to an instance of the following structure can be used as a
825** unique file ID in VxWorks. Each instance of this structure contains
826** a copy of the canonical filename. There is also a reference count.
827** The structure is reclaimed when the number of pointers to it drops to
828** zero.
829**
830** There are never very many files open at one time and lookups are not
831** a performance-critical path, so it is sufficient to put these
832** structures on a linked list.
833*/
834struct vxworksFileId {
835 struct vxworksFileId *pNext; /* Next in a list of them all */
836 int nRef; /* Number of references to this one */
837 int nName; /* Length of the zCanonicalName[] string */
838 char *zCanonicalName; /* Canonical filename */
839};
840
841#if OS_VXWORKS
842/*
drh9b35ea62008-11-29 02:20:26 +0000843** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000844** variable:
845*/
846static struct vxworksFileId *vxworksFileList = 0;
847
848/*
849** Simplify a filename into its canonical form
850** by making the following changes:
851**
852** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000853** * convert /./ into just /
854** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000855**
856** Changes are made in-place. Return the new name length.
857**
858** The original filename is in z[0..n-1]. Return the number of
859** characters in the simplified name.
860*/
861static int vxworksSimplifyName(char *z, int n){
862 int i, j;
863 while( n>1 && z[n-1]=='/' ){ n--; }
864 for(i=j=0; i<n; i++){
865 if( z[i]=='/' ){
866 if( z[i+1]=='/' ) continue;
867 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
868 i += 1;
869 continue;
870 }
871 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
872 while( j>0 && z[j-1]!='/' ){ j--; }
873 if( j>0 ){ j--; }
874 i += 2;
875 continue;
876 }
877 }
878 z[j++] = z[i];
879 }
880 z[j] = 0;
881 return j;
882}
883
884/*
885** Find a unique file ID for the given absolute pathname. Return
886** a pointer to the vxworksFileId object. This pointer is the unique
887** file ID.
888**
889** The nRef field of the vxworksFileId object is incremented before
890** the object is returned. A new vxworksFileId object is created
891** and added to the global list if necessary.
892**
893** If a memory allocation error occurs, return NULL.
894*/
895static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
896 struct vxworksFileId *pNew; /* search key and new file ID */
897 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
898 int n; /* Length of zAbsoluteName string */
899
900 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000901 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000902 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
903 if( pNew==0 ) return 0;
904 pNew->zCanonicalName = (char*)&pNew[1];
905 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
906 n = vxworksSimplifyName(pNew->zCanonicalName, n);
907
908 /* Search for an existing entry that matching the canonical name.
909 ** If found, increment the reference count and return a pointer to
910 ** the existing file ID.
911 */
912 unixEnterMutex();
913 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
914 if( pCandidate->nName==n
915 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
916 ){
917 sqlite3_free(pNew);
918 pCandidate->nRef++;
919 unixLeaveMutex();
920 return pCandidate;
921 }
922 }
923
924 /* No match was found. We will make a new file ID */
925 pNew->nRef = 1;
926 pNew->nName = n;
927 pNew->pNext = vxworksFileList;
928 vxworksFileList = pNew;
929 unixLeaveMutex();
930 return pNew;
931}
932
933/*
934** Decrement the reference count on a vxworksFileId object. Free
935** the object when the reference count reaches zero.
936*/
937static void vxworksReleaseFileId(struct vxworksFileId *pId){
938 unixEnterMutex();
939 assert( pId->nRef>0 );
940 pId->nRef--;
941 if( pId->nRef==0 ){
942 struct vxworksFileId **pp;
943 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
944 assert( *pp==pId );
945 *pp = pId->pNext;
946 sqlite3_free(pId);
947 }
948 unixLeaveMutex();
949}
950#endif /* OS_VXWORKS */
951/*************** End of Unique File ID Utility Used By VxWorks ****************
952******************************************************************************/
953
954
955/******************************************************************************
956*************************** Posix Advisory Locking ****************************
957**
drh9b35ea62008-11-29 02:20:26 +0000958** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000959** section 6.5.2.2 lines 483 through 490 specify that when a process
960** sets or clears a lock, that operation overrides any prior locks set
961** by the same process. It does not explicitly say so, but this implies
962** that it overrides locks set by the same process using a different
963** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000964**
965** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000966** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
967**
968** Suppose ./file1 and ./file2 are really the same file (because
969** one is a hard or symbolic link to the other) then if you set
970** an exclusive lock on fd1, then try to get an exclusive lock
971** on fd2, it works. I would have expected the second lock to
972** fail since there was already a lock on the file due to fd1.
973** But not so. Since both locks came from the same process, the
974** second overrides the first, even though they were on different
975** file descriptors opened on different file names.
976**
drh734c9862008-11-28 15:37:20 +0000977** This means that we cannot use POSIX locks to synchronize file access
978** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000979** to synchronize access for threads in separate processes, but not
980** threads within the same process.
981**
982** To work around the problem, SQLite has to manage file locks internally
983** on its own. Whenever a new database is opened, we have to find the
984** specific inode of the database file (the inode is determined by the
985** st_dev and st_ino fields of the stat structure that fstat() fills in)
986** and check for locks already existing on that inode. When locks are
987** created or removed, we have to look at our own internal record of the
988** locks to see if another thread has previously set a lock on that same
989** inode.
990**
drh9b35ea62008-11-29 02:20:26 +0000991** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
992** For VxWorks, we have to use the alternative unique ID system based on
993** canonical filename and implemented in the previous division.)
994**
danielk1977ad94b582007-08-20 06:44:22 +0000995** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000996** descriptor. It is now a structure that holds the integer file
997** descriptor and a pointer to a structure that describes the internal
998** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000999** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001000** point to the same locking structure. The locking structure keeps
1001** a reference count (so we will know when to delete it) and a "cnt"
1002** field that tells us its internal lock status. cnt==0 means the
1003** file is unlocked. cnt==-1 means the file has an exclusive lock.
1004** cnt>0 means there are cnt shared locks on the file.
1005**
1006** Any attempt to lock or unlock a file first checks the locking
1007** structure. The fcntl() system call is only invoked to set a
1008** POSIX lock if the internal lock structure transitions between
1009** a locked and an unlocked state.
1010**
drh734c9862008-11-28 15:37:20 +00001011** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001012**
1013** If you close a file descriptor that points to a file that has locks,
1014** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001015** released. To work around this problem, each unixInodeInfo object
1016** maintains a count of the number of pending locks on tha inode.
1017** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001018** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001019** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001020** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001021** be closed and that list is walked (and cleared) when the last lock
1022** clears.
1023**
drh9b35ea62008-11-29 02:20:26 +00001024** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001025**
drh9b35ea62008-11-29 02:20:26 +00001026** Many older versions of linux use the LinuxThreads library which is
1027** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001028** A cannot be modified or overridden by a different thread B.
1029** Only thread A can modify the lock. Locking behavior is correct
1030** if the appliation uses the newer Native Posix Thread Library (NPTL)
1031** on linux - with NPTL a lock created by thread A can override locks
1032** in thread B. But there is no way to know at compile-time which
1033** threading library is being used. So there is no way to know at
1034** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001035** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001036** current process.
drh5fdae772004-06-29 03:29:00 +00001037**
drh8af6c222010-05-14 12:43:01 +00001038** SQLite used to support LinuxThreads. But support for LinuxThreads
1039** was dropped beginning with version 3.7.0. SQLite will still work with
1040** LinuxThreads provided that (1) there is no more than one connection
1041** per database file in the same process and (2) database connections
1042** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001043*/
1044
1045/*
1046** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001047** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001048*/
1049struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001050 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001051#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001052 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001053#else
drh107886a2008-11-21 22:21:50 +00001054 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001055#endif
1056};
1057
1058/*
drhbbd42a62004-05-22 17:41:58 +00001059** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001060** inode. Or, on LinuxThreads, there is one of these structures for
1061** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001062**
danielk1977ad94b582007-08-20 06:44:22 +00001063** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001064** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001065** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001066*/
drh8af6c222010-05-14 12:43:01 +00001067struct unixInodeInfo {
1068 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001069 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001070 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1071 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001072 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001073 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1074 int nLock; /* Number of outstanding file locks */
1075 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1076 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1077 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001078#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001079 unsigned long long sharedByte; /* for AFP simulated shared lock */
1080#endif
drh6c7d5c52008-11-21 20:32:33 +00001081#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001082 sem_t *pSem; /* Named POSIX semaphore */
1083 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001084#endif
drhbbd42a62004-05-22 17:41:58 +00001085};
1086
drhda0e7682008-07-30 15:27:54 +00001087/*
drh8af6c222010-05-14 12:43:01 +00001088** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001089*/
drhd91c68f2010-05-14 14:52:25 +00001090static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001091
drh5fdae772004-06-29 03:29:00 +00001092/*
dane18d4952011-02-21 11:46:24 +00001093**
1094** This function - unixLogError_x(), is only ever called via the macro
1095** unixLogError().
1096**
1097** It is invoked after an error occurs in an OS function and errno has been
1098** set. It logs a message using sqlite3_log() containing the current value of
1099** errno and, if possible, the human-readable equivalent from strerror() or
1100** strerror_r().
1101**
1102** The first argument passed to the macro should be the error code that
1103** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1104** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001105** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001106** if any.
1107*/
drh0e9365c2011-03-02 02:08:13 +00001108#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1109static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001110 int errcode, /* SQLite error code */
1111 const char *zFunc, /* Name of OS function that failed */
1112 const char *zPath, /* File path associated with error */
1113 int iLine /* Source line number where error occurred */
1114){
1115 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001116 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001117
1118 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1119 ** the strerror() function to obtain the human-readable error message
1120 ** equivalent to errno. Otherwise, use strerror_r().
1121 */
1122#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1123 char aErr[80];
1124 memset(aErr, 0, sizeof(aErr));
1125 zErr = aErr;
1126
1127 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001128 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001129 ** returns a pointer to a buffer containing the error message. That pointer
1130 ** may point to aErr[], or it may point to some static storage somewhere.
1131 ** Otherwise, assume that the system provides the POSIX version of
1132 ** strerror_r(), which always writes an error message into aErr[].
1133 **
1134 ** If the code incorrectly assumes that it is the POSIX version that is
1135 ** available, the error message will often be an empty string. Not a
1136 ** huge problem. Incorrectly concluding that the GNU version is available
1137 ** could lead to a segfault though.
1138 */
1139#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1140 zErr =
1141# endif
drh0e9365c2011-03-02 02:08:13 +00001142 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001143
1144#elif SQLITE_THREADSAFE
1145 /* This is a threadsafe build, but strerror_r() is not available. */
1146 zErr = "";
1147#else
1148 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001149 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001150#endif
1151
drh0e9365c2011-03-02 02:08:13 +00001152 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001153 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001154 "os_unix.c:%d: (%d) %s(%s) - %s",
1155 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001156 );
1157
1158 return errcode;
1159}
1160
drh0e9365c2011-03-02 02:08:13 +00001161/*
1162** Close a file descriptor.
1163**
1164** We assume that close() almost always works, since it is only in a
1165** very sick application or on a very sick platform that it might fail.
1166** If it does fail, simply leak the file descriptor, but do log the
1167** error.
1168**
1169** Note that it is not safe to retry close() after EINTR since the
1170** file descriptor might have already been reused by another thread.
1171** So we don't even try to recover from an EINTR. Just log the error
1172** and move on.
1173*/
1174static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001175 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001176 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1177 pFile ? pFile->zPath : 0, lineno);
1178 }
1179}
dane18d4952011-02-21 11:46:24 +00001180
1181/*
drhe6d41732015-02-21 00:49:00 +00001182** Set the pFile->lastErrno. Do this in a subroutine as that provides
1183** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001184*/
1185static void storeLastErrno(unixFile *pFile, int error){
1186 pFile->lastErrno = error;
1187}
1188
1189/*
danb0ac3e32010-06-16 10:55:42 +00001190** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001191*/
drh0e9365c2011-03-02 02:08:13 +00001192static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001193 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001194 UnixUnusedFd *p;
1195 UnixUnusedFd *pNext;
1196 for(p=pInode->pUnused; p; p=pNext){
1197 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001198 robust_close(pFile, p->fd, __LINE__);
1199 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001200 }
drh0e9365c2011-03-02 02:08:13 +00001201 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001202}
1203
1204/*
drh8af6c222010-05-14 12:43:01 +00001205** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001206**
1207** The mutex entered using the unixEnterMutex() function must be held
1208** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001209*/
danb0ac3e32010-06-16 10:55:42 +00001210static void releaseInodeInfo(unixFile *pFile){
1211 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001212 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001213 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001214 pInode->nRef--;
1215 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001216 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001217 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001218 if( pInode->pPrev ){
1219 assert( pInode->pPrev->pNext==pInode );
1220 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001221 }else{
drh8af6c222010-05-14 12:43:01 +00001222 assert( inodeList==pInode );
1223 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001224 }
drh8af6c222010-05-14 12:43:01 +00001225 if( pInode->pNext ){
1226 assert( pInode->pNext->pPrev==pInode );
1227 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001228 }
drh8af6c222010-05-14 12:43:01 +00001229 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001230 }
drhbbd42a62004-05-22 17:41:58 +00001231 }
1232}
1233
1234/*
drh8af6c222010-05-14 12:43:01 +00001235** Given a file descriptor, locate the unixInodeInfo object that
1236** describes that file descriptor. Create a new one if necessary. The
1237** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001238**
dan9359c7b2009-08-21 08:29:10 +00001239** The mutex entered using the unixEnterMutex() function must be held
1240** when this function is called.
1241**
drh6c7d5c52008-11-21 20:32:33 +00001242** Return an appropriate error code.
1243*/
drh8af6c222010-05-14 12:43:01 +00001244static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001245 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001246 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001247){
1248 int rc; /* System call return code */
1249 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001250 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1251 struct stat statbuf; /* Low-level file information */
1252 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001253
dan9359c7b2009-08-21 08:29:10 +00001254 assert( unixMutexHeld() );
1255
drh6c7d5c52008-11-21 20:32:33 +00001256 /* Get low-level information about the file that we can used to
1257 ** create a unique name for the file.
1258 */
1259 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001260 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001261 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001262 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001263#ifdef EOVERFLOW
1264 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1265#endif
1266 return SQLITE_IOERR;
1267 }
1268
drheb0d74f2009-02-03 15:27:02 +00001269#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001270 /* On OS X on an msdos filesystem, the inode number is reported
1271 ** incorrectly for zero-size files. See ticket #3260. To work
1272 ** around this problem (we consider it a bug in OS X, not SQLite)
1273 ** we always increase the file size to 1 by writing a single byte
1274 ** prior to accessing the inode number. The one byte written is
1275 ** an ASCII 'S' character which also happens to be the first byte
1276 ** in the header of every SQLite database. In this way, if there
1277 ** is a race condition such that another thread has already populated
1278 ** the first page of the database, no damage is done.
1279 */
drh7ed97b92010-01-20 13:07:21 +00001280 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001281 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001282 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001283 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001284 return SQLITE_IOERR;
1285 }
drh99ab3b12011-03-02 15:09:07 +00001286 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001287 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001288 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001289 return SQLITE_IOERR;
1290 }
1291 }
drheb0d74f2009-02-03 15:27:02 +00001292#endif
drh6c7d5c52008-11-21 20:32:33 +00001293
drh8af6c222010-05-14 12:43:01 +00001294 memset(&fileId, 0, sizeof(fileId));
1295 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001296#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001297 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001298#else
drh8af6c222010-05-14 12:43:01 +00001299 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001300#endif
drh8af6c222010-05-14 12:43:01 +00001301 pInode = inodeList;
1302 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1303 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001304 }
drh8af6c222010-05-14 12:43:01 +00001305 if( pInode==0 ){
1306 pInode = sqlite3_malloc( sizeof(*pInode) );
1307 if( pInode==0 ){
1308 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001309 }
drh8af6c222010-05-14 12:43:01 +00001310 memset(pInode, 0, sizeof(*pInode));
1311 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1312 pInode->nRef = 1;
1313 pInode->pNext = inodeList;
1314 pInode->pPrev = 0;
1315 if( inodeList ) inodeList->pPrev = pInode;
1316 inodeList = pInode;
1317 }else{
1318 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001319 }
drh8af6c222010-05-14 12:43:01 +00001320 *ppInode = pInode;
1321 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001322}
drh6c7d5c52008-11-21 20:32:33 +00001323
drhb959a012013-12-07 12:29:22 +00001324/*
1325** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1326*/
1327static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001328#if OS_VXWORKS
1329 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1330#else
drhb959a012013-12-07 12:29:22 +00001331 struct stat buf;
1332 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001333 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001334#endif
drhb959a012013-12-07 12:29:22 +00001335}
1336
aswift5b1a2562008-08-22 00:22:35 +00001337
1338/*
drhfbc7e882013-04-11 01:16:15 +00001339** Check a unixFile that is a database. Verify the following:
1340**
1341** (1) There is exactly one hard link on the file
1342** (2) The file is not a symbolic link
1343** (3) The file has not been renamed or unlinked
1344**
1345** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1346*/
1347static void verifyDbFile(unixFile *pFile){
1348 struct stat buf;
1349 int rc;
drh3044b512014-06-16 16:41:52 +00001350 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1351 /* One or more of the following warnings have already been issued. Do not
1352 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001353 return;
1354 }
1355 rc = osFstat(pFile->h, &buf);
1356 if( rc!=0 ){
1357 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1358 pFile->ctrlFlags |= UNIXFILE_WARNED;
1359 return;
1360 }
drh3044b512014-06-16 16:41:52 +00001361 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001362 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1363 pFile->ctrlFlags |= UNIXFILE_WARNED;
1364 return;
1365 }
1366 if( buf.st_nlink>1 ){
1367 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1368 pFile->ctrlFlags |= UNIXFILE_WARNED;
1369 return;
1370 }
drhb959a012013-12-07 12:29:22 +00001371 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001372 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1373 pFile->ctrlFlags |= UNIXFILE_WARNED;
1374 return;
1375 }
1376}
1377
1378
1379/*
danielk197713adf8a2004-06-03 16:08:41 +00001380** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001381** file by this or any other process. If such a lock is held, set *pResOut
1382** to a non-zero value otherwise *pResOut is set to zero. The return value
1383** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001384*/
danielk1977861f7452008-06-05 11:39:11 +00001385static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001386 int rc = SQLITE_OK;
1387 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001388 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001389
danielk1977861f7452008-06-05 11:39:11 +00001390 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1391
drh054889e2005-11-30 03:20:31 +00001392 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001393 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001394
1395 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001396 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001397 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001398 }
1399
drh2ac3ee92004-06-07 16:27:46 +00001400 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001401 */
danielk197709480a92009-02-09 05:32:32 +00001402#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001403 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001404 struct flock lock;
1405 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001406 lock.l_start = RESERVED_BYTE;
1407 lock.l_len = 1;
1408 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001409 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1410 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001411 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001412 } else if( lock.l_type!=F_UNLCK ){
1413 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001414 }
1415 }
danielk197709480a92009-02-09 05:32:32 +00001416#endif
danielk197713adf8a2004-06-03 16:08:41 +00001417
drh6c7d5c52008-11-21 20:32:33 +00001418 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001419 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001420
aswift5b1a2562008-08-22 00:22:35 +00001421 *pResOut = reserved;
1422 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001423}
1424
1425/*
drha7e61d82011-03-12 17:02:57 +00001426** Attempt to set a system-lock on the file pFile. The lock is
1427** described by pLock.
1428**
drh77197112011-03-15 19:08:48 +00001429** If the pFile was opened read/write from unix-excl, then the only lock
1430** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001431** the first time any lock is attempted. All subsequent system locking
1432** operations become no-ops. Locking operations still happen internally,
1433** in order to coordinate access between separate database connections
1434** within this process, but all of that is handled in memory and the
1435** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001436**
1437** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1438** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1439** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001440**
1441** Zero is returned if the call completes successfully, or -1 if a call
1442** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001443*/
1444static int unixFileLock(unixFile *pFile, struct flock *pLock){
1445 int rc;
drh3cb93392011-03-12 18:10:44 +00001446 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001447 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001448 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001449 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1450 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1451 ){
drh3cb93392011-03-12 18:10:44 +00001452 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001453 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001454 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001455 lock.l_whence = SEEK_SET;
1456 lock.l_start = SHARED_FIRST;
1457 lock.l_len = SHARED_SIZE;
1458 lock.l_type = F_WRLCK;
1459 rc = osFcntl(pFile->h, F_SETLK, &lock);
1460 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001461 pInode->bProcessLock = 1;
1462 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001463 }else{
1464 rc = 0;
1465 }
1466 }else{
1467 rc = osFcntl(pFile->h, F_SETLK, pLock);
1468 }
1469 return rc;
1470}
1471
1472/*
drh308c2a52010-05-14 11:30:18 +00001473** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001474** of the following:
1475**
drh2ac3ee92004-06-07 16:27:46 +00001476** (1) SHARED_LOCK
1477** (2) RESERVED_LOCK
1478** (3) PENDING_LOCK
1479** (4) EXCLUSIVE_LOCK
1480**
drhb3e04342004-06-08 00:47:47 +00001481** Sometimes when requesting one lock state, additional lock states
1482** are inserted in between. The locking might fail on one of the later
1483** transitions leaving the lock state different from what it started but
1484** still short of its goal. The following chart shows the allowed
1485** transitions and the inserted intermediate states:
1486**
1487** UNLOCKED -> SHARED
1488** SHARED -> RESERVED
1489** SHARED -> (PENDING) -> EXCLUSIVE
1490** RESERVED -> (PENDING) -> EXCLUSIVE
1491** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001492**
drha6abd042004-06-09 17:37:22 +00001493** This routine will only increase a lock. Use the sqlite3OsUnlock()
1494** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001495*/
drh308c2a52010-05-14 11:30:18 +00001496static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001497 /* The following describes the implementation of the various locks and
1498 ** lock transitions in terms of the POSIX advisory shared and exclusive
1499 ** lock primitives (called read-locks and write-locks below, to avoid
1500 ** confusion with SQLite lock names). The algorithms are complicated
1501 ** slightly in order to be compatible with windows systems simultaneously
1502 ** accessing the same database file, in case that is ever required.
1503 **
1504 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1505 ** byte', each single bytes at well known offsets, and the 'shared byte
1506 ** range', a range of 510 bytes at a well known offset.
1507 **
1508 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1509 ** byte'. If this is successful, a random byte from the 'shared byte
1510 ** range' is read-locked and the lock on the 'pending byte' released.
1511 **
danielk197790ba3bd2004-06-25 08:32:25 +00001512 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1513 ** A RESERVED lock is implemented by grabbing a write-lock on the
1514 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001515 **
1516 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001517 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1518 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1519 ** obtained, but existing SHARED locks are allowed to persist. A process
1520 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1521 ** This property is used by the algorithm for rolling back a journal file
1522 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001523 **
danielk197790ba3bd2004-06-25 08:32:25 +00001524 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1525 ** implemented by obtaining a write-lock on the entire 'shared byte
1526 ** range'. Since all other locks require a read-lock on one of the bytes
1527 ** within this range, this ensures that no other locks are held on the
1528 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001529 **
1530 ** The reason a single byte cannot be used instead of the 'shared byte
1531 ** range' is that some versions of windows do not support read-locks. By
1532 ** locking a random byte from a range, concurrent SHARED locks may exist
1533 ** even if the locking primitive used is always a write-lock.
1534 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001535 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001536 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001537 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001538 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001539 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001540
drh054889e2005-11-30 03:20:31 +00001541 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001542 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1543 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001544 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001545
1546 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001547 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001548 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001549 */
drh308c2a52010-05-14 11:30:18 +00001550 if( pFile->eFileLock>=eFileLock ){
1551 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1552 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001553 return SQLITE_OK;
1554 }
1555
drh0c2694b2009-09-03 16:23:44 +00001556 /* Make sure the locking sequence is correct.
1557 ** (1) We never move from unlocked to anything higher than shared lock.
1558 ** (2) SQLite never explicitly requests a pendig lock.
1559 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001560 */
drh308c2a52010-05-14 11:30:18 +00001561 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1562 assert( eFileLock!=PENDING_LOCK );
1563 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001564
drh8af6c222010-05-14 12:43:01 +00001565 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001566 */
drh6c7d5c52008-11-21 20:32:33 +00001567 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001568 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001569
danielk1977ad94b582007-08-20 06:44:22 +00001570 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001571 ** handle that precludes the requested lock, return BUSY.
1572 */
drh8af6c222010-05-14 12:43:01 +00001573 if( (pFile->eFileLock!=pInode->eFileLock &&
1574 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001575 ){
1576 rc = SQLITE_BUSY;
1577 goto end_lock;
1578 }
1579
1580 /* If a SHARED lock is requested, and some thread using this PID already
1581 ** has a SHARED or RESERVED lock, then increment reference counts and
1582 ** return SQLITE_OK.
1583 */
drh308c2a52010-05-14 11:30:18 +00001584 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001585 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001586 assert( eFileLock==SHARED_LOCK );
1587 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001588 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001589 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001590 pInode->nShared++;
1591 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001592 goto end_lock;
1593 }
1594
danielk19779a1d0ab2004-06-01 14:09:28 +00001595
drh3cde3bb2004-06-12 02:17:14 +00001596 /* A PENDING lock is needed before acquiring a SHARED lock and before
1597 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1598 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001599 */
drh0c2694b2009-09-03 16:23:44 +00001600 lock.l_len = 1L;
1601 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001602 if( eFileLock==SHARED_LOCK
1603 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001604 ){
drh308c2a52010-05-14 11:30:18 +00001605 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001606 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001607 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001608 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001609 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001610 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001611 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001612 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001613 goto end_lock;
1614 }
drh3cde3bb2004-06-12 02:17:14 +00001615 }
1616
1617
1618 /* If control gets to this point, then actually go ahead and make
1619 ** operating system calls for the specified lock.
1620 */
drh308c2a52010-05-14 11:30:18 +00001621 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001622 assert( pInode->nShared==0 );
1623 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001624 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001625
drh2ac3ee92004-06-07 16:27:46 +00001626 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001627 lock.l_start = SHARED_FIRST;
1628 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001629 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001630 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001631 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001632 }
dan661d71a2011-03-30 19:08:03 +00001633
drh2ac3ee92004-06-07 16:27:46 +00001634 /* Drop the temporary PENDING lock */
1635 lock.l_start = PENDING_BYTE;
1636 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001637 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001638 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1639 /* This could happen with a network mount */
1640 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001641 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001642 }
dan661d71a2011-03-30 19:08:03 +00001643
1644 if( rc ){
1645 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001646 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001647 }
dan661d71a2011-03-30 19:08:03 +00001648 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001649 }else{
drh308c2a52010-05-14 11:30:18 +00001650 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001651 pInode->nLock++;
1652 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001653 }
drh8af6c222010-05-14 12:43:01 +00001654 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001655 /* We are trying for an exclusive lock but another thread in this
1656 ** same process is still holding a shared lock. */
1657 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001658 }else{
drh3cde3bb2004-06-12 02:17:14 +00001659 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001660 ** assumed that there is a SHARED or greater lock on the file
1661 ** already.
1662 */
drh308c2a52010-05-14 11:30:18 +00001663 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001664 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001665
1666 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1667 if( eFileLock==RESERVED_LOCK ){
1668 lock.l_start = RESERVED_BYTE;
1669 lock.l_len = 1L;
1670 }else{
1671 lock.l_start = SHARED_FIRST;
1672 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001673 }
dan661d71a2011-03-30 19:08:03 +00001674
1675 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001676 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001677 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001678 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001679 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001680 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001681 }
drhbbd42a62004-05-22 17:41:58 +00001682 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001683
drh8f941bc2009-01-14 23:03:40 +00001684
drhd3d8c042012-05-29 17:02:40 +00001685#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001686 /* Set up the transaction-counter change checking flags when
1687 ** transitioning from a SHARED to a RESERVED lock. The change
1688 ** from SHARED to RESERVED marks the beginning of a normal
1689 ** write operation (not a hot journal rollback).
1690 */
1691 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001692 && pFile->eFileLock<=SHARED_LOCK
1693 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001694 ){
1695 pFile->transCntrChng = 0;
1696 pFile->dbUpdate = 0;
1697 pFile->inNormalWrite = 1;
1698 }
1699#endif
1700
1701
danielk1977ecb2a962004-06-02 06:30:16 +00001702 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001703 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001704 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001705 }else if( eFileLock==EXCLUSIVE_LOCK ){
1706 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001707 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001708 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001709
1710end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001711 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001712 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1713 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001714 return rc;
1715}
1716
1717/*
dan08da86a2009-08-21 17:18:03 +00001718** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001719** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001720*/
1721static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001722 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001723 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001724 p->pNext = pInode->pUnused;
1725 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001726 pFile->h = -1;
1727 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001728}
1729
1730/*
drh308c2a52010-05-14 11:30:18 +00001731** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001732** must be either NO_LOCK or SHARED_LOCK.
1733**
1734** If the locking level of the file descriptor is already at or below
1735** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001736**
1737** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1738** the byte range is divided into 2 parts and the first part is unlocked then
1739** set to a read lock, then the other part is simply unlocked. This works
1740** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1741** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001742*/
drha7e61d82011-03-12 17:02:57 +00001743static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001744 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001745 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001746 struct flock lock;
1747 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001748
drh054889e2005-11-30 03:20:31 +00001749 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001750 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001751 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001752 getpid()));
drha6abd042004-06-09 17:37:22 +00001753
drh308c2a52010-05-14 11:30:18 +00001754 assert( eFileLock<=SHARED_LOCK );
1755 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001756 return SQLITE_OK;
1757 }
drh6c7d5c52008-11-21 20:32:33 +00001758 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001759 pInode = pFile->pInode;
1760 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001761 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001762 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001763
drhd3d8c042012-05-29 17:02:40 +00001764#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001765 /* When reducing a lock such that other processes can start
1766 ** reading the database file again, make sure that the
1767 ** transaction counter was updated if any part of the database
1768 ** file changed. If the transaction counter is not updated,
1769 ** other connections to the same file might not realize that
1770 ** the file has changed and hence might not know to flush their
1771 ** cache. The use of a stale cache can lead to database corruption.
1772 */
drh8f941bc2009-01-14 23:03:40 +00001773 pFile->inNormalWrite = 0;
1774#endif
1775
drh7ed97b92010-01-20 13:07:21 +00001776 /* downgrading to a shared lock on NFS involves clearing the write lock
1777 ** before establishing the readlock - to avoid a race condition we downgrade
1778 ** the lock in 2 blocks, so that part of the range will be covered by a
1779 ** write lock until the rest is covered by a read lock:
1780 ** 1: [WWWWW]
1781 ** 2: [....W]
1782 ** 3: [RRRRW]
1783 ** 4: [RRRR.]
1784 */
drh308c2a52010-05-14 11:30:18 +00001785 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001786#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001787 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001788 assert( handleNFSUnlock==0 );
1789#endif
1790#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001791 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001792 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001793 off_t divSize = SHARED_SIZE - 1;
1794
1795 lock.l_type = F_UNLCK;
1796 lock.l_whence = SEEK_SET;
1797 lock.l_start = SHARED_FIRST;
1798 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001799 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001800 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001801 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001802 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;
aswift5b1a2562008-08-22 00:22:35 +00001806 }
drh7ed97b92010-01-20 13:07:21 +00001807 lock.l_type = F_RDLCK;
1808 lock.l_whence = SEEK_SET;
1809 lock.l_start = SHARED_FIRST;
1810 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001811 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001812 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001813 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1814 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 }
1819 lock.l_type = F_UNLCK;
1820 lock.l_whence = SEEK_SET;
1821 lock.l_start = SHARED_FIRST+divSize;
1822 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001823 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001824 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001825 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001826 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001827 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001828 }
1829 goto end_unlock;
1830 }
drh30f776f2011-02-25 03:25:07 +00001831 }else
1832#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1833 {
drh7ed97b92010-01-20 13:07:21 +00001834 lock.l_type = F_RDLCK;
1835 lock.l_whence = SEEK_SET;
1836 lock.l_start = SHARED_FIRST;
1837 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001838 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001839 /* In theory, the call to unixFileLock() cannot fail because another
1840 ** process is holding an incompatible lock. If it does, this
1841 ** indicates that the other process is not following the locking
1842 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1843 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1844 ** an assert to fail). */
1845 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001846 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001847 goto end_unlock;
1848 }
drh9c105bb2004-10-02 20:38:28 +00001849 }
1850 }
drhbbd42a62004-05-22 17:41:58 +00001851 lock.l_type = F_UNLCK;
1852 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001853 lock.l_start = PENDING_BYTE;
1854 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001855 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001856 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001857 }else{
danea83bc62011-04-01 11:56:32 +00001858 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001859 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001860 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001861 }
drhbbd42a62004-05-22 17:41:58 +00001862 }
drh308c2a52010-05-14 11:30:18 +00001863 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001864 /* Decrement the shared lock counter. Release the lock using an
1865 ** OS call only when all threads in this same process have released
1866 ** the lock.
1867 */
drh8af6c222010-05-14 12:43:01 +00001868 pInode->nShared--;
1869 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001870 lock.l_type = F_UNLCK;
1871 lock.l_whence = SEEK_SET;
1872 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001873 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001874 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001875 }else{
danea83bc62011-04-01 11:56:32 +00001876 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001877 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001878 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001879 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001880 }
drha6abd042004-06-09 17:37:22 +00001881 }
1882
drhbbd42a62004-05-22 17:41:58 +00001883 /* Decrement the count of locks against this same file. When the
1884 ** count reaches zero, close any other file descriptors whose close
1885 ** was deferred because of outstanding locks.
1886 */
drh8af6c222010-05-14 12:43:01 +00001887 pInode->nLock--;
1888 assert( pInode->nLock>=0 );
1889 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001890 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001891 }
1892 }
drhf2f105d2012-08-20 15:53:54 +00001893
aswift5b1a2562008-08-22 00:22:35 +00001894end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001895 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001896 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001897 return rc;
drhbbd42a62004-05-22 17:41:58 +00001898}
1899
1900/*
drh308c2a52010-05-14 11:30:18 +00001901** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001902** must be either NO_LOCK or SHARED_LOCK.
1903**
1904** If the locking level of the file descriptor is already at or below
1905** the requested locking level, this routine is a no-op.
1906*/
drh308c2a52010-05-14 11:30:18 +00001907static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001908#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001909 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001910#endif
drha7e61d82011-03-12 17:02:57 +00001911 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001912}
1913
mistachkine98844f2013-08-24 00:59:24 +00001914#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001915static int unixMapfile(unixFile *pFd, i64 nByte);
1916static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001917#endif
danf23da962013-03-23 21:00:41 +00001918
drh7ed97b92010-01-20 13:07:21 +00001919/*
danielk1977e339d652008-06-28 11:23:00 +00001920** This function performs the parts of the "close file" operation
1921** common to all locking schemes. It closes the directory and file
1922** handles, if they are valid, and sets all fields of the unixFile
1923** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001924**
1925** It is *not* necessary to hold the mutex when this routine is called,
1926** even on VxWorks. A mutex will be acquired on VxWorks by the
1927** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001928*/
1929static int closeUnixFile(sqlite3_file *id){
1930 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001931#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001932 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001933#endif
dan661d71a2011-03-30 19:08:03 +00001934 if( pFile->h>=0 ){
1935 robust_close(pFile, pFile->h, __LINE__);
1936 pFile->h = -1;
1937 }
1938#if OS_VXWORKS
1939 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001940 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001941 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001942 }
1943 vxworksReleaseFileId(pFile->pId);
1944 pFile->pId = 0;
1945 }
1946#endif
drh0bdbc902014-06-16 18:35:06 +00001947#ifdef SQLITE_UNLINK_AFTER_CLOSE
1948 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1949 osUnlink(pFile->zPath);
1950 sqlite3_free(*(char**)&pFile->zPath);
1951 pFile->zPath = 0;
1952 }
1953#endif
dan661d71a2011-03-30 19:08:03 +00001954 OSTRACE(("CLOSE %-3d\n", pFile->h));
1955 OpenCounter(-1);
1956 sqlite3_free(pFile->pUnused);
1957 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001958 return SQLITE_OK;
1959}
1960
1961/*
danielk1977e3026632004-06-22 11:29:02 +00001962** Close a file.
1963*/
danielk197762079062007-08-15 17:08:46 +00001964static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001965 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001966 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001967 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001968 unixUnlock(id, NO_LOCK);
1969 unixEnterMutex();
1970
1971 /* unixFile.pInode is always valid here. Otherwise, a different close
1972 ** routine (e.g. nolockClose()) would be called instead.
1973 */
1974 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1975 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1976 /* If there are outstanding locks, do not actually close the file just
1977 ** yet because that would clear those locks. Instead, add the file
1978 ** descriptor to pInode->pUnused list. It will be automatically closed
1979 ** when the last lock is cleared.
1980 */
1981 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001982 }
dan661d71a2011-03-30 19:08:03 +00001983 releaseInodeInfo(pFile);
1984 rc = closeUnixFile(id);
1985 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001986 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001987}
1988
drh734c9862008-11-28 15:37:20 +00001989/************** End of the posix advisory lock implementation *****************
1990******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001991
drh734c9862008-11-28 15:37:20 +00001992/******************************************************************************
1993****************************** No-op Locking **********************************
1994**
1995** Of the various locking implementations available, this is by far the
1996** simplest: locking is ignored. No attempt is made to lock the database
1997** file for reading or writing.
1998**
1999** This locking mode is appropriate for use on read-only databases
2000** (ex: databases that are burned into CD-ROM, for example.) It can
2001** also be used if the application employs some external mechanism to
2002** prevent simultaneous access of the same database by two or more
2003** database connections. But there is a serious risk of database
2004** corruption if this locking mode is used in situations where multiple
2005** database connections are accessing the same database file at the same
2006** time and one or more of those connections are writing.
2007*/
drhbfe66312006-10-03 17:40:40 +00002008
drh734c9862008-11-28 15:37:20 +00002009static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2010 UNUSED_PARAMETER(NotUsed);
2011 *pResOut = 0;
2012 return SQLITE_OK;
2013}
drh734c9862008-11-28 15:37:20 +00002014static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2015 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2016 return SQLITE_OK;
2017}
drh734c9862008-11-28 15:37:20 +00002018static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2019 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2020 return SQLITE_OK;
2021}
2022
2023/*
drh9b35ea62008-11-29 02:20:26 +00002024** Close the file.
drh734c9862008-11-28 15:37:20 +00002025*/
2026static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002027 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002028}
2029
2030/******************* End of the no-op lock implementation *********************
2031******************************************************************************/
2032
2033/******************************************************************************
2034************************* Begin dot-file Locking ******************************
2035**
mistachkin48864df2013-03-21 21:20:32 +00002036** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002037** files (really a directory) to control access to the database. This works
2038** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002039**
2040** (1) There is zero concurrency. A single reader blocks all other
2041** connections from reading or writing the database.
2042**
2043** (2) An application crash or power loss can leave stale lock files
2044** sitting around that need to be cleared manually.
2045**
2046** Nevertheless, a dotlock is an appropriate locking mode for use if no
2047** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002048**
drh9ef6bc42011-11-04 02:24:02 +00002049** Dotfile locking works by creating a subdirectory in the same directory as
2050** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002051** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002052** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002053*/
2054
2055/*
2056** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002057** lock directory.
drh734c9862008-11-28 15:37:20 +00002058*/
2059#define DOTLOCK_SUFFIX ".lock"
2060
drh7708e972008-11-29 00:56:52 +00002061/*
2062** This routine checks if there is a RESERVED lock held on the specified
2063** file by this or any other process. If such a lock is held, set *pResOut
2064** to a non-zero value otherwise *pResOut is set to zero. The return value
2065** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2066**
2067** In dotfile locking, either a lock exists or it does not. So in this
2068** variation of CheckReservedLock(), *pResOut is set to true if any lock
2069** is held on the file and false if the file is unlocked.
2070*/
drh734c9862008-11-28 15:37:20 +00002071static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2072 int rc = SQLITE_OK;
2073 int reserved = 0;
2074 unixFile *pFile = (unixFile*)id;
2075
2076 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2077
2078 assert( pFile );
2079
2080 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002081 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002082 /* Either this connection or some other connection in the same process
2083 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002084 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002085 }else{
2086 /* The lock is held if and only if the lockfile exists */
2087 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002088 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002089 }
drh308c2a52010-05-14 11:30:18 +00002090 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002091 *pResOut = reserved;
2092 return rc;
2093}
2094
drh7708e972008-11-29 00:56:52 +00002095/*
drh308c2a52010-05-14 11:30:18 +00002096** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002097** of the following:
2098**
2099** (1) SHARED_LOCK
2100** (2) RESERVED_LOCK
2101** (3) PENDING_LOCK
2102** (4) EXCLUSIVE_LOCK
2103**
2104** Sometimes when requesting one lock state, additional lock states
2105** are inserted in between. The locking might fail on one of the later
2106** transitions leaving the lock state different from what it started but
2107** still short of its goal. The following chart shows the allowed
2108** transitions and the inserted intermediate states:
2109**
2110** UNLOCKED -> SHARED
2111** SHARED -> RESERVED
2112** SHARED -> (PENDING) -> EXCLUSIVE
2113** RESERVED -> (PENDING) -> EXCLUSIVE
2114** PENDING -> EXCLUSIVE
2115**
2116** This routine will only increase a lock. Use the sqlite3OsUnlock()
2117** routine to lower a locking level.
2118**
2119** With dotfile locking, we really only support state (4): EXCLUSIVE.
2120** But we track the other locking levels internally.
2121*/
drh308c2a52010-05-14 11:30:18 +00002122static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002123 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002124 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002125 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002126
drh7708e972008-11-29 00:56:52 +00002127
2128 /* If we have any lock, then the lock file already exists. All we have
2129 ** to do is adjust our internal record of the lock level.
2130 */
drh308c2a52010-05-14 11:30:18 +00002131 if( pFile->eFileLock > NO_LOCK ){
2132 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002133 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002134#ifdef HAVE_UTIME
2135 utime(zLockFile, NULL);
2136#else
drh734c9862008-11-28 15:37:20 +00002137 utimes(zLockFile, NULL);
2138#endif
drh7708e972008-11-29 00:56:52 +00002139 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002140 }
2141
2142 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002143 rc = osMkdir(zLockFile, 0777);
2144 if( rc<0 ){
2145 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002146 int tErrno = errno;
2147 if( EEXIST == tErrno ){
2148 rc = SQLITE_BUSY;
2149 } else {
2150 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2151 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002152 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002153 }
2154 }
drh7708e972008-11-29 00:56:52 +00002155 return rc;
drh734c9862008-11-28 15:37:20 +00002156 }
drh734c9862008-11-28 15:37:20 +00002157
2158 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002159 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002160 return rc;
2161}
2162
drh7708e972008-11-29 00:56:52 +00002163/*
drh308c2a52010-05-14 11:30:18 +00002164** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002165** must be either NO_LOCK or SHARED_LOCK.
2166**
2167** If the locking level of the file descriptor is already at or below
2168** the requested locking level, this routine is a no-op.
2169**
2170** When the locking level reaches NO_LOCK, delete the lock file.
2171*/
drh308c2a52010-05-14 11:30:18 +00002172static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002173 unixFile *pFile = (unixFile*)id;
2174 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002175 int rc;
drh734c9862008-11-28 15:37:20 +00002176
2177 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002178 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002179 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002180 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002181
2182 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002183 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002184 return SQLITE_OK;
2185 }
drh7708e972008-11-29 00:56:52 +00002186
2187 /* To downgrade to shared, simply update our internal notion of the
2188 ** lock state. No need to mess with the file on disk.
2189 */
drh308c2a52010-05-14 11:30:18 +00002190 if( eFileLock==SHARED_LOCK ){
2191 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002192 return SQLITE_OK;
2193 }
2194
drh7708e972008-11-29 00:56:52 +00002195 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002196 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002197 rc = osRmdir(zLockFile);
2198 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2199 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002200 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002201 rc = 0;
drh734c9862008-11-28 15:37:20 +00002202 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002203 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002204 }
2205 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002206 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002207 }
2208 return rc;
2209 }
drh308c2a52010-05-14 11:30:18 +00002210 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002211 return SQLITE_OK;
2212}
2213
2214/*
drh9b35ea62008-11-29 02:20:26 +00002215** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002216*/
2217static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002218 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002219 if( id ){
2220 unixFile *pFile = (unixFile*)id;
2221 dotlockUnlock(id, NO_LOCK);
2222 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002223 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002224 }
drh734c9862008-11-28 15:37:20 +00002225 return rc;
2226}
2227/****************** End of the dot-file lock implementation *******************
2228******************************************************************************/
2229
2230/******************************************************************************
2231************************** Begin flock Locking ********************************
2232**
2233** Use the flock() system call to do file locking.
2234**
drh6b9d6dd2008-12-03 19:34:47 +00002235** flock() locking is like dot-file locking in that the various
2236** fine-grain locking levels supported by SQLite are collapsed into
2237** a single exclusive lock. In other words, SHARED, RESERVED, and
2238** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2239** still works when you do this, but concurrency is reduced since
2240** only a single process can be reading the database at a time.
2241**
drh734c9862008-11-28 15:37:20 +00002242** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2243** compiling for VXWORKS.
2244*/
2245#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002246
drh6b9d6dd2008-12-03 19:34:47 +00002247/*
drhff812312011-02-23 13:33:46 +00002248** Retry flock() calls that fail with EINTR
2249*/
2250#ifdef EINTR
2251static int robust_flock(int fd, int op){
2252 int rc;
2253 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2254 return rc;
2255}
2256#else
drh5c819272011-02-23 14:00:12 +00002257# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002258#endif
2259
2260
2261/*
drh6b9d6dd2008-12-03 19:34:47 +00002262** This routine checks if there is a RESERVED lock held on the specified
2263** file by this or any other process. If such a lock is held, set *pResOut
2264** to a non-zero value otherwise *pResOut is set to zero. The return value
2265** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2266*/
drh734c9862008-11-28 15:37:20 +00002267static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2268 int rc = SQLITE_OK;
2269 int reserved = 0;
2270 unixFile *pFile = (unixFile*)id;
2271
2272 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2273
2274 assert( pFile );
2275
2276 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002277 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002278 reserved = 1;
2279 }
2280
2281 /* Otherwise see if some other process holds it. */
2282 if( !reserved ){
2283 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002284 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002285 if( !lrc ){
2286 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002287 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002288 if ( lrc ) {
2289 int tErrno = errno;
2290 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002291 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002292 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002293 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002294 rc = lrc;
2295 }
2296 }
2297 } else {
2298 int tErrno = errno;
2299 reserved = 1;
2300 /* someone else might have it reserved */
2301 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2302 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002303 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002304 rc = lrc;
2305 }
2306 }
2307 }
drh308c2a52010-05-14 11:30:18 +00002308 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002309
2310#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2311 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2312 rc = SQLITE_OK;
2313 reserved=1;
2314 }
2315#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2316 *pResOut = reserved;
2317 return rc;
2318}
2319
drh6b9d6dd2008-12-03 19:34:47 +00002320/*
drh308c2a52010-05-14 11:30:18 +00002321** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002322** of the following:
2323**
2324** (1) SHARED_LOCK
2325** (2) RESERVED_LOCK
2326** (3) PENDING_LOCK
2327** (4) EXCLUSIVE_LOCK
2328**
2329** Sometimes when requesting one lock state, additional lock states
2330** are inserted in between. The locking might fail on one of the later
2331** transitions leaving the lock state different from what it started but
2332** still short of its goal. The following chart shows the allowed
2333** transitions and the inserted intermediate states:
2334**
2335** UNLOCKED -> SHARED
2336** SHARED -> RESERVED
2337** SHARED -> (PENDING) -> EXCLUSIVE
2338** RESERVED -> (PENDING) -> EXCLUSIVE
2339** PENDING -> EXCLUSIVE
2340**
2341** flock() only really support EXCLUSIVE locks. We track intermediate
2342** lock states in the sqlite3_file structure, but all locks SHARED or
2343** above are really EXCLUSIVE locks and exclude all other processes from
2344** access the file.
2345**
2346** This routine will only increase a lock. Use the sqlite3OsUnlock()
2347** routine to lower a locking level.
2348*/
drh308c2a52010-05-14 11:30:18 +00002349static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002350 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002351 unixFile *pFile = (unixFile*)id;
2352
2353 assert( pFile );
2354
2355 /* if we already have a lock, it is exclusive.
2356 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002357 if (pFile->eFileLock > NO_LOCK) {
2358 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002359 return SQLITE_OK;
2360 }
2361
2362 /* grab an exclusive lock */
2363
drhff812312011-02-23 13:33:46 +00002364 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002365 int tErrno = errno;
2366 /* didn't get, must be busy */
2367 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2368 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002369 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002370 }
2371 } else {
2372 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002373 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002374 }
drh308c2a52010-05-14 11:30:18 +00002375 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2376 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002377#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2378 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2379 rc = SQLITE_BUSY;
2380 }
2381#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2382 return rc;
2383}
2384
drh6b9d6dd2008-12-03 19:34:47 +00002385
2386/*
drh308c2a52010-05-14 11:30:18 +00002387** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002388** must be either NO_LOCK or SHARED_LOCK.
2389**
2390** If the locking level of the file descriptor is already at or below
2391** the requested locking level, this routine is a no-op.
2392*/
drh308c2a52010-05-14 11:30:18 +00002393static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002394 unixFile *pFile = (unixFile*)id;
2395
2396 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002397 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2398 pFile->eFileLock, getpid()));
2399 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002400
2401 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002402 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002403 return SQLITE_OK;
2404 }
2405
2406 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002407 if (eFileLock==SHARED_LOCK) {
2408 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002409 return SQLITE_OK;
2410 }
2411
2412 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002413 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002414#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002415 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002416#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002417 return SQLITE_IOERR_UNLOCK;
2418 }else{
drh308c2a52010-05-14 11:30:18 +00002419 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002420 return SQLITE_OK;
2421 }
2422}
2423
2424/*
2425** Close a file.
2426*/
2427static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002428 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002429 if( id ){
2430 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002431 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002432 }
drh5a05be12012-10-09 18:51:44 +00002433 return rc;
drh734c9862008-11-28 15:37:20 +00002434}
2435
2436#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2437
2438/******************* End of the flock lock implementation *********************
2439******************************************************************************/
2440
2441/******************************************************************************
2442************************ Begin Named Semaphore Locking ************************
2443**
2444** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002445**
2446** Semaphore locking is like dot-lock and flock in that it really only
2447** supports EXCLUSIVE locking. Only a single process can read or write
2448** the database file at a time. This reduces potential concurrency, but
2449** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002450*/
2451#if OS_VXWORKS
2452
drh6b9d6dd2008-12-03 19:34:47 +00002453/*
2454** This routine checks if there is a RESERVED lock held on the specified
2455** file by this or any other process. If such a lock is held, set *pResOut
2456** to a non-zero value otherwise *pResOut is set to zero. The return value
2457** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2458*/
drh734c9862008-11-28 15:37:20 +00002459static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2460 int rc = SQLITE_OK;
2461 int reserved = 0;
2462 unixFile *pFile = (unixFile*)id;
2463
2464 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2465
2466 assert( pFile );
2467
2468 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002469 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002470 reserved = 1;
2471 }
2472
2473 /* Otherwise see if some other process holds it. */
2474 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002475 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002476
2477 if( sem_trywait(pSem)==-1 ){
2478 int tErrno = errno;
2479 if( EAGAIN != tErrno ){
2480 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002481 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002482 } else {
2483 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002484 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002485 }
2486 }else{
2487 /* we could have it if we want it */
2488 sem_post(pSem);
2489 }
2490 }
drh308c2a52010-05-14 11:30:18 +00002491 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002492
2493 *pResOut = reserved;
2494 return rc;
2495}
2496
drh6b9d6dd2008-12-03 19:34:47 +00002497/*
drh308c2a52010-05-14 11:30:18 +00002498** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002499** of the following:
2500**
2501** (1) SHARED_LOCK
2502** (2) RESERVED_LOCK
2503** (3) PENDING_LOCK
2504** (4) EXCLUSIVE_LOCK
2505**
2506** Sometimes when requesting one lock state, additional lock states
2507** are inserted in between. The locking might fail on one of the later
2508** transitions leaving the lock state different from what it started but
2509** still short of its goal. The following chart shows the allowed
2510** transitions and the inserted intermediate states:
2511**
2512** UNLOCKED -> SHARED
2513** SHARED -> RESERVED
2514** SHARED -> (PENDING) -> EXCLUSIVE
2515** RESERVED -> (PENDING) -> EXCLUSIVE
2516** PENDING -> EXCLUSIVE
2517**
2518** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2519** lock states in the sqlite3_file structure, but all locks SHARED or
2520** above are really EXCLUSIVE locks and exclude all other processes from
2521** access the file.
2522**
2523** This routine will only increase a lock. Use the sqlite3OsUnlock()
2524** routine to lower a locking level.
2525*/
drh308c2a52010-05-14 11:30:18 +00002526static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002527 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002528 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002529 int rc = SQLITE_OK;
2530
2531 /* if we already have a lock, it is exclusive.
2532 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002533 if (pFile->eFileLock > NO_LOCK) {
2534 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002535 rc = SQLITE_OK;
2536 goto sem_end_lock;
2537 }
2538
2539 /* lock semaphore now but bail out when already locked. */
2540 if( sem_trywait(pSem)==-1 ){
2541 rc = SQLITE_BUSY;
2542 goto sem_end_lock;
2543 }
2544
2545 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002546 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002547
2548 sem_end_lock:
2549 return rc;
2550}
2551
drh6b9d6dd2008-12-03 19:34:47 +00002552/*
drh308c2a52010-05-14 11:30:18 +00002553** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002554** must be either NO_LOCK or SHARED_LOCK.
2555**
2556** If the locking level of the file descriptor is already at or below
2557** the requested locking level, this routine is a no-op.
2558*/
drh308c2a52010-05-14 11:30:18 +00002559static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002560 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002561 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002562
2563 assert( pFile );
2564 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002565 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002566 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002567 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002568
2569 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002570 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002571 return SQLITE_OK;
2572 }
2573
2574 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002575 if (eFileLock==SHARED_LOCK) {
2576 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002577 return SQLITE_OK;
2578 }
2579
2580 /* no, really unlock. */
2581 if ( sem_post(pSem)==-1 ) {
2582 int rc, tErrno = errno;
2583 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2584 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002585 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002586 }
2587 return rc;
2588 }
drh308c2a52010-05-14 11:30:18 +00002589 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002590 return SQLITE_OK;
2591}
2592
2593/*
2594 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002595 */
drh734c9862008-11-28 15:37:20 +00002596static int semClose(sqlite3_file *id) {
2597 if( id ){
2598 unixFile *pFile = (unixFile*)id;
2599 semUnlock(id, NO_LOCK);
2600 assert( pFile );
2601 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002602 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002603 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002604 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002605 }
2606 return SQLITE_OK;
2607}
2608
2609#endif /* OS_VXWORKS */
2610/*
2611** Named semaphore locking is only available on VxWorks.
2612**
2613*************** End of the named semaphore lock implementation ****************
2614******************************************************************************/
2615
2616
2617/******************************************************************************
2618*************************** Begin AFP Locking *********************************
2619**
2620** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2621** on Apple Macintosh computers - both OS9 and OSX.
2622**
2623** Third-party implementations of AFP are available. But this code here
2624** only works on OSX.
2625*/
2626
drhd2cb50b2009-01-09 21:41:17 +00002627#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002628/*
2629** The afpLockingContext structure contains all afp lock specific state
2630*/
drhbfe66312006-10-03 17:40:40 +00002631typedef struct afpLockingContext afpLockingContext;
2632struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002633 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002634 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002635};
2636
2637struct ByteRangeLockPB2
2638{
2639 unsigned long long offset; /* offset to first byte to lock */
2640 unsigned long long length; /* nbr of bytes to lock */
2641 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2642 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2643 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2644 int fd; /* file desc to assoc this lock with */
2645};
2646
drhfd131da2007-08-07 17:13:03 +00002647#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002648
drh6b9d6dd2008-12-03 19:34:47 +00002649/*
2650** This is a utility for setting or clearing a bit-range lock on an
2651** AFP filesystem.
2652**
2653** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2654*/
2655static int afpSetLock(
2656 const char *path, /* Name of the file to be locked or unlocked */
2657 unixFile *pFile, /* Open file descriptor on path */
2658 unsigned long long offset, /* First byte to be locked */
2659 unsigned long long length, /* Number of bytes to lock */
2660 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002661){
drh6b9d6dd2008-12-03 19:34:47 +00002662 struct ByteRangeLockPB2 pb;
2663 int err;
drhbfe66312006-10-03 17:40:40 +00002664
2665 pb.unLockFlag = setLockFlag ? 0 : 1;
2666 pb.startEndFlag = 0;
2667 pb.offset = offset;
2668 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002669 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002670
drh308c2a52010-05-14 11:30:18 +00002671 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002672 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002673 offset, length));
drhbfe66312006-10-03 17:40:40 +00002674 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2675 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002676 int rc;
2677 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002678 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2679 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002680#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2681 rc = SQLITE_BUSY;
2682#else
drh734c9862008-11-28 15:37:20 +00002683 rc = sqliteErrorFromPosixError(tErrno,
2684 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002685#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002686 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002687 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002688 }
2689 return rc;
drhbfe66312006-10-03 17:40:40 +00002690 } else {
aswift5b1a2562008-08-22 00:22:35 +00002691 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002692 }
2693}
2694
drh6b9d6dd2008-12-03 19:34:47 +00002695/*
2696** This routine checks if there is a RESERVED lock held on the specified
2697** file by this or any other process. If such a lock is held, set *pResOut
2698** to a non-zero value otherwise *pResOut is set to zero. The return value
2699** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2700*/
danielk1977e339d652008-06-28 11:23:00 +00002701static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002702 int rc = SQLITE_OK;
2703 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002704 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002705 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002706
aswift5b1a2562008-08-22 00:22:35 +00002707 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2708
2709 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002710 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002711 if( context->reserved ){
2712 *pResOut = 1;
2713 return SQLITE_OK;
2714 }
drh8af6c222010-05-14 12:43:01 +00002715 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002716
2717 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002718 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002719 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002720 }
2721
2722 /* Otherwise see if some other process holds it.
2723 */
aswift5b1a2562008-08-22 00:22:35 +00002724 if( !reserved ){
2725 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002726 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002727 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002728 /* if we succeeded in taking the reserved lock, unlock it to restore
2729 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002730 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002731 } else {
2732 /* if we failed to get the lock then someone else must have it */
2733 reserved = 1;
2734 }
2735 if( IS_LOCK_ERROR(lrc) ){
2736 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002737 }
2738 }
drhbfe66312006-10-03 17:40:40 +00002739
drh7ed97b92010-01-20 13:07:21 +00002740 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002741 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002742
2743 *pResOut = reserved;
2744 return rc;
drhbfe66312006-10-03 17:40:40 +00002745}
2746
drh6b9d6dd2008-12-03 19:34:47 +00002747/*
drh308c2a52010-05-14 11:30:18 +00002748** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002749** of the following:
2750**
2751** (1) SHARED_LOCK
2752** (2) RESERVED_LOCK
2753** (3) PENDING_LOCK
2754** (4) EXCLUSIVE_LOCK
2755**
2756** Sometimes when requesting one lock state, additional lock states
2757** are inserted in between. The locking might fail on one of the later
2758** transitions leaving the lock state different from what it started but
2759** still short of its goal. The following chart shows the allowed
2760** transitions and the inserted intermediate states:
2761**
2762** UNLOCKED -> SHARED
2763** SHARED -> RESERVED
2764** SHARED -> (PENDING) -> EXCLUSIVE
2765** RESERVED -> (PENDING) -> EXCLUSIVE
2766** PENDING -> EXCLUSIVE
2767**
2768** This routine will only increase a lock. Use the sqlite3OsUnlock()
2769** routine to lower a locking level.
2770*/
drh308c2a52010-05-14 11:30:18 +00002771static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002772 int rc = SQLITE_OK;
2773 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002774 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002775 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002776
2777 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002778 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2779 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002780 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002781
drhbfe66312006-10-03 17:40:40 +00002782 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002783 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002784 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002785 */
drh308c2a52010-05-14 11:30:18 +00002786 if( pFile->eFileLock>=eFileLock ){
2787 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2788 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002789 return SQLITE_OK;
2790 }
2791
2792 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002793 ** (1) We never move from unlocked to anything higher than shared lock.
2794 ** (2) SQLite never explicitly requests a pendig lock.
2795 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002796 */
drh308c2a52010-05-14 11:30:18 +00002797 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2798 assert( eFileLock!=PENDING_LOCK );
2799 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002800
drh8af6c222010-05-14 12:43:01 +00002801 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002802 */
drh6c7d5c52008-11-21 20:32:33 +00002803 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002804 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002805
2806 /* If some thread using this PID has a lock via a different unixFile*
2807 ** handle that precludes the requested lock, return BUSY.
2808 */
drh8af6c222010-05-14 12:43:01 +00002809 if( (pFile->eFileLock!=pInode->eFileLock &&
2810 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002811 ){
2812 rc = SQLITE_BUSY;
2813 goto afp_end_lock;
2814 }
2815
2816 /* If a SHARED lock is requested, and some thread using this PID already
2817 ** has a SHARED or RESERVED lock, then increment reference counts and
2818 ** return SQLITE_OK.
2819 */
drh308c2a52010-05-14 11:30:18 +00002820 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002821 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002822 assert( eFileLock==SHARED_LOCK );
2823 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002824 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002825 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002826 pInode->nShared++;
2827 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002828 goto afp_end_lock;
2829 }
drhbfe66312006-10-03 17:40:40 +00002830
2831 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002832 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2833 ** be released.
2834 */
drh308c2a52010-05-14 11:30:18 +00002835 if( eFileLock==SHARED_LOCK
2836 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002837 ){
2838 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002839 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002840 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002841 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002842 goto afp_end_lock;
2843 }
2844 }
2845
2846 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002847 ** operating system calls for the specified lock.
2848 */
drh308c2a52010-05-14 11:30:18 +00002849 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002850 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002851 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002852
drh8af6c222010-05-14 12:43:01 +00002853 assert( pInode->nShared==0 );
2854 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002855
2856 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002857 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002858 /* note that the quality of the randomness doesn't matter that much */
2859 lk = random();
drh8af6c222010-05-14 12:43:01 +00002860 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002861 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002862 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002863 if( IS_LOCK_ERROR(lrc1) ){
2864 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002865 }
aswift5b1a2562008-08-22 00:22:35 +00002866 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002867 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002868
aswift5b1a2562008-08-22 00:22:35 +00002869 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002870 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002871 rc = lrc1;
2872 goto afp_end_lock;
2873 } else if( IS_LOCK_ERROR(lrc2) ){
2874 rc = lrc2;
2875 goto afp_end_lock;
2876 } else if( lrc1 != SQLITE_OK ) {
2877 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002878 } else {
drh308c2a52010-05-14 11:30:18 +00002879 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002880 pInode->nLock++;
2881 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002882 }
drh8af6c222010-05-14 12:43:01 +00002883 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002884 /* We are trying for an exclusive lock but another thread in this
2885 ** same process is still holding a shared lock. */
2886 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002887 }else{
2888 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2889 ** assumed that there is a SHARED or greater lock on the file
2890 ** already.
2891 */
2892 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002893 assert( 0!=pFile->eFileLock );
2894 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002895 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002896 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002897 if( !failed ){
2898 context->reserved = 1;
2899 }
drhbfe66312006-10-03 17:40:40 +00002900 }
drh308c2a52010-05-14 11:30:18 +00002901 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002902 /* Acquire an EXCLUSIVE lock */
2903
2904 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002905 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002906 */
drh6b9d6dd2008-12-03 19:34:47 +00002907 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002908 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002909 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002910 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002911 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002912 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002913 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002914 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002915 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2916 ** a critical I/O error
2917 */
2918 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2919 SQLITE_IOERR_LOCK;
2920 goto afp_end_lock;
2921 }
2922 }else{
aswift5b1a2562008-08-22 00:22:35 +00002923 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002924 }
2925 }
aswift5b1a2562008-08-22 00:22:35 +00002926 if( failed ){
2927 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002928 }
2929 }
2930
2931 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002932 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002933 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002934 }else if( eFileLock==EXCLUSIVE_LOCK ){
2935 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002936 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002937 }
2938
2939afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002940 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002941 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2942 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002943 return rc;
2944}
2945
2946/*
drh308c2a52010-05-14 11:30:18 +00002947** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002948** must be either NO_LOCK or SHARED_LOCK.
2949**
2950** If the locking level of the file descriptor is already at or below
2951** the requested locking level, this routine is a no-op.
2952*/
drh308c2a52010-05-14 11:30:18 +00002953static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002954 int rc = SQLITE_OK;
2955 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002956 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002957 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2958 int skipShared = 0;
2959#ifdef SQLITE_TEST
2960 int h = pFile->h;
2961#endif
drhbfe66312006-10-03 17:40:40 +00002962
2963 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002964 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002965 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002966 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002967
drh308c2a52010-05-14 11:30:18 +00002968 assert( eFileLock<=SHARED_LOCK );
2969 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002970 return SQLITE_OK;
2971 }
drh6c7d5c52008-11-21 20:32:33 +00002972 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002973 pInode = pFile->pInode;
2974 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002975 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002976 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002977 SimulateIOErrorBenign(1);
2978 SimulateIOError( h=(-1) )
2979 SimulateIOErrorBenign(0);
2980
drhd3d8c042012-05-29 17:02:40 +00002981#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002982 /* When reducing a lock such that other processes can start
2983 ** reading the database file again, make sure that the
2984 ** transaction counter was updated if any part of the database
2985 ** file changed. If the transaction counter is not updated,
2986 ** other connections to the same file might not realize that
2987 ** the file has changed and hence might not know to flush their
2988 ** cache. The use of a stale cache can lead to database corruption.
2989 */
2990 assert( pFile->inNormalWrite==0
2991 || pFile->dbUpdate==0
2992 || pFile->transCntrChng==1 );
2993 pFile->inNormalWrite = 0;
2994#endif
aswiftaebf4132008-11-21 00:10:35 +00002995
drh308c2a52010-05-14 11:30:18 +00002996 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002997 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002998 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002999 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003000 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003001 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3002 } else {
3003 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003004 }
3005 }
drh308c2a52010-05-14 11:30:18 +00003006 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003007 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003008 }
drh308c2a52010-05-14 11:30:18 +00003009 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003010 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3011 if( !rc ){
3012 context->reserved = 0;
3013 }
aswiftaebf4132008-11-21 00:10:35 +00003014 }
drh8af6c222010-05-14 12:43:01 +00003015 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3016 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003017 }
aswiftaebf4132008-11-21 00:10:35 +00003018 }
drh308c2a52010-05-14 11:30:18 +00003019 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003020
drh7ed97b92010-01-20 13:07:21 +00003021 /* Decrement the shared lock counter. Release the lock using an
3022 ** OS call only when all threads in this same process have released
3023 ** the lock.
3024 */
drh8af6c222010-05-14 12:43:01 +00003025 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3026 pInode->nShared--;
3027 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003028 SimulateIOErrorBenign(1);
3029 SimulateIOError( h=(-1) )
3030 SimulateIOErrorBenign(0);
3031 if( !skipShared ){
3032 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3033 }
3034 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003035 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003036 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003037 }
3038 }
3039 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003040 pInode->nLock--;
3041 assert( pInode->nLock>=0 );
3042 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003043 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003044 }
3045 }
drhbfe66312006-10-03 17:40:40 +00003046 }
drh7ed97b92010-01-20 13:07:21 +00003047
drh6c7d5c52008-11-21 20:32:33 +00003048 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003049 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003050 return rc;
3051}
3052
3053/*
drh339eb0b2008-03-07 15:34:11 +00003054** Close a file & cleanup AFP specific locking context
3055*/
danielk1977e339d652008-06-28 11:23:00 +00003056static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003057 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003058 if( id ){
3059 unixFile *pFile = (unixFile*)id;
3060 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003061 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003062 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003063 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003064 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003065 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003066 ** the last lock is cleared.
3067 */
dan08da86a2009-08-21 17:18:03 +00003068 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003069 }
danb0ac3e32010-06-16 10:55:42 +00003070 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003071 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003072 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003073 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003074 }
drh7ed97b92010-01-20 13:07:21 +00003075 return rc;
drhbfe66312006-10-03 17:40:40 +00003076}
3077
drhd2cb50b2009-01-09 21:41:17 +00003078#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003079/*
3080** The code above is the AFP lock implementation. The code is specific
3081** to MacOSX and does not work on other unix platforms. No alternative
3082** is available. If you don't compile for a mac, then the "unix-afp"
3083** VFS is not available.
3084**
3085********************* End of the AFP lock implementation **********************
3086******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003087
drh7ed97b92010-01-20 13:07:21 +00003088/******************************************************************************
3089*************************** Begin NFS Locking ********************************/
3090
3091#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3092/*
drh308c2a52010-05-14 11:30:18 +00003093 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003094 ** must be either NO_LOCK or SHARED_LOCK.
3095 **
3096 ** If the locking level of the file descriptor is already at or below
3097 ** the requested locking level, this routine is a no-op.
3098 */
drh308c2a52010-05-14 11:30:18 +00003099static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003100 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003101}
3102
3103#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3104/*
3105** The code above is the NFS lock implementation. The code is specific
3106** to MacOSX and does not work on other unix platforms. No alternative
3107** is available.
3108**
3109********************* End of the NFS lock implementation **********************
3110******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003111
3112/******************************************************************************
3113**************** Non-locking sqlite3_file methods *****************************
3114**
3115** The next division contains implementations for all methods of the
3116** sqlite3_file object other than the locking methods. The locking
3117** methods were defined in divisions above (one locking method per
3118** division). Those methods that are common to all locking modes
3119** are gather together into this division.
3120*/
drhbfe66312006-10-03 17:40:40 +00003121
3122/*
drh734c9862008-11-28 15:37:20 +00003123** Seek to the offset passed as the second argument, then read cnt
3124** bytes into pBuf. Return the number of bytes actually read.
3125**
3126** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3127** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3128** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003129** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003130** See tickets #2741 and #2681.
3131**
3132** To avoid stomping the errno value on a failed read the lastErrno value
3133** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003134*/
drh734c9862008-11-28 15:37:20 +00003135static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3136 int got;
drh58024642011-11-07 18:16:00 +00003137 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003138#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003139 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003140#endif
drh734c9862008-11-28 15:37:20 +00003141 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003142 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003143 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003144 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003145 do{
drh734c9862008-11-28 15:37:20 +00003146#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003147 got = osPread(id->h, pBuf, cnt, offset);
3148 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003149#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003150 got = osPread64(id->h, pBuf, cnt, offset);
3151 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003152#else
drh58024642011-11-07 18:16:00 +00003153 newOffset = lseek(id->h, offset, SEEK_SET);
3154 SimulateIOError( newOffset-- );
3155 if( newOffset!=offset ){
3156 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003157 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003158 }else{
drh4bf66fd2015-02-19 02:43:02 +00003159 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003160 }
3161 return -1;
drh734c9862008-11-28 15:37:20 +00003162 }
drh58024642011-11-07 18:16:00 +00003163 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003164#endif
drh58024642011-11-07 18:16:00 +00003165 if( got==cnt ) break;
3166 if( got<0 ){
3167 if( errno==EINTR ){ got = 1; continue; }
3168 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003169 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003170 break;
3171 }else if( got>0 ){
3172 cnt -= got;
3173 offset += got;
3174 prior += got;
3175 pBuf = (void*)(got + (char*)pBuf);
3176 }
3177 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003178 TIMER_END;
drh58024642011-11-07 18:16:00 +00003179 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3180 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3181 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003182}
3183
3184/*
drh734c9862008-11-28 15:37:20 +00003185** Read data from a file into a buffer. Return SQLITE_OK if all
3186** bytes were read successfully and SQLITE_IOERR if anything goes
3187** wrong.
drh339eb0b2008-03-07 15:34:11 +00003188*/
drh734c9862008-11-28 15:37:20 +00003189static int unixRead(
3190 sqlite3_file *id,
3191 void *pBuf,
3192 int amt,
3193 sqlite3_int64 offset
3194){
dan08da86a2009-08-21 17:18:03 +00003195 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003196 int got;
3197 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003198 assert( offset>=0 );
3199 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003200
dan08da86a2009-08-21 17:18:03 +00003201 /* If this is a database file (not a journal, master-journal or temp
3202 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003203#if 0
dane946c392009-08-22 11:39:46 +00003204 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003205 || offset>=PENDING_BYTE+512
3206 || offset+amt<=PENDING_BYTE
3207 );
dan7c246102010-04-12 19:00:29 +00003208#endif
drh08c6d442009-02-09 17:34:07 +00003209
drh9b4c59f2013-04-15 17:03:42 +00003210#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003211 /* Deal with as much of this read request as possible by transfering
3212 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003213 if( offset<pFile->mmapSize ){
3214 if( offset+amt <= pFile->mmapSize ){
3215 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3216 return SQLITE_OK;
3217 }else{
3218 int nCopy = pFile->mmapSize - offset;
3219 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3220 pBuf = &((u8 *)pBuf)[nCopy];
3221 amt -= nCopy;
3222 offset += nCopy;
3223 }
3224 }
drh6e0b6d52013-04-09 16:19:20 +00003225#endif
danf23da962013-03-23 21:00:41 +00003226
dan08da86a2009-08-21 17:18:03 +00003227 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003228 if( got==amt ){
3229 return SQLITE_OK;
3230 }else if( got<0 ){
3231 /* lastErrno set by seekAndRead */
3232 return SQLITE_IOERR_READ;
3233 }else{
drh4bf66fd2015-02-19 02:43:02 +00003234 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003235 /* Unread parts of the buffer must be zero-filled */
3236 memset(&((char*)pBuf)[got], 0, amt-got);
3237 return SQLITE_IOERR_SHORT_READ;
3238 }
3239}
3240
3241/*
dan47a2b4a2013-04-26 16:09:29 +00003242** Attempt to seek the file-descriptor passed as the first argument to
3243** absolute offset iOff, then attempt to write nBuf bytes of data from
3244** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3245** return the actual number of bytes written (which may be less than
3246** nBuf).
3247*/
3248static int seekAndWriteFd(
3249 int fd, /* File descriptor to write to */
3250 i64 iOff, /* File offset to begin writing at */
3251 const void *pBuf, /* Copy data from this buffer to the file */
3252 int nBuf, /* Size of buffer pBuf in bytes */
3253 int *piErrno /* OUT: Error number if error occurs */
3254){
3255 int rc = 0; /* Value returned by system call */
3256
3257 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003258 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003259 nBuf &= 0x1ffff;
3260 TIMER_START;
3261
3262#if defined(USE_PREAD)
3263 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3264#elif defined(USE_PREAD64)
3265 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3266#else
3267 do{
3268 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3269 SimulateIOError( iSeek-- );
3270
3271 if( iSeek!=iOff ){
3272 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3273 return -1;
3274 }
3275 rc = osWrite(fd, pBuf, nBuf);
3276 }while( rc<0 && errno==EINTR );
3277#endif
3278
3279 TIMER_END;
3280 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3281
3282 if( rc<0 && piErrno ) *piErrno = errno;
3283 return rc;
3284}
3285
3286
3287/*
drh734c9862008-11-28 15:37:20 +00003288** Seek to the offset in id->offset then read cnt bytes into pBuf.
3289** Return the number of bytes actually read. Update the offset.
3290**
3291** To avoid stomping the errno value on a failed write the lastErrno value
3292** is set before returning.
3293*/
3294static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003295 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003296}
3297
3298
3299/*
3300** Write data from a buffer into a file. Return SQLITE_OK on success
3301** or some other error code on failure.
3302*/
3303static int unixWrite(
3304 sqlite3_file *id,
3305 const void *pBuf,
3306 int amt,
3307 sqlite3_int64 offset
3308){
dan08da86a2009-08-21 17:18:03 +00003309 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003310 int wrote = 0;
3311 assert( id );
3312 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003313
dan08da86a2009-08-21 17:18:03 +00003314 /* If this is a database file (not a journal, master-journal or temp
3315 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003316#if 0
dane946c392009-08-22 11:39:46 +00003317 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003318 || offset>=PENDING_BYTE+512
3319 || offset+amt<=PENDING_BYTE
3320 );
dan7c246102010-04-12 19:00:29 +00003321#endif
drh08c6d442009-02-09 17:34:07 +00003322
drhd3d8c042012-05-29 17:02:40 +00003323#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003324 /* If we are doing a normal write to a database file (as opposed to
3325 ** doing a hot-journal rollback or a write to some file other than a
3326 ** normal database file) then record the fact that the database
3327 ** has changed. If the transaction counter is modified, record that
3328 ** fact too.
3329 */
dan08da86a2009-08-21 17:18:03 +00003330 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003331 pFile->dbUpdate = 1; /* The database has been modified */
3332 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003333 int rc;
drh8f941bc2009-01-14 23:03:40 +00003334 char oldCntr[4];
3335 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003336 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003337 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003338 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003339 pFile->transCntrChng = 1; /* The transaction counter has changed */
3340 }
3341 }
3342 }
3343#endif
3344
drh9b4c59f2013-04-15 17:03:42 +00003345#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003346 /* Deal with as much of this write request as possible by transfering
3347 ** data from the memory mapping using memcpy(). */
3348 if( offset<pFile->mmapSize ){
3349 if( offset+amt <= pFile->mmapSize ){
3350 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3351 return SQLITE_OK;
3352 }else{
3353 int nCopy = pFile->mmapSize - offset;
3354 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3355 pBuf = &((u8 *)pBuf)[nCopy];
3356 amt -= nCopy;
3357 offset += nCopy;
3358 }
3359 }
drh6e0b6d52013-04-09 16:19:20 +00003360#endif
danf23da962013-03-23 21:00:41 +00003361
dan08da86a2009-08-21 17:18:03 +00003362 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003363 amt -= wrote;
3364 offset += wrote;
3365 pBuf = &((char*)pBuf)[wrote];
3366 }
3367 SimulateIOError(( wrote=(-1), amt=1 ));
3368 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003369
drh734c9862008-11-28 15:37:20 +00003370 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003371 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003372 /* lastErrno set by seekAndWrite */
3373 return SQLITE_IOERR_WRITE;
3374 }else{
drh4bf66fd2015-02-19 02:43:02 +00003375 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003376 return SQLITE_FULL;
3377 }
3378 }
dan6e09d692010-07-27 18:34:15 +00003379
drh734c9862008-11-28 15:37:20 +00003380 return SQLITE_OK;
3381}
3382
3383#ifdef SQLITE_TEST
3384/*
3385** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003386** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003387*/
3388int sqlite3_sync_count = 0;
3389int sqlite3_fullsync_count = 0;
3390#endif
3391
3392/*
drh89240432009-03-25 01:06:01 +00003393** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003394** Others do no. To be safe, we will stick with the (slightly slower)
3395** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003396** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003397*/
drhf7a4a1b2015-01-10 18:02:45 +00003398#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003399# define fdatasync fsync
3400#endif
3401
3402/*
3403** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3404** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3405** only available on Mac OS X. But that could change.
3406*/
3407#ifdef F_FULLFSYNC
3408# define HAVE_FULLFSYNC 1
3409#else
3410# define HAVE_FULLFSYNC 0
3411#endif
3412
3413
3414/*
3415** The fsync() system call does not work as advertised on many
3416** unix systems. The following procedure is an attempt to make
3417** it work better.
3418**
3419** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3420** for testing when we want to run through the test suite quickly.
3421** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3422** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3423** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003424**
3425** SQLite sets the dataOnly flag if the size of the file is unchanged.
3426** The idea behind dataOnly is that it should only write the file content
3427** to disk, not the inode. We only set dataOnly if the file size is
3428** unchanged since the file size is part of the inode. However,
3429** Ted Ts'o tells us that fdatasync() will also write the inode if the
3430** file size has changed. The only real difference between fdatasync()
3431** and fsync(), Ted tells us, is that fdatasync() will not flush the
3432** inode if the mtime or owner or other inode attributes have changed.
3433** We only care about the file size, not the other file attributes, so
3434** as far as SQLite is concerned, an fdatasync() is always adequate.
3435** So, we always use fdatasync() if it is available, regardless of
3436** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003437*/
3438static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003439 int rc;
drh734c9862008-11-28 15:37:20 +00003440
3441 /* The following "ifdef/elif/else/" block has the same structure as
3442 ** the one below. It is replicated here solely to avoid cluttering
3443 ** up the real code with the UNUSED_PARAMETER() macros.
3444 */
3445#ifdef SQLITE_NO_SYNC
3446 UNUSED_PARAMETER(fd);
3447 UNUSED_PARAMETER(fullSync);
3448 UNUSED_PARAMETER(dataOnly);
3449#elif HAVE_FULLFSYNC
3450 UNUSED_PARAMETER(dataOnly);
3451#else
3452 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003453 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003454#endif
3455
3456 /* Record the number of times that we do a normal fsync() and
3457 ** FULLSYNC. This is used during testing to verify that this procedure
3458 ** gets called with the correct arguments.
3459 */
3460#ifdef SQLITE_TEST
3461 if( fullSync ) sqlite3_fullsync_count++;
3462 sqlite3_sync_count++;
3463#endif
3464
3465 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3466 ** no-op
3467 */
3468#ifdef SQLITE_NO_SYNC
3469 rc = SQLITE_OK;
3470#elif HAVE_FULLFSYNC
3471 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003472 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003473 }else{
3474 rc = 1;
3475 }
3476 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003477 ** It shouldn't be possible for fullfsync to fail on the local
3478 ** file system (on OSX), so failure indicates that FULLFSYNC
3479 ** isn't supported for this file system. So, attempt an fsync
3480 ** and (for now) ignore the overhead of a superfluous fcntl call.
3481 ** It'd be better to detect fullfsync support once and avoid
3482 ** the fcntl call every time sync is called.
3483 */
drh734c9862008-11-28 15:37:20 +00003484 if( rc ) rc = fsync(fd);
3485
drh7ed97b92010-01-20 13:07:21 +00003486#elif defined(__APPLE__)
3487 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3488 ** so currently we default to the macro that redefines fdatasync to fsync
3489 */
3490 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003491#else
drh0b647ff2009-03-21 14:41:04 +00003492 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003493#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003494 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003495 rc = fsync(fd);
3496 }
drh0b647ff2009-03-21 14:41:04 +00003497#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003498#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3499
3500 if( OS_VXWORKS && rc!= -1 ){
3501 rc = 0;
3502 }
chw97185482008-11-17 08:05:31 +00003503 return rc;
drhbfe66312006-10-03 17:40:40 +00003504}
3505
drh734c9862008-11-28 15:37:20 +00003506/*
drh0059eae2011-08-08 23:48:40 +00003507** Open a file descriptor to the directory containing file zFilename.
3508** If successful, *pFd is set to the opened file descriptor and
3509** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3510** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3511** value.
3512**
drh90315a22011-08-10 01:52:12 +00003513** The directory file descriptor is used for only one thing - to
3514** fsync() a directory to make sure file creation and deletion events
3515** are flushed to disk. Such fsyncs are not needed on newer
3516** journaling filesystems, but are required on older filesystems.
3517**
3518** This routine can be overridden using the xSetSysCall interface.
3519** The ability to override this routine was added in support of the
3520** chromium sandbox. Opening a directory is a security risk (we are
3521** told) so making it overrideable allows the chromium sandbox to
3522** replace this routine with a harmless no-op. To make this routine
3523** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3524** *pFd set to a negative number.
3525**
drh0059eae2011-08-08 23:48:40 +00003526** If SQLITE_OK is returned, the caller is responsible for closing
3527** the file descriptor *pFd using close().
3528*/
3529static int openDirectory(const char *zFilename, int *pFd){
3530 int ii;
3531 int fd = -1;
3532 char zDirname[MAX_PATHNAME+1];
3533
3534 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3535 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3536 if( ii>0 ){
3537 zDirname[ii] = '\0';
3538 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3539 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003540 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3541 }
3542 }
3543 *pFd = fd;
3544 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3545}
3546
3547/*
drh734c9862008-11-28 15:37:20 +00003548** Make sure all writes to a particular file are committed to disk.
3549**
3550** If dataOnly==0 then both the file itself and its metadata (file
3551** size, access time, etc) are synced. If dataOnly!=0 then only the
3552** file data is synced.
3553**
3554** Under Unix, also make sure that the directory entry for the file
3555** has been created by fsync-ing the directory that contains the file.
3556** If we do not do this and we encounter a power failure, the directory
3557** entry for the journal might not exist after we reboot. The next
3558** SQLite to access the file will not know that the journal exists (because
3559** the directory entry for the journal was never created) and the transaction
3560** will not roll back - possibly leading to database corruption.
3561*/
3562static int unixSync(sqlite3_file *id, int flags){
3563 int rc;
3564 unixFile *pFile = (unixFile*)id;
3565
3566 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3567 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3568
3569 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3570 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3571 || (flags&0x0F)==SQLITE_SYNC_FULL
3572 );
3573
3574 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3575 ** line is to test that doing so does not cause any problems.
3576 */
3577 SimulateDiskfullError( return SQLITE_FULL );
3578
3579 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003580 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003581 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3582 SimulateIOError( rc=1 );
3583 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003584 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003585 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003586 }
drh0059eae2011-08-08 23:48:40 +00003587
3588 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003589 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003590 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003591 */
3592 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3593 int dirfd;
3594 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003595 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003596 rc = osOpenDirectory(pFile->zPath, &dirfd);
3597 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003598 full_fsync(dirfd, 0, 0);
3599 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003600 }else if( rc==SQLITE_CANTOPEN ){
3601 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003602 }
drh0059eae2011-08-08 23:48:40 +00003603 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003604 }
3605 return rc;
3606}
3607
3608/*
3609** Truncate an open file to a specified size
3610*/
3611static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003612 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003613 int rc;
dan6e09d692010-07-27 18:34:15 +00003614 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003615 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003616
3617 /* If the user has configured a chunk-size for this file, truncate the
3618 ** file so that it consists of an integer number of chunks (i.e. the
3619 ** actual file size after the operation may be larger than the requested
3620 ** size).
3621 */
drhb8af4b72012-04-05 20:04:39 +00003622 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003623 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3624 }
3625
dan2ee53412014-09-06 16:49:40 +00003626 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003627 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003628 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003629 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003630 }else{
drhd3d8c042012-05-29 17:02:40 +00003631#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003632 /* If we are doing a normal write to a database file (as opposed to
3633 ** doing a hot-journal rollback or a write to some file other than a
3634 ** normal database file) and we truncate the file to zero length,
3635 ** that effectively updates the change counter. This might happen
3636 ** when restoring a database using the backup API from a zero-length
3637 ** source.
3638 */
dan6e09d692010-07-27 18:34:15 +00003639 if( pFile->inNormalWrite && nByte==0 ){
3640 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003641 }
danf23da962013-03-23 21:00:41 +00003642#endif
danc0003312013-03-22 17:46:11 +00003643
mistachkine98844f2013-08-24 00:59:24 +00003644#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003645 /* If the file was just truncated to a size smaller than the currently
3646 ** mapped region, reduce the effective mapping size as well. SQLite will
3647 ** use read() and write() to access data beyond this point from now on.
3648 */
3649 if( nByte<pFile->mmapSize ){
3650 pFile->mmapSize = nByte;
3651 }
mistachkine98844f2013-08-24 00:59:24 +00003652#endif
drh3313b142009-11-06 04:13:18 +00003653
drh734c9862008-11-28 15:37:20 +00003654 return SQLITE_OK;
3655 }
3656}
3657
3658/*
3659** Determine the current size of a file in bytes
3660*/
3661static int unixFileSize(sqlite3_file *id, i64 *pSize){
3662 int rc;
3663 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003664 assert( id );
3665 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003666 SimulateIOError( rc=1 );
3667 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003668 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003669 return SQLITE_IOERR_FSTAT;
3670 }
3671 *pSize = buf.st_size;
3672
drh8af6c222010-05-14 12:43:01 +00003673 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003674 ** writes a single byte into that file in order to work around a bug
3675 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3676 ** layers, we need to report this file size as zero even though it is
3677 ** really 1. Ticket #3260.
3678 */
3679 if( *pSize==1 ) *pSize = 0;
3680
3681
3682 return SQLITE_OK;
3683}
3684
drhd2cb50b2009-01-09 21:41:17 +00003685#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003686/*
3687** Handler for proxy-locking file-control verbs. Defined below in the
3688** proxying locking division.
3689*/
3690static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003691#endif
drh715ff302008-12-03 22:32:44 +00003692
dan502019c2010-07-28 14:26:17 +00003693/*
3694** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003695** file-control operation. Enlarge the database to nBytes in size
3696** (rounded up to the next chunk-size). If the database is already
3697** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003698*/
3699static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003700 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003701 i64 nSize; /* Required file size */
3702 struct stat buf; /* Used to hold return values of fstat() */
3703
drh4bf66fd2015-02-19 02:43:02 +00003704 if( osFstat(pFile->h, &buf) ){
3705 return SQLITE_IOERR_FSTAT;
3706 }
dan502019c2010-07-28 14:26:17 +00003707
3708 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3709 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003710
dan502019c2010-07-28 14:26:17 +00003711#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003712 /* The code below is handling the return value of osFallocate()
3713 ** correctly. posix_fallocate() is defined to "returns zero on success,
3714 ** or an error number on failure". See the manpage for details. */
3715 int err;
drhff812312011-02-23 13:33:46 +00003716 do{
dan661d71a2011-03-30 19:08:03 +00003717 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3718 }while( err==EINTR );
3719 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003720#else
dan592bf7f2014-12-30 19:58:31 +00003721 /* If the OS does not have posix_fallocate(), fake it. Write a
3722 ** single byte to the last byte in each block that falls entirely
3723 ** within the extended region. Then, if required, a single byte
3724 ** at offset (nSize-1), to set the size of the file correctly.
3725 ** This is a similar technique to that used by glibc on systems
3726 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003727 */
3728 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003729 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003730 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003731
dan502019c2010-07-28 14:26:17 +00003732 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003733 assert( iWrite>=buf.st_size );
3734 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3735 assert( ((iWrite+1)%nBlk)==0 );
3736 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003737 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003738 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003739 }
danef3d66c2015-01-06 21:31:47 +00003740 if( nWrite==0 || (nSize%nBlk) ){
3741 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003742 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003743 }
dan502019c2010-07-28 14:26:17 +00003744#endif
3745 }
3746 }
3747
mistachkine98844f2013-08-24 00:59:24 +00003748#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003749 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003750 int rc;
3751 if( pFile->szChunk<=0 ){
3752 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003753 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003754 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3755 }
3756 }
3757
3758 rc = unixMapfile(pFile, nByte);
3759 return rc;
3760 }
mistachkine98844f2013-08-24 00:59:24 +00003761#endif
danf23da962013-03-23 21:00:41 +00003762
dan502019c2010-07-28 14:26:17 +00003763 return SQLITE_OK;
3764}
danielk1977ad94b582007-08-20 06:44:22 +00003765
danielk1977e3026632004-06-22 11:29:02 +00003766/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003767** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003768** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3769**
3770** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3771*/
3772static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3773 if( *pArg<0 ){
3774 *pArg = (pFile->ctrlFlags & mask)!=0;
3775 }else if( (*pArg)==0 ){
3776 pFile->ctrlFlags &= ~mask;
3777 }else{
3778 pFile->ctrlFlags |= mask;
3779 }
3780}
3781
drh696b33e2012-12-06 19:01:42 +00003782/* Forward declaration */
3783static int unixGetTempname(int nBuf, char *zBuf);
3784
drhf12b3f62011-12-21 14:42:29 +00003785/*
drh9e33c2c2007-08-31 18:34:59 +00003786** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003787*/
drhcc6bb3e2007-08-31 16:11:35 +00003788static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003789 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003790 switch( op ){
3791 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003792 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003793 return SQLITE_OK;
3794 }
drh4bf66fd2015-02-19 02:43:02 +00003795 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003796 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003797 return SQLITE_OK;
3798 }
dan6e09d692010-07-27 18:34:15 +00003799 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003800 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003801 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003802 }
drh9ff27ec2010-05-19 19:26:05 +00003803 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003804 int rc;
3805 SimulateIOErrorBenign(1);
3806 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3807 SimulateIOErrorBenign(0);
3808 return rc;
drhf0b190d2011-07-26 16:03:07 +00003809 }
3810 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003811 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3812 return SQLITE_OK;
3813 }
drhcb15f352011-12-23 01:04:17 +00003814 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3815 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003816 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003817 }
drhde60fc22011-12-14 17:53:36 +00003818 case SQLITE_FCNTL_VFSNAME: {
3819 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3820 return SQLITE_OK;
3821 }
drh696b33e2012-12-06 19:01:42 +00003822 case SQLITE_FCNTL_TEMPFILENAME: {
3823 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3824 if( zTFile ){
3825 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3826 *(char**)pArg = zTFile;
3827 }
3828 return SQLITE_OK;
3829 }
drhb959a012013-12-07 12:29:22 +00003830 case SQLITE_FCNTL_HAS_MOVED: {
3831 *(int*)pArg = fileHasMoved(pFile);
3832 return SQLITE_OK;
3833 }
mistachkine98844f2013-08-24 00:59:24 +00003834#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003835 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003836 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003837 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003838 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3839 newLimit = sqlite3GlobalConfig.mxMmap;
3840 }
3841 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003842 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003843 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003844 if( pFile->mmapSize>0 ){
3845 unixUnmapfile(pFile);
3846 rc = unixMapfile(pFile, -1);
3847 }
danbcb8a862013-04-08 15:30:41 +00003848 }
drh34e258c2013-05-23 01:40:53 +00003849 return rc;
danb2d3de32013-03-14 18:34:37 +00003850 }
mistachkine98844f2013-08-24 00:59:24 +00003851#endif
drhd3d8c042012-05-29 17:02:40 +00003852#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003853 /* The pager calls this method to signal that it has done
3854 ** a rollback and that the database is therefore unchanged and
3855 ** it hence it is OK for the transaction change counter to be
3856 ** unchanged.
3857 */
3858 case SQLITE_FCNTL_DB_UNCHANGED: {
3859 ((unixFile*)id)->dbUpdate = 0;
3860 return SQLITE_OK;
3861 }
3862#endif
drhd2cb50b2009-01-09 21:41:17 +00003863#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003864 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3865 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003866 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003867 }
drhd2cb50b2009-01-09 21:41:17 +00003868#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003869 }
drh0b52b7d2011-01-26 19:46:22 +00003870 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003871}
3872
3873/*
danielk1977a3d4c882007-03-23 10:08:38 +00003874** Return the sector size in bytes of the underlying block device for
3875** the specified file. This is almost always 512 bytes, but may be
3876** larger for some devices.
3877**
3878** SQLite code assumes this function cannot fail. It also assumes that
3879** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003880** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003881** same for both.
3882*/
drh537dddf2012-10-26 13:46:24 +00003883#ifndef __QNXNTO__
3884static int unixSectorSize(sqlite3_file *NotUsed){
3885 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003886 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003887}
drh537dddf2012-10-26 13:46:24 +00003888#endif
3889
3890/*
3891** The following version of unixSectorSize() is optimized for QNX.
3892*/
3893#ifdef __QNXNTO__
3894#include <sys/dcmd_blk.h>
3895#include <sys/statvfs.h>
3896static int unixSectorSize(sqlite3_file *id){
3897 unixFile *pFile = (unixFile*)id;
3898 if( pFile->sectorSize == 0 ){
3899 struct statvfs fsInfo;
3900
3901 /* Set defaults for non-supported filesystems */
3902 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3903 pFile->deviceCharacteristics = 0;
3904 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3905 return pFile->sectorSize;
3906 }
3907
3908 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3909 pFile->sectorSize = fsInfo.f_bsize;
3910 pFile->deviceCharacteristics =
3911 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3912 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3913 ** the write succeeds */
3914 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3915 ** so it is ordered */
3916 0;
3917 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3918 pFile->sectorSize = fsInfo.f_bsize;
3919 pFile->deviceCharacteristics =
3920 /* etfs cluster size writes are atomic */
3921 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3922 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3923 ** the write succeeds */
3924 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3925 ** so it is ordered */
3926 0;
3927 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3928 pFile->sectorSize = fsInfo.f_bsize;
3929 pFile->deviceCharacteristics =
3930 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3931 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3932 ** the write succeeds */
3933 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3934 ** so it is ordered */
3935 0;
3936 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3937 pFile->sectorSize = fsInfo.f_bsize;
3938 pFile->deviceCharacteristics =
3939 /* full bitset of atomics from max sector size and smaller */
3940 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3941 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3942 ** so it is ordered */
3943 0;
3944 }else if( strstr(fsInfo.f_basetype, "dos") ){
3945 pFile->sectorSize = fsInfo.f_bsize;
3946 pFile->deviceCharacteristics =
3947 /* full bitset of atomics from max sector size and smaller */
3948 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3949 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3950 ** so it is ordered */
3951 0;
3952 }else{
3953 pFile->deviceCharacteristics =
3954 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3955 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3956 ** the write succeeds */
3957 0;
3958 }
3959 }
3960 /* Last chance verification. If the sector size isn't a multiple of 512
3961 ** then it isn't valid.*/
3962 if( pFile->sectorSize % 512 != 0 ){
3963 pFile->deviceCharacteristics = 0;
3964 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3965 }
3966 return pFile->sectorSize;
3967}
3968#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003969
danielk197790949c22007-08-17 16:50:38 +00003970/*
drhf12b3f62011-12-21 14:42:29 +00003971** Return the device characteristics for the file.
3972**
drhcb15f352011-12-23 01:04:17 +00003973** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003974** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003975** file system does not always provide powersafe overwrites. (In other
3976** words, after a power-loss event, parts of the file that were never
3977** written might end up being altered.) However, non-PSOW behavior is very,
3978** very rare. And asserting PSOW makes a large reduction in the amount
3979** of required I/O for journaling, since a lot of padding is eliminated.
3980** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3981** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003982*/
drhf12b3f62011-12-21 14:42:29 +00003983static int unixDeviceCharacteristics(sqlite3_file *id){
3984 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003985 int rc = 0;
3986#ifdef __QNXNTO__
3987 if( p->sectorSize==0 ) unixSectorSize(id);
3988 rc = p->deviceCharacteristics;
3989#endif
drhcb15f352011-12-23 01:04:17 +00003990 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003991 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003992 }
drh537dddf2012-10-26 13:46:24 +00003993 return rc;
danielk197762079062007-08-15 17:08:46 +00003994}
3995
dan702eec12014-06-23 10:04:58 +00003996#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003997
dan702eec12014-06-23 10:04:58 +00003998/*
3999** Return the system page size.
4000**
4001** This function should not be called directly by other code in this file.
4002** Instead, it should be called via macro osGetpagesize().
4003*/
4004static int unixGetpagesize(void){
4005#if defined(_BSD_SOURCE)
4006 return getpagesize();
4007#else
4008 return (int)sysconf(_SC_PAGESIZE);
4009#endif
4010}
4011
4012#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4013
4014#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004015
4016/*
drhd91c68f2010-05-14 14:52:25 +00004017** Object used to represent an shared memory buffer.
4018**
4019** When multiple threads all reference the same wal-index, each thread
4020** has its own unixShm object, but they all point to a single instance
4021** of this unixShmNode object. In other words, each wal-index is opened
4022** only once per process.
4023**
4024** Each unixShmNode object is connected to a single unixInodeInfo object.
4025** We could coalesce this object into unixInodeInfo, but that would mean
4026** every open file that does not use shared memory (in other words, most
4027** open files) would have to carry around this extra information. So
4028** the unixInodeInfo object contains a pointer to this unixShmNode object
4029** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004030**
4031** unixMutexHeld() must be true when creating or destroying
4032** this object or while reading or writing the following fields:
4033**
4034** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004035**
4036** The following fields are read-only after the object is created:
4037**
4038** fid
4039** zFilename
4040**
drhd91c68f2010-05-14 14:52:25 +00004041** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004042** unixMutexHeld() is true when reading or writing any other field
4043** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004044*/
drhd91c68f2010-05-14 14:52:25 +00004045struct unixShmNode {
4046 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004047 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004048 char *zFilename; /* Name of the mmapped file */
4049 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004050 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004051 u16 nRegion; /* Size of array apRegion */
4052 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004053 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004054 int nRef; /* Number of unixShm objects pointing to this */
4055 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004056#ifdef SQLITE_DEBUG
4057 u8 exclMask; /* Mask of exclusive locks held */
4058 u8 sharedMask; /* Mask of shared locks held */
4059 u8 nextShmId; /* Next available unixShm.id value */
4060#endif
4061};
4062
4063/*
drhd9e5c4f2010-05-12 18:01:39 +00004064** Structure used internally by this VFS to record the state of an
4065** open shared memory connection.
4066**
drhd91c68f2010-05-14 14:52:25 +00004067** The following fields are initialized when this object is created and
4068** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004069**
drhd91c68f2010-05-14 14:52:25 +00004070** unixShm.pFile
4071** unixShm.id
4072**
4073** All other fields are read/write. The unixShm.pFile->mutex must be held
4074** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004075*/
4076struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004077 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4078 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004079 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004080 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004081 u16 sharedMask; /* Mask of shared locks held */
4082 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004083};
4084
4085/*
drhd9e5c4f2010-05-12 18:01:39 +00004086** Constants used for locking
4087*/
drhbd9676c2010-06-23 17:58:38 +00004088#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004089#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004090
drhd9e5c4f2010-05-12 18:01:39 +00004091/*
drh73b64e42010-05-30 19:55:15 +00004092** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004093**
4094** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4095** otherwise.
4096*/
4097static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004098 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4099 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004100 int ofst, /* First byte of the locking range */
4101 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004102){
4103 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004104 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004105
drhd91c68f2010-05-14 14:52:25 +00004106 /* Access to the unixShmNode object is serialized by the caller */
4107 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004108
drh73b64e42010-05-30 19:55:15 +00004109 /* Shared locks never span more than one byte */
4110 assert( n==1 || lockType!=F_RDLCK );
4111
4112 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004113 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004114
drh3cb93392011-03-12 18:10:44 +00004115 if( pShmNode->h>=0 ){
4116 /* Initialize the locking parameters */
4117 memset(&f, 0, sizeof(f));
4118 f.l_type = lockType;
4119 f.l_whence = SEEK_SET;
4120 f.l_start = ofst;
4121 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004122
drh3cb93392011-03-12 18:10:44 +00004123 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4124 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4125 }
drhd9e5c4f2010-05-12 18:01:39 +00004126
4127 /* Update the global lock state and do debug tracing */
4128#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004129 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004130 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004131 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004132 if( rc==SQLITE_OK ){
4133 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004134 OSTRACE(("unlock %d ok", ofst));
4135 pShmNode->exclMask &= ~mask;
4136 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004137 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004138 OSTRACE(("read-lock %d ok", ofst));
4139 pShmNode->exclMask &= ~mask;
4140 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004141 }else{
4142 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004143 OSTRACE(("write-lock %d ok", ofst));
4144 pShmNode->exclMask |= mask;
4145 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004146 }
4147 }else{
4148 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004149 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004150 }else if( lockType==F_RDLCK ){
4151 OSTRACE(("read-lock failed"));
4152 }else{
4153 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004154 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004155 }
4156 }
drh20e1f082010-05-31 16:10:12 +00004157 OSTRACE((" - afterwards %03x,%03x\n",
4158 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004159 }
drhd9e5c4f2010-05-12 18:01:39 +00004160#endif
4161
4162 return rc;
4163}
4164
dan781e34c2014-03-20 08:59:47 +00004165/*
dan781e34c2014-03-20 08:59:47 +00004166** Return the minimum number of 32KB shm regions that should be mapped at
4167** a time, assuming that each mapping must be an integer multiple of the
4168** current system page-size.
4169**
4170** Usually, this is 1. The exception seems to be systems that are configured
4171** to use 64KB pages - in this case each mapping must cover at least two
4172** shm regions.
4173*/
4174static int unixShmRegionPerMap(void){
4175 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004176 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004177 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4178 if( pgsz<shmsz ) return 1;
4179 return pgsz/shmsz;
4180}
drhd9e5c4f2010-05-12 18:01:39 +00004181
4182/*
drhd91c68f2010-05-14 14:52:25 +00004183** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004184**
4185** This is not a VFS shared-memory method; it is a utility function called
4186** by VFS shared-memory methods.
4187*/
drhd91c68f2010-05-14 14:52:25 +00004188static void unixShmPurge(unixFile *pFd){
4189 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004190 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004191 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004192 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004193 int i;
drhd91c68f2010-05-14 14:52:25 +00004194 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004195 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004196 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004197 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004198 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004199 }else{
4200 sqlite3_free(p->apRegion[i]);
4201 }
dan13a3cb82010-06-11 19:04:21 +00004202 }
dan18801912010-06-14 14:07:50 +00004203 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004204 if( p->h>=0 ){
4205 robust_close(pFd, p->h, __LINE__);
4206 p->h = -1;
4207 }
drhd91c68f2010-05-14 14:52:25 +00004208 p->pInode->pShmNode = 0;
4209 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004210 }
4211}
4212
4213/*
danda9fe0c2010-07-13 18:44:03 +00004214** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004215** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004216**
drh7234c6d2010-06-19 15:10:09 +00004217** The file used to implement shared-memory is in the same directory
4218** as the open database file and has the same name as the open database
4219** file with the "-shm" suffix added. For example, if the database file
4220** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004221** for shared memory will be called "/home/user1/config.db-shm".
4222**
4223** Another approach to is to use files in /dev/shm or /dev/tmp or an
4224** some other tmpfs mount. But if a file in a different directory
4225** from the database file is used, then differing access permissions
4226** or a chroot() might cause two different processes on the same
4227** database to end up using different files for shared memory -
4228** meaning that their memory would not really be shared - resulting
4229** in database corruption. Nevertheless, this tmpfs file usage
4230** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4231** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4232** option results in an incompatible build of SQLite; builds of SQLite
4233** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4234** same database file at the same time, database corruption will likely
4235** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4236** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004237**
4238** When opening a new shared-memory file, if no other instances of that
4239** file are currently open, in this process or in other processes, then
4240** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004241**
4242** If the original database file (pDbFd) is using the "unix-excl" VFS
4243** that means that an exclusive lock is held on the database file and
4244** that no other processes are able to read or write the database. In
4245** that case, we do not really need shared memory. No shared memory
4246** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004247*/
danda9fe0c2010-07-13 18:44:03 +00004248static int unixOpenSharedMemory(unixFile *pDbFd){
4249 struct unixShm *p = 0; /* The connection to be opened */
4250 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4251 int rc; /* Result code */
4252 unixInodeInfo *pInode; /* The inode of fd */
4253 char *zShmFilename; /* Name of the file used for SHM */
4254 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004255
danda9fe0c2010-07-13 18:44:03 +00004256 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004257 p = sqlite3_malloc( sizeof(*p) );
4258 if( p==0 ) return SQLITE_NOMEM;
4259 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004260 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004261
danda9fe0c2010-07-13 18:44:03 +00004262 /* Check to see if a unixShmNode object already exists. Reuse an existing
4263 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004264 */
4265 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004266 pInode = pDbFd->pInode;
4267 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004268 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004269 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004270#ifndef SQLITE_SHM_DIRECTORY
4271 const char *zBasePath = pDbFd->zPath;
4272#endif
danddb0ac42010-07-14 14:48:58 +00004273
4274 /* Call fstat() to figure out the permissions on the database file. If
4275 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004276 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004277 */
drh3cb93392011-03-12 18:10:44 +00004278 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004279 rc = SQLITE_IOERR_FSTAT;
4280 goto shm_open_err;
4281 }
4282
drha4ced192010-07-15 18:32:40 +00004283#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004284 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004285#else
drh4bf66fd2015-02-19 02:43:02 +00004286 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004287#endif
drh7234c6d2010-06-19 15:10:09 +00004288 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004289 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004290 rc = SQLITE_NOMEM;
4291 goto shm_open_err;
4292 }
drh9cb5a0d2012-01-05 21:19:54 +00004293 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004294 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004295#ifdef SQLITE_SHM_DIRECTORY
4296 sqlite3_snprintf(nShmFilename, zShmFilename,
4297 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4298 (u32)sStat.st_ino, (u32)sStat.st_dev);
4299#else
drh4bf66fd2015-02-19 02:43:02 +00004300 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004301 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004302#endif
drhd91c68f2010-05-14 14:52:25 +00004303 pShmNode->h = -1;
4304 pDbFd->pInode->pShmNode = pShmNode;
4305 pShmNode->pInode = pDbFd->pInode;
4306 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4307 if( pShmNode->mutex==0 ){
4308 rc = SQLITE_NOMEM;
4309 goto shm_open_err;
4310 }
drhd9e5c4f2010-05-12 18:01:39 +00004311
drh3cb93392011-03-12 18:10:44 +00004312 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004313 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004314 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004315 openFlags = O_RDONLY;
4316 pShmNode->isReadonly = 1;
4317 }
4318 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004319 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004320 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4321 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004322 }
drhac7c3ac2012-02-11 19:23:48 +00004323
4324 /* If this process is running as root, make sure that the SHM file
4325 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004326 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004327 */
drhed466822012-05-31 13:10:49 +00004328 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004329
4330 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004331 ** If not, truncate the file to zero length.
4332 */
4333 rc = SQLITE_OK;
4334 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4335 if( robust_ftruncate(pShmNode->h, 0) ){
4336 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004337 }
4338 }
drh66dfec8b2011-06-01 20:01:49 +00004339 if( rc==SQLITE_OK ){
4340 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4341 }
4342 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004343 }
drhd9e5c4f2010-05-12 18:01:39 +00004344 }
4345
drhd91c68f2010-05-14 14:52:25 +00004346 /* Make the new connection a child of the unixShmNode */
4347 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004348#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004349 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004350#endif
drhd91c68f2010-05-14 14:52:25 +00004351 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004352 pDbFd->pShm = p;
4353 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004354
4355 /* The reference count on pShmNode has already been incremented under
4356 ** the cover of the unixEnterMutex() mutex and the pointer from the
4357 ** new (struct unixShm) object to the pShmNode has been set. All that is
4358 ** left to do is to link the new object into the linked list starting
4359 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4360 ** mutex.
4361 */
4362 sqlite3_mutex_enter(pShmNode->mutex);
4363 p->pNext = pShmNode->pFirst;
4364 pShmNode->pFirst = p;
4365 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004366 return SQLITE_OK;
4367
4368 /* Jump here on any error */
4369shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004370 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004371 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004372 unixLeaveMutex();
4373 return rc;
4374}
4375
4376/*
danda9fe0c2010-07-13 18:44:03 +00004377** This function is called to obtain a pointer to region iRegion of the
4378** shared-memory associated with the database file fd. Shared-memory regions
4379** are numbered starting from zero. Each shared-memory region is szRegion
4380** bytes in size.
4381**
4382** If an error occurs, an error code is returned and *pp is set to NULL.
4383**
4384** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4385** region has not been allocated (by any client, including one running in a
4386** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4387** bExtend is non-zero and the requested shared-memory region has not yet
4388** been allocated, it is allocated by this function.
4389**
4390** If the shared-memory region has already been allocated or is allocated by
4391** this call as described above, then it is mapped into this processes
4392** address space (if it is not already), *pp is set to point to the mapped
4393** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004394*/
danda9fe0c2010-07-13 18:44:03 +00004395static int unixShmMap(
4396 sqlite3_file *fd, /* Handle open on database file */
4397 int iRegion, /* Region to retrieve */
4398 int szRegion, /* Size of regions */
4399 int bExtend, /* True to extend file if necessary */
4400 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004401){
danda9fe0c2010-07-13 18:44:03 +00004402 unixFile *pDbFd = (unixFile*)fd;
4403 unixShm *p;
4404 unixShmNode *pShmNode;
4405 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004406 int nShmPerMap = unixShmRegionPerMap();
4407 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004408
danda9fe0c2010-07-13 18:44:03 +00004409 /* If the shared-memory file has not yet been opened, open it now. */
4410 if( pDbFd->pShm==0 ){
4411 rc = unixOpenSharedMemory(pDbFd);
4412 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004413 }
drhd9e5c4f2010-05-12 18:01:39 +00004414
danda9fe0c2010-07-13 18:44:03 +00004415 p = pDbFd->pShm;
4416 pShmNode = p->pShmNode;
4417 sqlite3_mutex_enter(pShmNode->mutex);
4418 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004419 assert( pShmNode->pInode==pDbFd->pInode );
4420 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4421 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004422
dan781e34c2014-03-20 08:59:47 +00004423 /* Minimum number of regions required to be mapped. */
4424 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4425
4426 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004427 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004428 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004429 struct stat sStat; /* Used by fstat() */
4430
4431 pShmNode->szRegion = szRegion;
4432
drh3cb93392011-03-12 18:10:44 +00004433 if( pShmNode->h>=0 ){
4434 /* The requested region is not mapped into this processes address space.
4435 ** Check to see if it has been allocated (i.e. if the wal-index file is
4436 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004437 */
drh3cb93392011-03-12 18:10:44 +00004438 if( osFstat(pShmNode->h, &sStat) ){
4439 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004440 goto shmpage_out;
4441 }
drh3cb93392011-03-12 18:10:44 +00004442
4443 if( sStat.st_size<nByte ){
4444 /* The requested memory region does not exist. If bExtend is set to
4445 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004446 */
dan47a2b4a2013-04-26 16:09:29 +00004447 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004448 goto shmpage_out;
4449 }
dan47a2b4a2013-04-26 16:09:29 +00004450
4451 /* Alternatively, if bExtend is true, extend the file. Do this by
4452 ** writing a single byte to the end of each (OS) page being
4453 ** allocated or extended. Technically, we need only write to the
4454 ** last page in order to extend the file. But writing to all new
4455 ** pages forces the OS to allocate them immediately, which reduces
4456 ** the chances of SIGBUS while accessing the mapped region later on.
4457 */
4458 else{
4459 static const int pgsz = 4096;
4460 int iPg;
4461
4462 /* Write to the last byte of each newly allocated or extended page */
4463 assert( (nByte % pgsz)==0 );
4464 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4465 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4466 const char *zFile = pShmNode->zFilename;
4467 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4468 goto shmpage_out;
4469 }
4470 }
drh3cb93392011-03-12 18:10:44 +00004471 }
4472 }
danda9fe0c2010-07-13 18:44:03 +00004473 }
4474
4475 /* Map the requested memory region into this processes address space. */
4476 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004477 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004478 );
4479 if( !apNew ){
4480 rc = SQLITE_IOERR_NOMEM;
4481 goto shmpage_out;
4482 }
4483 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004484 while( pShmNode->nRegion<nReqRegion ){
4485 int nMap = szRegion*nShmPerMap;
4486 int i;
drh3cb93392011-03-12 18:10:44 +00004487 void *pMem;
4488 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004489 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004490 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004491 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004492 );
4493 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004494 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004495 goto shmpage_out;
4496 }
4497 }else{
4498 pMem = sqlite3_malloc(szRegion);
4499 if( pMem==0 ){
4500 rc = SQLITE_NOMEM;
4501 goto shmpage_out;
4502 }
4503 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004504 }
dan781e34c2014-03-20 08:59:47 +00004505
4506 for(i=0; i<nShmPerMap; i++){
4507 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4508 }
4509 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004510 }
4511 }
4512
4513shmpage_out:
4514 if( pShmNode->nRegion>iRegion ){
4515 *pp = pShmNode->apRegion[iRegion];
4516 }else{
4517 *pp = 0;
4518 }
drh66dfec8b2011-06-01 20:01:49 +00004519 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004520 sqlite3_mutex_leave(pShmNode->mutex);
4521 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004522}
4523
4524/*
drhd9e5c4f2010-05-12 18:01:39 +00004525** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004526**
4527** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4528** different here than in posix. In xShmLock(), one can go from unlocked
4529** to shared and back or from unlocked to exclusive and back. But one may
4530** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004531*/
4532static int unixShmLock(
4533 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004534 int ofst, /* First lock to acquire or release */
4535 int n, /* Number of locks to acquire or release */
4536 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004537){
drh73b64e42010-05-30 19:55:15 +00004538 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4539 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4540 unixShm *pX; /* For looping over all siblings */
4541 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4542 int rc = SQLITE_OK; /* Result code */
4543 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004544
drhd91c68f2010-05-14 14:52:25 +00004545 assert( pShmNode==pDbFd->pInode->pShmNode );
4546 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004547 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004548 assert( n>=1 );
4549 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4550 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4551 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4552 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4553 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004554 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4555 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004556
drhc99597c2010-05-31 01:41:15 +00004557 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004558 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004559 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004560 if( flags & SQLITE_SHM_UNLOCK ){
4561 u16 allMask = 0; /* Mask of locks held by siblings */
4562
4563 /* See if any siblings hold this same lock */
4564 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4565 if( pX==p ) continue;
4566 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4567 allMask |= pX->sharedMask;
4568 }
4569
4570 /* Unlock the system-level locks */
4571 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004572 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004573 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004574 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004575 }
drh73b64e42010-05-30 19:55:15 +00004576
4577 /* Undo the local locks */
4578 if( rc==SQLITE_OK ){
4579 p->exclMask &= ~mask;
4580 p->sharedMask &= ~mask;
4581 }
4582 }else if( flags & SQLITE_SHM_SHARED ){
4583 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4584
4585 /* Find out which shared locks are already held by sibling connections.
4586 ** If any sibling already holds an exclusive lock, go ahead and return
4587 ** SQLITE_BUSY.
4588 */
4589 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004590 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004591 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004592 break;
4593 }
4594 allShared |= pX->sharedMask;
4595 }
4596
4597 /* Get shared locks at the system level, if necessary */
4598 if( rc==SQLITE_OK ){
4599 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004600 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004601 }else{
drh73b64e42010-05-30 19:55:15 +00004602 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004603 }
drhd9e5c4f2010-05-12 18:01:39 +00004604 }
drh73b64e42010-05-30 19:55:15 +00004605
4606 /* Get the local shared locks */
4607 if( rc==SQLITE_OK ){
4608 p->sharedMask |= mask;
4609 }
4610 }else{
4611 /* Make sure no sibling connections hold locks that will block this
4612 ** lock. If any do, return SQLITE_BUSY right away.
4613 */
4614 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004615 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4616 rc = SQLITE_BUSY;
4617 break;
4618 }
4619 }
4620
4621 /* Get the exclusive locks at the system level. Then if successful
4622 ** also mark the local connection as being locked.
4623 */
4624 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004625 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004626 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004627 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004628 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004629 }
drhd9e5c4f2010-05-12 18:01:39 +00004630 }
4631 }
drhd91c68f2010-05-14 14:52:25 +00004632 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004633 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4634 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004635 return rc;
4636}
4637
drh286a2882010-05-20 23:51:06 +00004638/*
4639** Implement a memory barrier or memory fence on shared memory.
4640**
4641** All loads and stores begun before the barrier must complete before
4642** any load or store begun after the barrier.
4643*/
4644static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004645 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004646){
drhff828942010-06-26 21:34:06 +00004647 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004648 unixEnterMutex();
4649 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004650}
4651
dan18801912010-06-14 14:07:50 +00004652/*
danda9fe0c2010-07-13 18:44:03 +00004653** Close a connection to shared-memory. Delete the underlying
4654** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004655**
4656** If there is no shared memory associated with the connection then this
4657** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004658*/
danda9fe0c2010-07-13 18:44:03 +00004659static int unixShmUnmap(
4660 sqlite3_file *fd, /* The underlying database file */
4661 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004662){
danda9fe0c2010-07-13 18:44:03 +00004663 unixShm *p; /* The connection to be closed */
4664 unixShmNode *pShmNode; /* The underlying shared-memory file */
4665 unixShm **pp; /* For looping over sibling connections */
4666 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004667
danda9fe0c2010-07-13 18:44:03 +00004668 pDbFd = (unixFile*)fd;
4669 p = pDbFd->pShm;
4670 if( p==0 ) return SQLITE_OK;
4671 pShmNode = p->pShmNode;
4672
4673 assert( pShmNode==pDbFd->pInode->pShmNode );
4674 assert( pShmNode->pInode==pDbFd->pInode );
4675
4676 /* Remove connection p from the set of connections associated
4677 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004678 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004679 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4680 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004681
danda9fe0c2010-07-13 18:44:03 +00004682 /* Free the connection p */
4683 sqlite3_free(p);
4684 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004685 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004686
4687 /* If pShmNode->nRef has reached 0, then close the underlying
4688 ** shared-memory file, too */
4689 unixEnterMutex();
4690 assert( pShmNode->nRef>0 );
4691 pShmNode->nRef--;
4692 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004693 if( deleteFlag && pShmNode->h>=0 ){
4694 osUnlink(pShmNode->zFilename);
4695 }
danda9fe0c2010-07-13 18:44:03 +00004696 unixShmPurge(pDbFd);
4697 }
4698 unixLeaveMutex();
4699
4700 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004701}
drh286a2882010-05-20 23:51:06 +00004702
danda9fe0c2010-07-13 18:44:03 +00004703
drhd9e5c4f2010-05-12 18:01:39 +00004704#else
drh6b017cc2010-06-14 18:01:46 +00004705# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004706# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004707# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004708# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004709#endif /* #ifndef SQLITE_OMIT_WAL */
4710
mistachkine98844f2013-08-24 00:59:24 +00004711#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004712/*
danaef49d72013-03-25 16:28:54 +00004713** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004714*/
danf23da962013-03-23 21:00:41 +00004715static void unixUnmapfile(unixFile *pFd){
4716 assert( pFd->nFetchOut==0 );
4717 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004718 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004719 pFd->pMapRegion = 0;
4720 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004721 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004722 }
4723}
dan5d8a1372013-03-19 19:28:06 +00004724
danaef49d72013-03-25 16:28:54 +00004725/*
dane6ecd662013-04-01 17:56:59 +00004726** Attempt to set the size of the memory mapping maintained by file
4727** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4728**
4729** If successful, this function sets the following variables:
4730**
4731** unixFile.pMapRegion
4732** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004733** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004734**
4735** If unsuccessful, an error message is logged via sqlite3_log() and
4736** the three variables above are zeroed. In this case SQLite should
4737** continue accessing the database using the xRead() and xWrite()
4738** methods.
4739*/
4740static void unixRemapfile(
4741 unixFile *pFd, /* File descriptor object */
4742 i64 nNew /* Required mapping size */
4743){
dan4ff7bc42013-04-02 12:04:09 +00004744 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004745 int h = pFd->h; /* File descriptor open on db file */
4746 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004747 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004748 u8 *pNew = 0; /* Location of new mapping */
4749 int flags = PROT_READ; /* Flags to pass to mmap() */
4750
4751 assert( pFd->nFetchOut==0 );
4752 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004753 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004754 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004755 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004756 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004757
4758 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4759
4760 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004761#if HAVE_MREMAP
4762 i64 nReuse = pFd->mmapSize;
4763#else
danbc760632014-03-20 09:42:09 +00004764 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004765 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004766#endif
dane6ecd662013-04-01 17:56:59 +00004767 u8 *pReq = &pOrig[nReuse];
4768
4769 /* Unmap any pages of the existing mapping that cannot be reused. */
4770 if( nReuse!=nOrig ){
4771 osMunmap(pReq, nOrig-nReuse);
4772 }
4773
4774#if HAVE_MREMAP
4775 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004776 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004777#else
4778 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4779 if( pNew!=MAP_FAILED ){
4780 if( pNew!=pReq ){
4781 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004782 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004783 }else{
4784 pNew = pOrig;
4785 }
4786 }
4787#endif
4788
dan48ccef82013-04-02 20:55:01 +00004789 /* The attempt to extend the existing mapping failed. Free it. */
4790 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004791 osMunmap(pOrig, nReuse);
4792 }
4793 }
4794
4795 /* If pNew is still NULL, try to create an entirely new mapping. */
4796 if( pNew==0 ){
4797 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004798 }
4799
dan4ff7bc42013-04-02 12:04:09 +00004800 if( pNew==MAP_FAILED ){
4801 pNew = 0;
4802 nNew = 0;
4803 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4804
4805 /* If the mmap() above failed, assume that all subsequent mmap() calls
4806 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4807 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004808 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004809 }
dane6ecd662013-04-01 17:56:59 +00004810 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004811 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004812}
4813
4814/*
danaef49d72013-03-25 16:28:54 +00004815** Memory map or remap the file opened by file-descriptor pFd (if the file
4816** is already mapped, the existing mapping is replaced by the new). Or, if
4817** there already exists a mapping for this file, and there are still
4818** outstanding xFetch() references to it, this function is a no-op.
4819**
4820** If parameter nByte is non-negative, then it is the requested size of
4821** the mapping to create. Otherwise, if nByte is less than zero, then the
4822** requested size is the size of the file on disk. The actual size of the
4823** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004824** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004825**
4826** SQLITE_OK is returned if no error occurs (even if the mapping is not
4827** recreated as a result of outstanding references) or an SQLite error
4828** code otherwise.
4829*/
danf23da962013-03-23 21:00:41 +00004830static int unixMapfile(unixFile *pFd, i64 nByte){
4831 i64 nMap = nByte;
4832 int rc;
daneb97b292013-03-20 14:26:59 +00004833
danf23da962013-03-23 21:00:41 +00004834 assert( nMap>=0 || pFd->nFetchOut==0 );
4835 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4836
4837 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004838 struct stat statbuf; /* Low-level file information */
4839 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004840 if( rc!=SQLITE_OK ){
4841 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004842 }
drh3044b512014-06-16 16:41:52 +00004843 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004844 }
drh9b4c59f2013-04-15 17:03:42 +00004845 if( nMap>pFd->mmapSizeMax ){
4846 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004847 }
4848
danf23da962013-03-23 21:00:41 +00004849 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004850 if( nMap>0 ){
4851 unixRemapfile(pFd, nMap);
4852 }else{
danb7e3a322013-03-25 20:30:13 +00004853 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004854 }
4855 }
4856
danf23da962013-03-23 21:00:41 +00004857 return SQLITE_OK;
4858}
mistachkine98844f2013-08-24 00:59:24 +00004859#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004860
danaef49d72013-03-25 16:28:54 +00004861/*
4862** If possible, return a pointer to a mapping of file fd starting at offset
4863** iOff. The mapping must be valid for at least nAmt bytes.
4864**
4865** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4866** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4867** Finally, if an error does occur, return an SQLite error code. The final
4868** value of *pp is undefined in this case.
4869**
4870** If this function does return a pointer, the caller must eventually
4871** release the reference by calling unixUnfetch().
4872*/
danf23da962013-03-23 21:00:41 +00004873static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004874#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004875 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004876#endif
danf23da962013-03-23 21:00:41 +00004877 *pp = 0;
4878
drh9b4c59f2013-04-15 17:03:42 +00004879#if SQLITE_MAX_MMAP_SIZE>0
4880 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004881 if( pFd->pMapRegion==0 ){
4882 int rc = unixMapfile(pFd, -1);
4883 if( rc!=SQLITE_OK ) return rc;
4884 }
4885 if( pFd->mmapSize >= iOff+nAmt ){
4886 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4887 pFd->nFetchOut++;
4888 }
4889 }
drh6e0b6d52013-04-09 16:19:20 +00004890#endif
danf23da962013-03-23 21:00:41 +00004891 return SQLITE_OK;
4892}
4893
danaef49d72013-03-25 16:28:54 +00004894/*
dandf737fe2013-03-25 17:00:24 +00004895** If the third argument is non-NULL, then this function releases a
4896** reference obtained by an earlier call to unixFetch(). The second
4897** argument passed to this function must be the same as the corresponding
4898** argument that was passed to the unixFetch() invocation.
4899**
4900** Or, if the third argument is NULL, then this function is being called
4901** to inform the VFS layer that, according to POSIX, any existing mapping
4902** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004903*/
dandf737fe2013-03-25 17:00:24 +00004904static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004905#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004906 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004907 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004908
danaef49d72013-03-25 16:28:54 +00004909 /* If p==0 (unmap the entire file) then there must be no outstanding
4910 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4911 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004912 assert( (p==0)==(pFd->nFetchOut==0) );
4913
dandf737fe2013-03-25 17:00:24 +00004914 /* If p!=0, it must match the iOff value. */
4915 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4916
danf23da962013-03-23 21:00:41 +00004917 if( p ){
4918 pFd->nFetchOut--;
4919 }else{
4920 unixUnmapfile(pFd);
4921 }
4922
4923 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004924#else
4925 UNUSED_PARAMETER(fd);
4926 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004927 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004928#endif
danf23da962013-03-23 21:00:41 +00004929 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004930}
4931
4932/*
drh734c9862008-11-28 15:37:20 +00004933** Here ends the implementation of all sqlite3_file methods.
4934**
4935********************** End sqlite3_file Methods *******************************
4936******************************************************************************/
4937
4938/*
drh6b9d6dd2008-12-03 19:34:47 +00004939** This division contains definitions of sqlite3_io_methods objects that
4940** implement various file locking strategies. It also contains definitions
4941** of "finder" functions. A finder-function is used to locate the appropriate
4942** sqlite3_io_methods object for a particular database file. The pAppData
4943** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4944** the correct finder-function for that VFS.
4945**
4946** Most finder functions return a pointer to a fixed sqlite3_io_methods
4947** object. The only interesting finder-function is autolockIoFinder, which
4948** looks at the filesystem type and tries to guess the best locking
4949** strategy from that.
4950**
peter.d.reid60ec9142014-09-06 16:39:46 +00004951** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004952**
4953** (1) The real finder-function named "FImpt()".
4954**
dane946c392009-08-22 11:39:46 +00004955** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004956**
4957**
4958** A pointer to the F pointer is used as the pAppData value for VFS
4959** objects. We have to do this instead of letting pAppData point
4960** directly at the finder-function since C90 rules prevent a void*
4961** from be cast into a function pointer.
4962**
drh6b9d6dd2008-12-03 19:34:47 +00004963**
drh7708e972008-11-29 00:56:52 +00004964** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004965**
drh7708e972008-11-29 00:56:52 +00004966** * A constant sqlite3_io_methods object call METHOD that has locking
4967** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4968**
4969** * An I/O method finder function called FINDER that returns a pointer
4970** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004971*/
drhe6d41732015-02-21 00:49:00 +00004972#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004973static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004974 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004975 CLOSE, /* xClose */ \
4976 unixRead, /* xRead */ \
4977 unixWrite, /* xWrite */ \
4978 unixTruncate, /* xTruncate */ \
4979 unixSync, /* xSync */ \
4980 unixFileSize, /* xFileSize */ \
4981 LOCK, /* xLock */ \
4982 UNLOCK, /* xUnlock */ \
4983 CKLOCK, /* xCheckReservedLock */ \
4984 unixFileControl, /* xFileControl */ \
4985 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004986 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004987 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004988 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004989 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004990 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004991 unixFetch, /* xFetch */ \
4992 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004993}; \
drh0c2694b2009-09-03 16:23:44 +00004994static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4995 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004996 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004997} \
drh0c2694b2009-09-03 16:23:44 +00004998static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004999 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005000
5001/*
5002** Here are all of the sqlite3_io_methods objects for each of the
5003** locking strategies. Functions that return pointers to these methods
5004** are also created.
5005*/
5006IOMETHODS(
5007 posixIoFinder, /* Finder function name */
5008 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005009 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005010 unixClose, /* xClose method */
5011 unixLock, /* xLock method */
5012 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005013 unixCheckReservedLock, /* xCheckReservedLock method */
5014 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005015)
drh7708e972008-11-29 00:56:52 +00005016IOMETHODS(
5017 nolockIoFinder, /* Finder function name */
5018 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005019 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005020 nolockClose, /* xClose method */
5021 nolockLock, /* xLock method */
5022 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005023 nolockCheckReservedLock, /* xCheckReservedLock method */
5024 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005025)
drh7708e972008-11-29 00:56:52 +00005026IOMETHODS(
5027 dotlockIoFinder, /* Finder function name */
5028 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005029 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005030 dotlockClose, /* xClose method */
5031 dotlockLock, /* xLock method */
5032 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005033 dotlockCheckReservedLock, /* xCheckReservedLock method */
5034 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005035)
drh7708e972008-11-29 00:56:52 +00005036
chw78a13182009-04-07 05:35:03 +00005037#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005038IOMETHODS(
5039 flockIoFinder, /* Finder function name */
5040 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005041 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005042 flockClose, /* xClose method */
5043 flockLock, /* xLock method */
5044 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005045 flockCheckReservedLock, /* xCheckReservedLock method */
5046 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005047)
drh7708e972008-11-29 00:56:52 +00005048#endif
5049
drh6c7d5c52008-11-21 20:32:33 +00005050#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005051IOMETHODS(
5052 semIoFinder, /* Finder function name */
5053 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005054 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005055 semClose, /* xClose method */
5056 semLock, /* xLock method */
5057 semUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005058 semCheckReservedLock, /* xCheckReservedLock method */
5059 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005060)
aswiftaebf4132008-11-21 00:10:35 +00005061#endif
drh7708e972008-11-29 00:56:52 +00005062
drhd2cb50b2009-01-09 21:41:17 +00005063#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005064IOMETHODS(
5065 afpIoFinder, /* Finder function name */
5066 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005067 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005068 afpClose, /* xClose method */
5069 afpLock, /* xLock method */
5070 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005071 afpCheckReservedLock, /* xCheckReservedLock method */
5072 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005073)
drh715ff302008-12-03 22:32:44 +00005074#endif
5075
5076/*
5077** The proxy locking method is a "super-method" in the sense that it
5078** opens secondary file descriptors for the conch and lock files and
5079** it uses proxy, dot-file, AFP, and flock() locking methods on those
5080** secondary files. For this reason, the division that implements
5081** proxy locking is located much further down in the file. But we need
5082** to go ahead and define the sqlite3_io_methods and finder function
5083** for proxy locking here. So we forward declare the I/O methods.
5084*/
drhd2cb50b2009-01-09 21:41:17 +00005085#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005086static int proxyClose(sqlite3_file*);
5087static int proxyLock(sqlite3_file*, int);
5088static int proxyUnlock(sqlite3_file*, int);
5089static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005090IOMETHODS(
5091 proxyIoFinder, /* Finder function name */
5092 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005093 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005094 proxyClose, /* xClose method */
5095 proxyLock, /* xLock method */
5096 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005097 proxyCheckReservedLock, /* xCheckReservedLock method */
5098 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005099)
aswiftaebf4132008-11-21 00:10:35 +00005100#endif
drh7708e972008-11-29 00:56:52 +00005101
drh7ed97b92010-01-20 13:07:21 +00005102/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5103#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5104IOMETHODS(
5105 nfsIoFinder, /* Finder function name */
5106 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005107 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005108 unixClose, /* xClose method */
5109 unixLock, /* xLock method */
5110 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005111 unixCheckReservedLock, /* xCheckReservedLock method */
5112 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005113)
5114#endif
drh7708e972008-11-29 00:56:52 +00005115
drhd2cb50b2009-01-09 21:41:17 +00005116#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005117/*
drh6b9d6dd2008-12-03 19:34:47 +00005118** This "finder" function attempts to determine the best locking strategy
5119** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005120** object that implements that strategy.
5121**
5122** This is for MacOSX only.
5123*/
drh1875f7a2008-12-08 18:19:17 +00005124static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005125 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005126 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005127){
5128 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005129 const char *zFilesystem; /* Filesystem type name */
5130 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005131 } aMap[] = {
5132 { "hfs", &posixIoMethods },
5133 { "ufs", &posixIoMethods },
5134 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005135 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005136 { "webdav", &nolockIoMethods },
5137 { 0, 0 }
5138 };
5139 int i;
5140 struct statfs fsInfo;
5141 struct flock lockInfo;
5142
5143 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005144 /* If filePath==NULL that means we are dealing with a transient file
5145 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005146 return &nolockIoMethods;
5147 }
5148 if( statfs(filePath, &fsInfo) != -1 ){
5149 if( fsInfo.f_flags & MNT_RDONLY ){
5150 return &nolockIoMethods;
5151 }
5152 for(i=0; aMap[i].zFilesystem; i++){
5153 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5154 return aMap[i].pMethods;
5155 }
5156 }
5157 }
5158
5159 /* Default case. Handles, amongst others, "nfs".
5160 ** Test byte-range lock using fcntl(). If the call succeeds,
5161 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005162 */
drh7708e972008-11-29 00:56:52 +00005163 lockInfo.l_len = 1;
5164 lockInfo.l_start = 0;
5165 lockInfo.l_whence = SEEK_SET;
5166 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005167 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005168 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5169 return &nfsIoMethods;
5170 } else {
5171 return &posixIoMethods;
5172 }
drh7708e972008-11-29 00:56:52 +00005173 }else{
5174 return &dotlockIoMethods;
5175 }
5176}
drh0c2694b2009-09-03 16:23:44 +00005177static const sqlite3_io_methods
5178 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005179
drhd2cb50b2009-01-09 21:41:17 +00005180#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005181
chw78a13182009-04-07 05:35:03 +00005182#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5183/*
5184** This "finder" function attempts to determine the best locking strategy
5185** for the database file "filePath". It then returns the sqlite3_io_methods
5186** object that implements that strategy.
5187**
5188** This is for VXWorks only.
5189*/
5190static const sqlite3_io_methods *autolockIoFinderImpl(
5191 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005192 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005193){
5194 struct flock lockInfo;
5195
5196 if( !filePath ){
5197 /* If filePath==NULL that means we are dealing with a transient file
5198 ** that does not need to be locked. */
5199 return &nolockIoMethods;
5200 }
5201
5202 /* Test if fcntl() is supported and use POSIX style locks.
5203 ** Otherwise fall back to the named semaphore method.
5204 */
5205 lockInfo.l_len = 1;
5206 lockInfo.l_start = 0;
5207 lockInfo.l_whence = SEEK_SET;
5208 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005209 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005210 return &posixIoMethods;
5211 }else{
5212 return &semIoMethods;
5213 }
5214}
drh0c2694b2009-09-03 16:23:44 +00005215static const sqlite3_io_methods
5216 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005217
5218#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5219
drh7708e972008-11-29 00:56:52 +00005220/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005221** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005222*/
drh0c2694b2009-09-03 16:23:44 +00005223typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005224
aswiftaebf4132008-11-21 00:10:35 +00005225
drh734c9862008-11-28 15:37:20 +00005226/****************************************************************************
5227**************************** sqlite3_vfs methods ****************************
5228**
5229** This division contains the implementation of methods on the
5230** sqlite3_vfs object.
5231*/
5232
danielk1977a3d4c882007-03-23 10:08:38 +00005233/*
danielk1977e339d652008-06-28 11:23:00 +00005234** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005235*/
5236static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005237 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005238 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005239 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005240 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005241 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005242){
drh7708e972008-11-29 00:56:52 +00005243 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005244 unixFile *pNew = (unixFile *)pId;
5245 int rc = SQLITE_OK;
5246
drh8af6c222010-05-14 12:43:01 +00005247 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005248
dan00157392010-10-05 11:33:15 +00005249 /* Usually the path zFilename should not be a relative pathname. The
5250 ** exception is when opening the proxy "conch" file in builds that
5251 ** include the special Apple locking styles.
5252 */
dan00157392010-10-05 11:33:15 +00005253#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005254 assert( zFilename==0 || zFilename[0]=='/'
5255 || pVfs->pAppData==(void*)&autolockIoFinder );
5256#else
5257 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005258#endif
dan00157392010-10-05 11:33:15 +00005259
drhb07028f2011-10-14 21:49:18 +00005260 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005261 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005262
drh308c2a52010-05-14 11:30:18 +00005263 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005264 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005265 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005266 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005267 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005268#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005269 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005270#endif
drhc02a43a2012-01-10 23:18:38 +00005271 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5272 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005273 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005274 }
drh503a6862013-03-01 01:07:17 +00005275 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005276 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005277 }
drh339eb0b2008-03-07 15:34:11 +00005278
drh6c7d5c52008-11-21 20:32:33 +00005279#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005280 pNew->pId = vxworksFindFileId(zFilename);
5281 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005282 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005283 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005284 }
5285#endif
5286
drhc02a43a2012-01-10 23:18:38 +00005287 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005288 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005289 }else{
drh0c2694b2009-09-03 16:23:44 +00005290 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005291#if SQLITE_ENABLE_LOCKING_STYLE
5292 /* Cache zFilename in the locking context (AFP and dotlock override) for
5293 ** proxyLock activation is possible (remote proxy is based on db name)
5294 ** zFilename remains valid until file is closed, to support */
5295 pNew->lockingContext = (void*)zFilename;
5296#endif
drhda0e7682008-07-30 15:27:54 +00005297 }
danielk1977e339d652008-06-28 11:23:00 +00005298
drh7ed97b92010-01-20 13:07:21 +00005299 if( pLockingStyle == &posixIoMethods
5300#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5301 || pLockingStyle == &nfsIoMethods
5302#endif
5303 ){
drh7708e972008-11-29 00:56:52 +00005304 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005305 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005306 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005307 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005308 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005309 ** in two scenarios:
5310 **
5311 ** (a) A call to fstat() failed.
5312 ** (b) A malloc failed.
5313 **
5314 ** Scenario (b) may only occur if the process is holding no other
5315 ** file descriptors open on the same file. If there were other file
5316 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005317 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005318 ** handle h - as it is guaranteed that no posix locks will be released
5319 ** by doing so.
5320 **
5321 ** If scenario (a) caused the error then things are not so safe. The
5322 ** implicit assumption here is that if fstat() fails, things are in
5323 ** such bad shape that dropping a lock or two doesn't matter much.
5324 */
drh0e9365c2011-03-02 02:08:13 +00005325 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005326 h = -1;
5327 }
drh7708e972008-11-29 00:56:52 +00005328 unixLeaveMutex();
5329 }
danielk1977e339d652008-06-28 11:23:00 +00005330
drhd2cb50b2009-01-09 21:41:17 +00005331#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005332 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005333 /* AFP locking uses the file path so it needs to be included in
5334 ** the afpLockingContext.
5335 */
5336 afpLockingContext *pCtx;
5337 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5338 if( pCtx==0 ){
5339 rc = SQLITE_NOMEM;
5340 }else{
5341 /* NB: zFilename exists and remains valid until the file is closed
5342 ** according to requirement F11141. So we do not need to make a
5343 ** copy of the filename. */
5344 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005345 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005346 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005347 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005348 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005349 if( rc!=SQLITE_OK ){
5350 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005351 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005352 h = -1;
5353 }
drh7708e972008-11-29 00:56:52 +00005354 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005355 }
drh7708e972008-11-29 00:56:52 +00005356 }
5357#endif
danielk1977e339d652008-06-28 11:23:00 +00005358
drh7708e972008-11-29 00:56:52 +00005359 else if( pLockingStyle == &dotlockIoMethods ){
5360 /* Dotfile locking uses the file path so it needs to be included in
5361 ** the dotlockLockingContext
5362 */
5363 char *zLockFile;
5364 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005365 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005366 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005367 zLockFile = (char *)sqlite3_malloc(nFilename);
5368 if( zLockFile==0 ){
5369 rc = SQLITE_NOMEM;
5370 }else{
5371 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005372 }
drh7708e972008-11-29 00:56:52 +00005373 pNew->lockingContext = zLockFile;
5374 }
danielk1977e339d652008-06-28 11:23:00 +00005375
drh6c7d5c52008-11-21 20:32:33 +00005376#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005377 else if( pLockingStyle == &semIoMethods ){
5378 /* Named semaphore locking uses the file path so it needs to be
5379 ** included in the semLockingContext
5380 */
5381 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005382 rc = findInodeInfo(pNew, &pNew->pInode);
5383 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5384 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005385 int n;
drh2238dcc2009-08-27 17:56:20 +00005386 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005387 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005388 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005389 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005390 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5391 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005392 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005393 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005394 }
chw97185482008-11-17 08:05:31 +00005395 }
drh7708e972008-11-29 00:56:52 +00005396 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005397 }
drh7708e972008-11-29 00:56:52 +00005398#endif
aswift5b1a2562008-08-22 00:22:35 +00005399
drh4bf66fd2015-02-19 02:43:02 +00005400 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005401#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005402 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005403 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005404 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005405 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005406 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005407 }
chw97185482008-11-17 08:05:31 +00005408#endif
danielk1977e339d652008-06-28 11:23:00 +00005409 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005410 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005411 }else{
drh7708e972008-11-29 00:56:52 +00005412 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005413 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005414 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005415 }
danielk1977e339d652008-06-28 11:23:00 +00005416 return rc;
drh054889e2005-11-30 03:20:31 +00005417}
drh9c06c952005-11-26 00:25:00 +00005418
danielk1977ad94b582007-08-20 06:44:22 +00005419/*
drh8b3cf822010-06-01 21:02:51 +00005420** Return the name of a directory in which to put temporary files.
5421** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005422*/
drh7234c6d2010-06-19 15:10:09 +00005423static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005424 static const char *azDirs[] = {
5425 0,
aswiftaebf4132008-11-21 00:10:35 +00005426 0,
mistachkind95a3d32013-08-30 21:52:38 +00005427 0,
danielk197717b90b52008-06-06 11:11:25 +00005428 "/var/tmp",
5429 "/usr/tmp",
5430 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005431 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005432 };
drh8b3cf822010-06-01 21:02:51 +00005433 unsigned int i;
5434 struct stat buf;
5435 const char *zDir = 0;
5436
5437 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005438 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5439 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005440 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005441 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005442 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005443 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005444 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005445 break;
5446 }
5447 return zDir;
5448}
5449
5450/*
5451** Create a temporary file name in zBuf. zBuf must be allocated
5452** by the calling process and must be big enough to hold at least
5453** pVfs->mxPathname bytes.
5454*/
5455static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005456 static const unsigned char zChars[] =
5457 "abcdefghijklmnopqrstuvwxyz"
5458 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5459 "0123456789";
drh41022642008-11-21 00:24:42 +00005460 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005461 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005462
5463 /* It's odd to simulate an io-error here, but really this is just
5464 ** using the io-error infrastructure to test that SQLite handles this
5465 ** function failing.
5466 */
5467 SimulateIOError( return SQLITE_IOERR );
5468
drh7234c6d2010-06-19 15:10:09 +00005469 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005470 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005471
5472 /* Check that the output buffer is large enough for the temporary file
5473 ** name. If it is not, return SQLITE_ERROR.
5474 */
drhc02a43a2012-01-10 23:18:38 +00005475 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005476 return SQLITE_ERROR;
5477 }
5478
5479 do{
drhc02a43a2012-01-10 23:18:38 +00005480 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005481 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005482 sqlite3_randomness(15, &zBuf[j]);
5483 for(i=0; i<15; i++, j++){
5484 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5485 }
5486 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005487 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005488 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005489 return SQLITE_OK;
5490}
5491
drhd2cb50b2009-01-09 21:41:17 +00005492#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005493/*
5494** Routine to transform a unixFile into a proxy-locking unixFile.
5495** Implementation in the proxy-lock division, but used by unixOpen()
5496** if SQLITE_PREFER_PROXY_LOCKING is defined.
5497*/
5498static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005499#endif
drhc66d5b62008-12-03 22:48:32 +00005500
dan08da86a2009-08-21 17:18:03 +00005501/*
5502** Search for an unused file descriptor that was opened on the database
5503** file (not a journal or master-journal file) identified by pathname
5504** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5505** argument to this function.
5506**
5507** Such a file descriptor may exist if a database connection was closed
5508** but the associated file descriptor could not be closed because some
5509** other file descriptor open on the same file is holding a file-lock.
5510** Refer to comments in the unixClose() function and the lengthy comment
5511** describing "Posix Advisory Locking" at the start of this file for
5512** further details. Also, ticket #4018.
5513**
5514** If a suitable file descriptor is found, then it is returned. If no
5515** such file descriptor is located, -1 is returned.
5516*/
dane946c392009-08-22 11:39:46 +00005517static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5518 UnixUnusedFd *pUnused = 0;
5519
5520 /* Do not search for an unused file descriptor on vxworks. Not because
5521 ** vxworks would not benefit from the change (it might, we're not sure),
5522 ** but because no way to test it is currently available. It is better
5523 ** not to risk breaking vxworks support for the sake of such an obscure
5524 ** feature. */
5525#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005526 struct stat sStat; /* Results of stat() call */
5527
5528 /* A stat() call may fail for various reasons. If this happens, it is
5529 ** almost certain that an open() call on the same path will also fail.
5530 ** For this reason, if an error occurs in the stat() call here, it is
5531 ** ignored and -1 is returned. The caller will try to open a new file
5532 ** descriptor on the same path, fail, and return an error to SQLite.
5533 **
5534 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005535 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005536 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005537 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005538
5539 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005540 pInode = inodeList;
5541 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5542 || pInode->fileId.ino!=sStat.st_ino) ){
5543 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005544 }
drh8af6c222010-05-14 12:43:01 +00005545 if( pInode ){
dane946c392009-08-22 11:39:46 +00005546 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005547 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005548 pUnused = *pp;
5549 if( pUnused ){
5550 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005551 }
5552 }
5553 unixLeaveMutex();
5554 }
dane946c392009-08-22 11:39:46 +00005555#endif /* if !OS_VXWORKS */
5556 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005557}
danielk197717b90b52008-06-06 11:11:25 +00005558
5559/*
danddb0ac42010-07-14 14:48:58 +00005560** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005561** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005562** and a value suitable for passing as the third argument to open(2) is
5563** written to *pMode. If an IO error occurs, an SQLite error code is
5564** returned and the value of *pMode is not modified.
5565**
peter.d.reid60ec9142014-09-06 16:39:46 +00005566** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005567** an indication to robust_open() to create the file using
5568** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5569** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005570** this function queries the file-system for the permissions on the
5571** corresponding database file and sets *pMode to this value. Whenever
5572** possible, WAL and journal files are created using the same permissions
5573** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005574**
5575** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5576** original filename is unavailable. But 8_3_NAMES is only used for
5577** FAT filesystems and permissions do not matter there, so just use
5578** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005579*/
5580static int findCreateFileMode(
5581 const char *zPath, /* Path of file (possibly) being created */
5582 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005583 mode_t *pMode, /* OUT: Permissions to open file with */
5584 uid_t *pUid, /* OUT: uid to set on the file */
5585 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005586){
5587 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005588 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005589 *pUid = 0;
5590 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005591 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005592 char zDb[MAX_PATHNAME+1]; /* Database file path */
5593 int nDb; /* Number of valid bytes in zDb */
5594 struct stat sStat; /* Output of stat() on database file */
5595
dana0c989d2010-11-05 18:07:37 +00005596 /* zPath is a path to a WAL or journal file. The following block derives
5597 ** the path to the associated database file from zPath. This block handles
5598 ** the following naming conventions:
5599 **
5600 ** "<path to db>-journal"
5601 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005602 ** "<path to db>-journalNN"
5603 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005604 **
drhd337c5b2011-10-20 18:23:35 +00005605 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005606 ** used by the test_multiplex.c module.
5607 */
5608 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005609#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005610 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005611 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005612#else
5613 while( zPath[nDb]!='-' ){
5614 assert( nDb>0 );
5615 assert( zPath[nDb]!='\n' );
5616 nDb--;
5617 }
5618#endif
danddb0ac42010-07-14 14:48:58 +00005619 memcpy(zDb, zPath, nDb);
5620 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005621
drh58384f12011-07-28 00:14:45 +00005622 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005623 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005624 *pUid = sStat.st_uid;
5625 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005626 }else{
5627 rc = SQLITE_IOERR_FSTAT;
5628 }
5629 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5630 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005631 }
5632 return rc;
5633}
5634
5635/*
danielk1977ad94b582007-08-20 06:44:22 +00005636** Open the file zPath.
5637**
danielk1977b4b47412007-08-17 15:53:36 +00005638** Previously, the SQLite OS layer used three functions in place of this
5639** one:
5640**
5641** sqlite3OsOpenReadWrite();
5642** sqlite3OsOpenReadOnly();
5643** sqlite3OsOpenExclusive();
5644**
5645** These calls correspond to the following combinations of flags:
5646**
5647** ReadWrite() -> (READWRITE | CREATE)
5648** ReadOnly() -> (READONLY)
5649** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5650**
5651** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5652** true, the file was configured to be automatically deleted when the
5653** file handle closed. To achieve the same effect using this new
5654** interface, add the DELETEONCLOSE flag to those specified above for
5655** OpenExclusive().
5656*/
5657static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005658 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5659 const char *zPath, /* Pathname of file to be opened */
5660 sqlite3_file *pFile, /* The file descriptor to be filled in */
5661 int flags, /* Input flags to control the opening */
5662 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005663){
dan08da86a2009-08-21 17:18:03 +00005664 unixFile *p = (unixFile *)pFile;
5665 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005666 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005667 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005668 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005669 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005670 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005671
5672 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5673 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5674 int isCreate = (flags & SQLITE_OPEN_CREATE);
5675 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5676 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005677#if SQLITE_ENABLE_LOCKING_STYLE
5678 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5679#endif
drh3d4435b2011-08-26 20:55:50 +00005680#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5681 struct statfs fsInfo;
5682#endif
danielk1977b4b47412007-08-17 15:53:36 +00005683
danielk1977fee2d252007-08-18 10:59:19 +00005684 /* If creating a master or main-file journal, this function will open
5685 ** a file-descriptor on the directory too. The first time unixSync()
5686 ** is called the directory file descriptor will be fsync()ed and close()d.
5687 */
drh0059eae2011-08-08 23:48:40 +00005688 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005689 eType==SQLITE_OPEN_MASTER_JOURNAL
5690 || eType==SQLITE_OPEN_MAIN_JOURNAL
5691 || eType==SQLITE_OPEN_WAL
5692 ));
danielk1977fee2d252007-08-18 10:59:19 +00005693
danielk197717b90b52008-06-06 11:11:25 +00005694 /* If argument zPath is a NULL pointer, this function is required to open
5695 ** a temporary file. Use this buffer to store the file name in.
5696 */
drhc02a43a2012-01-10 23:18:38 +00005697 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005698 const char *zName = zPath;
5699
danielk1977fee2d252007-08-18 10:59:19 +00005700 /* Check the following statements are true:
5701 **
5702 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5703 ** (b) if CREATE is set, then READWRITE must also be set, and
5704 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005705 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005706 */
danielk1977b4b47412007-08-17 15:53:36 +00005707 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005708 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005709 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005710 assert(isDelete==0 || isCreate);
5711
danddb0ac42010-07-14 14:48:58 +00005712 /* The main DB, main journal, WAL file and master journal are never
5713 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005714 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5715 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5716 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005717 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005718
danielk1977fee2d252007-08-18 10:59:19 +00005719 /* Assert that the upper layer has set one of the "file-type" flags. */
5720 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5721 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5722 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005723 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005724 );
5725
drhb00d8622014-01-01 15:18:36 +00005726 /* Detect a pid change and reset the PRNG. There is a race condition
5727 ** here such that two or more threads all trying to open databases at
5728 ** the same instant might all reset the PRNG. But multiple resets
5729 ** are harmless.
5730 */
5731 if( randomnessPid!=getpid() ){
5732 randomnessPid = getpid();
5733 sqlite3_randomness(0,0);
5734 }
5735
dan08da86a2009-08-21 17:18:03 +00005736 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005737
dan08da86a2009-08-21 17:18:03 +00005738 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005739 UnixUnusedFd *pUnused;
5740 pUnused = findReusableFd(zName, flags);
5741 if( pUnused ){
5742 fd = pUnused->fd;
5743 }else{
dan6aa657f2009-08-24 18:57:58 +00005744 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005745 if( !pUnused ){
5746 return SQLITE_NOMEM;
5747 }
5748 }
5749 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005750
5751 /* Database filenames are double-zero terminated if they are not
5752 ** URIs with parameters. Hence, they can always be passed into
5753 ** sqlite3_uri_parameter(). */
5754 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5755
dan08da86a2009-08-21 17:18:03 +00005756 }else if( !zName ){
5757 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005758 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005759 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005760 if( rc!=SQLITE_OK ){
5761 return rc;
5762 }
5763 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005764
5765 /* Generated temporary filenames are always double-zero terminated
5766 ** for use by sqlite3_uri_parameter(). */
5767 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005768 }
5769
dan08da86a2009-08-21 17:18:03 +00005770 /* Determine the value of the flags parameter passed to POSIX function
5771 ** open(). These must be calculated even if open() is not called, as
5772 ** they may be stored as part of the file handle and used by the
5773 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005774 if( isReadonly ) openFlags |= O_RDONLY;
5775 if( isReadWrite ) openFlags |= O_RDWR;
5776 if( isCreate ) openFlags |= O_CREAT;
5777 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5778 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005779
danielk1977b4b47412007-08-17 15:53:36 +00005780 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005781 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005782 uid_t uid; /* Userid for the file */
5783 gid_t gid; /* Groupid for the file */
5784 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005785 if( rc!=SQLITE_OK ){
5786 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005787 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005788 return rc;
5789 }
drhad4f1e52011-03-04 15:43:57 +00005790 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005791 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005792 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5793 /* Failed to open the file for read/write access. Try read-only. */
5794 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005795 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005796 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005797 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005798 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005799 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005800 }
5801 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005802 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005803 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005804 }
drhac7c3ac2012-02-11 19:23:48 +00005805
5806 /* If this process is running as root and if creating a new rollback
5807 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005808 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005809 */
5810 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005811 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005812 }
danielk1977b4b47412007-08-17 15:53:36 +00005813 }
dan08da86a2009-08-21 17:18:03 +00005814 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005815 if( pOutFlags ){
5816 *pOutFlags = flags;
5817 }
5818
dane946c392009-08-22 11:39:46 +00005819 if( p->pUnused ){
5820 p->pUnused->fd = fd;
5821 p->pUnused->flags = flags;
5822 }
5823
danielk1977b4b47412007-08-17 15:53:36 +00005824 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005825#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005826 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005827#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5828 zPath = sqlite3_mprintf("%s", zName);
5829 if( zPath==0 ){
5830 robust_close(p, fd, __LINE__);
5831 return SQLITE_NOMEM;
5832 }
chw97185482008-11-17 08:05:31 +00005833#else
drh036ac7f2011-08-08 23:18:05 +00005834 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005835#endif
danielk1977b4b47412007-08-17 15:53:36 +00005836 }
drh41022642008-11-21 00:24:42 +00005837#if SQLITE_ENABLE_LOCKING_STYLE
5838 else{
dan08da86a2009-08-21 17:18:03 +00005839 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005840 }
5841#endif
5842
drhda0e7682008-07-30 15:27:54 +00005843 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005844
drh7ed97b92010-01-20 13:07:21 +00005845
5846#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005847 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005848 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005849 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005850 return SQLITE_IOERR_ACCESS;
5851 }
5852 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5853 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5854 }
drh4bf66fd2015-02-19 02:43:02 +00005855 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5856 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5857 }
drh7ed97b92010-01-20 13:07:21 +00005858#endif
drhc02a43a2012-01-10 23:18:38 +00005859
5860 /* Set up appropriate ctrlFlags */
5861 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5862 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5863 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5864 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5865 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5866
drh7ed97b92010-01-20 13:07:21 +00005867#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005868#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005869 isAutoProxy = 1;
5870#endif
5871 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005872 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5873 int useProxy = 0;
5874
dan08da86a2009-08-21 17:18:03 +00005875 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5876 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005877 if( envforce!=NULL ){
5878 useProxy = atoi(envforce)>0;
5879 }else{
aswiftaebf4132008-11-21 00:10:35 +00005880 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5881 }
5882 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005883 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005884 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005885 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005886 if( rc!=SQLITE_OK ){
5887 /* Use unixClose to clean up the resources added in fillInUnixFile
5888 ** and clear all the structure's references. Specifically,
5889 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5890 */
5891 unixClose(pFile);
5892 return rc;
5893 }
aswiftaebf4132008-11-21 00:10:35 +00005894 }
dane946c392009-08-22 11:39:46 +00005895 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005896 }
5897 }
5898#endif
5899
drhc02a43a2012-01-10 23:18:38 +00005900 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5901
dane946c392009-08-22 11:39:46 +00005902open_finished:
5903 if( rc!=SQLITE_OK ){
5904 sqlite3_free(p->pUnused);
5905 }
5906 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005907}
5908
dane946c392009-08-22 11:39:46 +00005909
danielk1977b4b47412007-08-17 15:53:36 +00005910/*
danielk1977fee2d252007-08-18 10:59:19 +00005911** Delete the file at zPath. If the dirSync argument is true, fsync()
5912** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005913*/
drh6b9d6dd2008-12-03 19:34:47 +00005914static int unixDelete(
5915 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5916 const char *zPath, /* Name of file to be deleted */
5917 int dirSync /* If true, fsync() directory after deleting file */
5918){
danielk1977fee2d252007-08-18 10:59:19 +00005919 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005920 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005921 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005922 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005923 if( errno==ENOENT
5924#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005925 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005926#endif
5927 ){
dan9fc5b4a2012-11-09 20:17:26 +00005928 rc = SQLITE_IOERR_DELETE_NOENT;
5929 }else{
drhb4308162012-11-09 21:40:02 +00005930 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005931 }
drhb4308162012-11-09 21:40:02 +00005932 return rc;
drh5d4feff2010-07-14 01:45:22 +00005933 }
danielk1977d39fa702008-10-16 13:27:40 +00005934#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005935 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005936 int fd;
drh90315a22011-08-10 01:52:12 +00005937 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005938 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005939#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005940 if( fsync(fd)==-1 )
5941#else
5942 if( fsync(fd) )
5943#endif
5944 {
dane18d4952011-02-21 11:46:24 +00005945 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005946 }
drh0e9365c2011-03-02 02:08:13 +00005947 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005948 }else if( rc==SQLITE_CANTOPEN ){
5949 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005950 }
5951 }
danielk1977d138dd82008-10-15 16:02:48 +00005952#endif
danielk1977fee2d252007-08-18 10:59:19 +00005953 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005954}
5955
danielk197790949c22007-08-17 16:50:38 +00005956/*
mistachkin48864df2013-03-21 21:20:32 +00005957** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005958** test performed depends on the value of flags:
5959**
5960** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5961** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5962** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5963**
5964** Otherwise return 0.
5965*/
danielk1977861f7452008-06-05 11:39:11 +00005966static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005967 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5968 const char *zPath, /* Path of the file to examine */
5969 int flags, /* What do we want to learn about the zPath file? */
5970 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005971){
rse25c0d1a2007-09-20 08:38:14 +00005972 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005973 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005974 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005975 switch( flags ){
5976 case SQLITE_ACCESS_EXISTS:
5977 amode = F_OK;
5978 break;
5979 case SQLITE_ACCESS_READWRITE:
5980 amode = W_OK|R_OK;
5981 break;
drh50d3f902007-08-27 21:10:36 +00005982 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005983 amode = R_OK;
5984 break;
5985
5986 default:
5987 assert(!"Invalid flags argument");
5988 }
drh99ab3b12011-03-02 15:09:07 +00005989 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005990 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5991 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005992 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005993 *pResOut = 0;
5994 }
5995 }
danielk1977861f7452008-06-05 11:39:11 +00005996 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005997}
5998
danielk1977b4b47412007-08-17 15:53:36 +00005999
6000/*
6001** Turn a relative pathname into a full pathname. The relative path
6002** is stored as a nul-terminated string in the buffer pointed to by
6003** zPath.
6004**
6005** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6006** (in this case, MAX_PATHNAME bytes). The full-path is written to
6007** this buffer before returning.
6008*/
danielk1977adfb9b02007-09-17 07:02:56 +00006009static int unixFullPathname(
6010 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6011 const char *zPath, /* Possibly relative input path */
6012 int nOut, /* Size of output buffer in bytes */
6013 char *zOut /* Output buffer */
6014){
danielk1977843e65f2007-09-01 16:16:15 +00006015
6016 /* It's odd to simulate an io-error here, but really this is just
6017 ** using the io-error infrastructure to test that SQLite handles this
6018 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006019 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006020 */
6021 SimulateIOError( return SQLITE_ERROR );
6022
drh153c62c2007-08-24 03:51:33 +00006023 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006024 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006025
drh3c7f2dc2007-12-06 13:26:20 +00006026 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00006027 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00006028 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006029 }else{
6030 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00006031 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006032 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006033 }
drhea678832008-12-10 19:26:22 +00006034 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00006035 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006036 }
6037 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006038}
6039
drh0ccebe72005-06-07 22:22:50 +00006040
drh761df872006-12-21 01:29:22 +00006041#ifndef SQLITE_OMIT_LOAD_EXTENSION
6042/*
6043** Interfaces for opening a shared library, finding entry points
6044** within the shared library, and closing the shared library.
6045*/
6046#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006047static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6048 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006049 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6050}
danielk197795c8a542007-09-01 06:51:27 +00006051
6052/*
6053** SQLite calls this function immediately after a call to unixDlSym() or
6054** unixDlOpen() fails (returns a null pointer). If a more detailed error
6055** message is available, it is written to zBufOut. If no error message
6056** is available, zBufOut is left unmodified and SQLite uses a default
6057** error message.
6058*/
danielk1977397d65f2008-11-19 11:35:39 +00006059static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006060 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006061 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006062 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006063 zErr = dlerror();
6064 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006065 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006066 }
drh6c7d5c52008-11-21 20:32:33 +00006067 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006068}
drh1875f7a2008-12-08 18:19:17 +00006069static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6070 /*
6071 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6072 ** cast into a pointer to a function. And yet the library dlsym() routine
6073 ** returns a void* which is really a pointer to a function. So how do we
6074 ** use dlsym() with -pedantic-errors?
6075 **
6076 ** Variable x below is defined to be a pointer to a function taking
6077 ** parameters void* and const char* and returning a pointer to a function.
6078 ** We initialize x by assigning it a pointer to the dlsym() function.
6079 ** (That assignment requires a cast.) Then we call the function that
6080 ** x points to.
6081 **
6082 ** This work-around is unlikely to work correctly on any system where
6083 ** you really cannot cast a function pointer into void*. But then, on the
6084 ** other hand, dlsym() will not work on such a system either, so we have
6085 ** not really lost anything.
6086 */
6087 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006088 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006089 x = (void(*(*)(void*,const char*))(void))dlsym;
6090 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006091}
danielk1977397d65f2008-11-19 11:35:39 +00006092static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6093 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006094 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006095}
danielk1977b4b47412007-08-17 15:53:36 +00006096#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6097 #define unixDlOpen 0
6098 #define unixDlError 0
6099 #define unixDlSym 0
6100 #define unixDlClose 0
6101#endif
6102
6103/*
danielk197790949c22007-08-17 16:50:38 +00006104** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006105*/
danielk1977397d65f2008-11-19 11:35:39 +00006106static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6107 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006108 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006109
drhbbd42a62004-05-22 17:41:58 +00006110 /* We have to initialize zBuf to prevent valgrind from reporting
6111 ** errors. The reports issued by valgrind are incorrect - we would
6112 ** prefer that the randomness be increased by making use of the
6113 ** uninitialized space in zBuf - but valgrind errors tend to worry
6114 ** some users. Rather than argue, it seems easier just to initialize
6115 ** the whole array and silence valgrind, even if that means less randomness
6116 ** in the random seed.
6117 **
6118 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006119 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006120 ** tests repeatable.
6121 */
danielk1977b4b47412007-08-17 15:53:36 +00006122 memset(zBuf, 0, nBuf);
drhb00d8622014-01-01 15:18:36 +00006123 randomnessPid = getpid();
drhbbd42a62004-05-22 17:41:58 +00006124#if !defined(SQLITE_TEST)
6125 {
drhb00d8622014-01-01 15:18:36 +00006126 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006127 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006128 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006129 time_t t;
6130 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006131 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006132 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6133 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6134 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006135 }else{
drhc18b4042012-02-10 03:10:27 +00006136 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006137 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006138 }
drhbbd42a62004-05-22 17:41:58 +00006139 }
6140#endif
drh72cbd072008-10-14 17:58:38 +00006141 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006142}
6143
danielk1977b4b47412007-08-17 15:53:36 +00006144
drhbbd42a62004-05-22 17:41:58 +00006145/*
6146** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006147** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006148** The return value is the number of microseconds of sleep actually
6149** requested from the underlying operating system, a number which
6150** might be greater than or equal to the argument, but not less
6151** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006152*/
danielk1977397d65f2008-11-19 11:35:39 +00006153static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006154#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006155 struct timespec sp;
6156
6157 sp.tv_sec = microseconds / 1000000;
6158 sp.tv_nsec = (microseconds % 1000000) * 1000;
6159 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006160 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006161 return microseconds;
6162#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006163 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006164 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006165 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006166#else
danielk1977b4b47412007-08-17 15:53:36 +00006167 int seconds = (microseconds+999999)/1000000;
6168 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006169 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006170 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006171#endif
drh88f474a2006-01-02 20:00:12 +00006172}
6173
6174/*
drh6b9d6dd2008-12-03 19:34:47 +00006175** The following variable, if set to a non-zero value, is interpreted as
6176** the number of seconds since 1970 and is used to set the result of
6177** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006178*/
6179#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006180int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006181#endif
6182
6183/*
drhb7e8ea22010-05-03 14:32:30 +00006184** Find the current time (in Universal Coordinated Time). Write into *piNow
6185** the current time and date as a Julian Day number times 86_400_000. In
6186** other words, write into *piNow the number of milliseconds since the Julian
6187** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6188** proleptic Gregorian calendar.
6189**
drh31702252011-10-12 23:13:43 +00006190** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6191** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006192*/
6193static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6194 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006195 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006196#if defined(NO_GETTOD)
6197 time_t t;
6198 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006199 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006200#elif OS_VXWORKS
6201 struct timespec sNow;
6202 clock_gettime(CLOCK_REALTIME, &sNow);
6203 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6204#else
6205 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006206 if( gettimeofday(&sNow, 0)==0 ){
6207 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6208 }else{
6209 rc = SQLITE_ERROR;
6210 }
drhb7e8ea22010-05-03 14:32:30 +00006211#endif
6212
6213#ifdef SQLITE_TEST
6214 if( sqlite3_current_time ){
6215 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6216 }
6217#endif
6218 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006219 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006220}
6221
6222/*
drhbbd42a62004-05-22 17:41:58 +00006223** Find the current time (in Universal Coordinated Time). Write the
6224** current time and date as a Julian Day number into *prNow and
6225** return 0. Return 1 if the time and date cannot be found.
6226*/
danielk1977397d65f2008-11-19 11:35:39 +00006227static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006228 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006229 int rc;
drhff828942010-06-26 21:34:06 +00006230 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006231 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006232 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006233 return rc;
drhbbd42a62004-05-22 17:41:58 +00006234}
danielk1977b4b47412007-08-17 15:53:36 +00006235
drh6b9d6dd2008-12-03 19:34:47 +00006236/*
6237** We added the xGetLastError() method with the intention of providing
6238** better low-level error messages when operating-system problems come up
6239** during SQLite operation. But so far, none of that has been implemented
6240** in the core. So this routine is never called. For now, it is merely
6241** a place-holder.
6242*/
danielk1977397d65f2008-11-19 11:35:39 +00006243static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6244 UNUSED_PARAMETER(NotUsed);
6245 UNUSED_PARAMETER(NotUsed2);
6246 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006247 return 0;
6248}
6249
drhf2424c52010-04-26 00:04:55 +00006250
6251/*
drh734c9862008-11-28 15:37:20 +00006252************************ End of sqlite3_vfs methods ***************************
6253******************************************************************************/
6254
drh715ff302008-12-03 22:32:44 +00006255/******************************************************************************
6256************************** Begin Proxy Locking ********************************
6257**
6258** Proxy locking is a "uber-locking-method" in this sense: It uses the
6259** other locking methods on secondary lock files. Proxy locking is a
6260** meta-layer over top of the primitive locking implemented above. For
6261** this reason, the division that implements of proxy locking is deferred
6262** until late in the file (here) after all of the other I/O methods have
6263** been defined - so that the primitive locking methods are available
6264** as services to help with the implementation of proxy locking.
6265**
6266****
6267**
6268** The default locking schemes in SQLite use byte-range locks on the
6269** database file to coordinate safe, concurrent access by multiple readers
6270** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6271** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6272** as POSIX read & write locks over fixed set of locations (via fsctl),
6273** on AFP and SMB only exclusive byte-range locks are available via fsctl
6274** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6275** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6276** address in the shared range is taken for a SHARED lock, the entire
6277** shared range is taken for an EXCLUSIVE lock):
6278**
drhf2f105d2012-08-20 15:53:54 +00006279** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006280** RESERVED_BYTE 0x40000001
6281** SHARED_RANGE 0x40000002 -> 0x40000200
6282**
6283** This works well on the local file system, but shows a nearly 100x
6284** slowdown in read performance on AFP because the AFP client disables
6285** the read cache when byte-range locks are present. Enabling the read
6286** cache exposes a cache coherency problem that is present on all OS X
6287** supported network file systems. NFS and AFP both observe the
6288** close-to-open semantics for ensuring cache coherency
6289** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6290** address the requirements for concurrent database access by multiple
6291** readers and writers
6292** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6293**
6294** To address the performance and cache coherency issues, proxy file locking
6295** changes the way database access is controlled by limiting access to a
6296** single host at a time and moving file locks off of the database file
6297** and onto a proxy file on the local file system.
6298**
6299**
6300** Using proxy locks
6301** -----------------
6302**
6303** C APIs
6304**
drh4bf66fd2015-02-19 02:43:02 +00006305** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006306** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006307** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6308** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006309**
6310**
6311** SQL pragmas
6312**
6313** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6314** PRAGMA [database.]lock_proxy_file
6315**
6316** Specifying ":auto:" means that if there is a conch file with a matching
6317** host ID in it, the proxy path in the conch file will be used, otherwise
6318** a proxy path based on the user's temp dir
6319** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6320** actual proxy file name is generated from the name and path of the
6321** database file. For example:
6322**
6323** For database path "/Users/me/foo.db"
6324** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6325**
6326** Once a lock proxy is configured for a database connection, it can not
6327** be removed, however it may be switched to a different proxy path via
6328** the above APIs (assuming the conch file is not being held by another
6329** connection or process).
6330**
6331**
6332** How proxy locking works
6333** -----------------------
6334**
6335** Proxy file locking relies primarily on two new supporting files:
6336**
6337** * conch file to limit access to the database file to a single host
6338** at a time
6339**
6340** * proxy file to act as a proxy for the advisory locks normally
6341** taken on the database
6342**
6343** The conch file - to use a proxy file, sqlite must first "hold the conch"
6344** by taking an sqlite-style shared lock on the conch file, reading the
6345** contents and comparing the host's unique host ID (see below) and lock
6346** proxy path against the values stored in the conch. The conch file is
6347** stored in the same directory as the database file and the file name
6348** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006349** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006350** host ID and/or proxy path, then the lock is escalated to an exclusive
6351** lock and the conch file contents is updated with the host ID and proxy
6352** path and the lock is downgraded to a shared lock again. If the conch
6353** is held by another process (with a shared lock), the exclusive lock
6354** will fail and SQLITE_BUSY is returned.
6355**
6356** The proxy file - a single-byte file used for all advisory file locks
6357** normally taken on the database file. This allows for safe sharing
6358** of the database file for multiple readers and writers on the same
6359** host (the conch ensures that they all use the same local lock file).
6360**
drh715ff302008-12-03 22:32:44 +00006361** Requesting the lock proxy does not immediately take the conch, it is
6362** only taken when the first request to lock database file is made.
6363** This matches the semantics of the traditional locking behavior, where
6364** opening a connection to a database file does not take a lock on it.
6365** The shared lock and an open file descriptor are maintained until
6366** the connection to the database is closed.
6367**
6368** The proxy file and the lock file are never deleted so they only need
6369** to be created the first time they are used.
6370**
6371** Configuration options
6372** ---------------------
6373**
6374** SQLITE_PREFER_PROXY_LOCKING
6375**
6376** Database files accessed on non-local file systems are
6377** automatically configured for proxy locking, lock files are
6378** named automatically using the same logic as
6379** PRAGMA lock_proxy_file=":auto:"
6380**
6381** SQLITE_PROXY_DEBUG
6382**
6383** Enables the logging of error messages during host id file
6384** retrieval and creation
6385**
drh715ff302008-12-03 22:32:44 +00006386** LOCKPROXYDIR
6387**
6388** Overrides the default directory used for lock proxy files that
6389** are named automatically via the ":auto:" setting
6390**
6391** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6392**
6393** Permissions to use when creating a directory for storing the
6394** lock proxy files, only used when LOCKPROXYDIR is not set.
6395**
6396**
6397** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6398** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6399** force proxy locking to be used for every database file opened, and 0
6400** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006401** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006402** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6403*/
6404
6405/*
6406** Proxy locking is only available on MacOSX
6407*/
drhd2cb50b2009-01-09 21:41:17 +00006408#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006409
drh715ff302008-12-03 22:32:44 +00006410/*
6411** The proxyLockingContext has the path and file structures for the remote
6412** and local proxy files in it
6413*/
6414typedef struct proxyLockingContext proxyLockingContext;
6415struct proxyLockingContext {
6416 unixFile *conchFile; /* Open conch file */
6417 char *conchFilePath; /* Name of the conch file */
6418 unixFile *lockProxy; /* Open proxy lock file */
6419 char *lockProxyPath; /* Name of the proxy lock file */
6420 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006421 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006422 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006423 void *oldLockingContext; /* Original lockingcontext to restore on close */
6424 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6425};
6426
drh7ed97b92010-01-20 13:07:21 +00006427/*
6428** The proxy lock file path for the database at dbPath is written into lPath,
6429** which must point to valid, writable memory large enough for a maxLen length
6430** file path.
drh715ff302008-12-03 22:32:44 +00006431*/
drh715ff302008-12-03 22:32:44 +00006432static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6433 int len;
6434 int dbLen;
6435 int i;
6436
6437#ifdef LOCKPROXYDIR
6438 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6439#else
6440# ifdef _CS_DARWIN_USER_TEMP_DIR
6441 {
drh7ed97b92010-01-20 13:07:21 +00006442 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006443 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6444 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006445 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006446 }
drh7ed97b92010-01-20 13:07:21 +00006447 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006448 }
6449# else
6450 len = strlcpy(lPath, "/tmp/", maxLen);
6451# endif
6452#endif
6453
6454 if( lPath[len-1]!='/' ){
6455 len = strlcat(lPath, "/", maxLen);
6456 }
6457
6458 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006459 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006460 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006461 char c = dbPath[i];
6462 lPath[i+len] = (c=='/')?'_':c;
6463 }
6464 lPath[i+len]='\0';
6465 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006466 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006467 return SQLITE_OK;
6468}
6469
drh7ed97b92010-01-20 13:07:21 +00006470/*
6471 ** Creates the lock file and any missing directories in lockPath
6472 */
6473static int proxyCreateLockPath(const char *lockPath){
6474 int i, len;
6475 char buf[MAXPATHLEN];
6476 int start = 0;
6477
6478 assert(lockPath!=NULL);
6479 /* try to create all the intermediate directories */
6480 len = (int)strlen(lockPath);
6481 buf[0] = lockPath[0];
6482 for( i=1; i<len; i++ ){
6483 if( lockPath[i] == '/' && (i - start > 0) ){
6484 /* only mkdir if leaf dir != "." or "/" or ".." */
6485 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6486 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6487 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006488 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006489 int err=errno;
6490 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006491 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006492 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006493 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006494 return err;
6495 }
6496 }
6497 }
6498 start=i+1;
6499 }
6500 buf[i] = lockPath[i];
6501 }
drh308c2a52010-05-14 11:30:18 +00006502 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006503 return 0;
6504}
6505
drh715ff302008-12-03 22:32:44 +00006506/*
6507** Create a new VFS file descriptor (stored in memory obtained from
6508** sqlite3_malloc) and open the file named "path" in the file descriptor.
6509**
6510** The caller is responsible not only for closing the file descriptor
6511** but also for freeing the memory associated with the file descriptor.
6512*/
drh7ed97b92010-01-20 13:07:21 +00006513static int proxyCreateUnixFile(
6514 const char *path, /* path for the new unixFile */
6515 unixFile **ppFile, /* unixFile created and returned by ref */
6516 int islockfile /* if non zero missing dirs will be created */
6517) {
6518 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006519 unixFile *pNew;
6520 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006521 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006522 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006523 int terrno = 0;
6524 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006525
drh7ed97b92010-01-20 13:07:21 +00006526 /* 1. first try to open/create the file
6527 ** 2. if that fails, and this is a lock file (not-conch), try creating
6528 ** the parent directories and then try again.
6529 ** 3. if that fails, try to open the file read-only
6530 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6531 */
6532 pUnused = findReusableFd(path, openFlags);
6533 if( pUnused ){
6534 fd = pUnused->fd;
6535 }else{
6536 pUnused = sqlite3_malloc(sizeof(*pUnused));
6537 if( !pUnused ){
6538 return SQLITE_NOMEM;
6539 }
6540 }
6541 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006542 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006543 terrno = errno;
6544 if( fd<0 && errno==ENOENT && islockfile ){
6545 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006546 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006547 }
6548 }
6549 }
6550 if( fd<0 ){
6551 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006552 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006553 terrno = errno;
6554 }
6555 if( fd<0 ){
6556 if( islockfile ){
6557 return SQLITE_BUSY;
6558 }
6559 switch (terrno) {
6560 case EACCES:
6561 return SQLITE_PERM;
6562 case EIO:
6563 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6564 default:
drh9978c972010-02-23 17:36:32 +00006565 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006566 }
6567 }
6568
6569 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6570 if( pNew==NULL ){
6571 rc = SQLITE_NOMEM;
6572 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006573 }
6574 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006575 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006576 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006577 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006578 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006579 pUnused->fd = fd;
6580 pUnused->flags = openFlags;
6581 pNew->pUnused = pUnused;
6582
drhc02a43a2012-01-10 23:18:38 +00006583 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006584 if( rc==SQLITE_OK ){
6585 *ppFile = pNew;
6586 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006587 }
drh7ed97b92010-01-20 13:07:21 +00006588end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006589 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006590 sqlite3_free(pNew);
6591 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006592 return rc;
6593}
6594
drh7ed97b92010-01-20 13:07:21 +00006595#ifdef SQLITE_TEST
6596/* simulate multiple hosts by creating unique hostid file paths */
6597int sqlite3_hostid_num = 0;
6598#endif
6599
6600#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6601
drh0ab216a2010-07-02 17:10:40 +00006602/* Not always defined in the headers as it ought to be */
6603extern int gethostuuid(uuid_t id, const struct timespec *wait);
6604
drh7ed97b92010-01-20 13:07:21 +00006605/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6606** bytes of writable memory.
6607*/
6608static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006609 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6610 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh4bf66fd2015-02-19 02:43:02 +00006611# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
6612 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
drh29ecd8a2010-12-21 00:16:40 +00006613 {
drh4bf66fd2015-02-19 02:43:02 +00006614 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006615 if( gethostuuid(pHostID, &timeout) ){
6616 int err = errno;
6617 if( pError ){
6618 *pError = err;
6619 }
6620 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006621 }
drh7ed97b92010-01-20 13:07:21 +00006622 }
drh3d4435b2011-08-26 20:55:50 +00006623#else
6624 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006625#endif
drh7ed97b92010-01-20 13:07:21 +00006626#ifdef SQLITE_TEST
6627 /* simulate multiple hosts by creating unique hostid file paths */
6628 if( sqlite3_hostid_num != 0){
6629 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6630 }
6631#endif
6632
6633 return SQLITE_OK;
6634}
6635
6636/* The conch file contains the header, host id and lock file path
6637 */
6638#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6639#define PROXY_HEADERLEN 1 /* conch file header length */
6640#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6641#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6642
6643/*
6644** Takes an open conch file, copies the contents to a new path and then moves
6645** it back. The newly created file's file descriptor is assigned to the
6646** conch file structure and finally the original conch file descriptor is
6647** closed. Returns zero if successful.
6648*/
6649static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6650 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6651 unixFile *conchFile = pCtx->conchFile;
6652 char tPath[MAXPATHLEN];
6653 char buf[PROXY_MAXCONCHLEN];
6654 char *cPath = pCtx->conchFilePath;
6655 size_t readLen = 0;
6656 size_t pathLen = 0;
6657 char errmsg[64] = "";
6658 int fd = -1;
6659 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006660 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006661
6662 /* create a new path by replace the trailing '-conch' with '-break' */
6663 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6664 if( pathLen>MAXPATHLEN || pathLen<6 ||
6665 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006666 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006667 goto end_breaklock;
6668 }
6669 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006670 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006671 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006672 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006673 goto end_breaklock;
6674 }
6675 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006676 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006677 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006678 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006679 goto end_breaklock;
6680 }
drhe562be52011-03-02 18:01:10 +00006681 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006682 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006683 goto end_breaklock;
6684 }
6685 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006686 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006687 goto end_breaklock;
6688 }
6689 rc = 0;
6690 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006691 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006692 conchFile->h = fd;
6693 conchFile->openFlags = O_RDWR | O_CREAT;
6694
6695end_breaklock:
6696 if( rc ){
6697 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006698 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006699 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006700 }
6701 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6702 }
6703 return rc;
6704}
6705
6706/* Take the requested lock on the conch file and break a stale lock if the
6707** host id matches.
6708*/
6709static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6710 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6711 unixFile *conchFile = pCtx->conchFile;
6712 int rc = SQLITE_OK;
6713 int nTries = 0;
6714 struct timespec conchModTime;
6715
drh3d4435b2011-08-26 20:55:50 +00006716 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006717 do {
6718 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6719 nTries ++;
6720 if( rc==SQLITE_BUSY ){
6721 /* If the lock failed (busy):
6722 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6723 * 2nd try: fail if the mod time changed or host id is different, wait
6724 * 10 sec and try again
6725 * 3rd try: break the lock unless the mod time has changed.
6726 */
6727 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006728 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006729 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006730 return SQLITE_IOERR_LOCK;
6731 }
6732
6733 if( nTries==1 ){
6734 conchModTime = buf.st_mtimespec;
6735 usleep(500000); /* wait 0.5 sec and try the lock again*/
6736 continue;
6737 }
6738
6739 assert( nTries>1 );
6740 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6741 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6742 return SQLITE_BUSY;
6743 }
6744
6745 if( nTries==2 ){
6746 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006747 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006748 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006749 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006750 return SQLITE_IOERR_LOCK;
6751 }
6752 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6753 /* don't break the lock if the host id doesn't match */
6754 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6755 return SQLITE_BUSY;
6756 }
6757 }else{
6758 /* don't break the lock on short read or a version mismatch */
6759 return SQLITE_BUSY;
6760 }
6761 usleep(10000000); /* wait 10 sec and try the lock again */
6762 continue;
6763 }
6764
6765 assert( nTries==3 );
6766 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6767 rc = SQLITE_OK;
6768 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006769 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006770 }
6771 if( !rc ){
6772 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6773 }
6774 }
6775 }
6776 } while( rc==SQLITE_BUSY && nTries<3 );
6777
6778 return rc;
6779}
6780
6781/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006782** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6783** lockPath means that the lockPath in the conch file will be used if the
6784** host IDs match, or a new lock path will be generated automatically
6785** and written to the conch file.
6786*/
6787static int proxyTakeConch(unixFile *pFile){
6788 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6789
drh7ed97b92010-01-20 13:07:21 +00006790 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006791 return SQLITE_OK;
6792 }else{
6793 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006794 uuid_t myHostID;
6795 int pError = 0;
6796 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006797 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006798 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006799 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006800 int createConch = 0;
6801 int hostIdMatch = 0;
6802 int readLen = 0;
6803 int tryOldLockPath = 0;
6804 int forceNewLockPath = 0;
6805
drh308c2a52010-05-14 11:30:18 +00006806 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6807 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006808
drh7ed97b92010-01-20 13:07:21 +00006809 rc = proxyGetHostID(myHostID, &pError);
6810 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006811 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006812 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006813 }
drh7ed97b92010-01-20 13:07:21 +00006814 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006815 if( rc!=SQLITE_OK ){
6816 goto end_takeconch;
6817 }
drh7ed97b92010-01-20 13:07:21 +00006818 /* read the existing conch file */
6819 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6820 if( readLen<0 ){
6821 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006822 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006823 rc = SQLITE_IOERR_READ;
6824 goto end_takeconch;
6825 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6826 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6827 /* a short read or version format mismatch means we need to create a new
6828 ** conch file.
6829 */
6830 createConch = 1;
6831 }
6832 /* if the host id matches and the lock path already exists in the conch
6833 ** we'll try to use the path there, if we can't open that path, we'll
6834 ** retry with a new auto-generated path
6835 */
6836 do { /* in case we need to try again for an :auto: named lock file */
6837
6838 if( !createConch && !forceNewLockPath ){
6839 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6840 PROXY_HOSTIDLEN);
6841 /* if the conch has data compare the contents */
6842 if( !pCtx->lockProxyPath ){
6843 /* for auto-named local lock file, just check the host ID and we'll
6844 ** use the local lock file path that's already in there
6845 */
6846 if( hostIdMatch ){
6847 size_t pathLen = (readLen - PROXY_PATHINDEX);
6848
6849 if( pathLen>=MAXPATHLEN ){
6850 pathLen=MAXPATHLEN-1;
6851 }
6852 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6853 lockPath[pathLen] = 0;
6854 tempLockPath = lockPath;
6855 tryOldLockPath = 1;
6856 /* create a copy of the lock path if the conch is taken */
6857 goto end_takeconch;
6858 }
6859 }else if( hostIdMatch
6860 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6861 readLen-PROXY_PATHINDEX)
6862 ){
6863 /* conch host and lock path match */
6864 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006865 }
drh7ed97b92010-01-20 13:07:21 +00006866 }
6867
6868 /* if the conch isn't writable and doesn't match, we can't take it */
6869 if( (conchFile->openFlags&O_RDWR) == 0 ){
6870 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006871 goto end_takeconch;
6872 }
drh7ed97b92010-01-20 13:07:21 +00006873
6874 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006875 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006876 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6877 tempLockPath = lockPath;
6878 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006879 }
drh7ed97b92010-01-20 13:07:21 +00006880
6881 /* update conch with host and path (this will fail if other process
6882 ** has a shared lock already), if the host id matches, use the big
6883 ** stick.
drh715ff302008-12-03 22:32:44 +00006884 */
drh7ed97b92010-01-20 13:07:21 +00006885 futimes(conchFile->h, NULL);
6886 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006887 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006888 /* We are trying for an exclusive lock but another thread in this
6889 ** same process is still holding a shared lock. */
6890 rc = SQLITE_BUSY;
6891 } else {
6892 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006893 }
drh715ff302008-12-03 22:32:44 +00006894 }else{
drh4bf66fd2015-02-19 02:43:02 +00006895 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006896 }
drh7ed97b92010-01-20 13:07:21 +00006897 if( rc==SQLITE_OK ){
6898 char writeBuffer[PROXY_MAXCONCHLEN];
6899 int writeSize = 0;
6900
6901 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6902 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6903 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006904 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6905 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006906 }else{
6907 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6908 }
6909 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006910 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006911 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6912 fsync(conchFile->h);
6913 /* If we created a new conch file (not just updated the contents of a
6914 ** valid conch file), try to match the permissions of the database
6915 */
6916 if( rc==SQLITE_OK && createConch ){
6917 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006918 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006919 if( err==0 ){
6920 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6921 S_IROTH|S_IWOTH);
6922 /* try to match the database file R/W permissions, ignore failure */
6923#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006924 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006925#else
drhff812312011-02-23 13:33:46 +00006926 do{
drhe562be52011-03-02 18:01:10 +00006927 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006928 }while( rc==(-1) && errno==EINTR );
6929 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006930 int code = errno;
6931 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6932 cmode, code, strerror(code));
6933 } else {
6934 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6935 }
6936 }else{
6937 int code = errno;
6938 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6939 err, code, strerror(code));
6940#endif
6941 }
drh715ff302008-12-03 22:32:44 +00006942 }
6943 }
drh7ed97b92010-01-20 13:07:21 +00006944 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6945
6946 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006947 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006948 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006949 int fd;
drh7ed97b92010-01-20 13:07:21 +00006950 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006951 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006952 }
6953 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006954 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006955 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006956 if( fd>=0 ){
6957 pFile->h = fd;
6958 }else{
drh9978c972010-02-23 17:36:32 +00006959 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006960 during locking */
6961 }
6962 }
6963 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6964 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6965 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6966 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6967 /* we couldn't create the proxy lock file with the old lock file path
6968 ** so try again via auto-naming
6969 */
6970 forceNewLockPath = 1;
6971 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006972 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006973 }
6974 }
6975 if( rc==SQLITE_OK ){
6976 /* Need to make a copy of path if we extracted the value
6977 ** from the conch file or the path was allocated on the stack
6978 */
6979 if( tempLockPath ){
6980 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6981 if( !pCtx->lockProxyPath ){
6982 rc = SQLITE_NOMEM;
6983 }
6984 }
6985 }
6986 if( rc==SQLITE_OK ){
6987 pCtx->conchHeld = 1;
6988
6989 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6990 afpLockingContext *afpCtx;
6991 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6992 afpCtx->dbPath = pCtx->lockProxyPath;
6993 }
6994 } else {
6995 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6996 }
drh308c2a52010-05-14 11:30:18 +00006997 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6998 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006999 return rc;
drh308c2a52010-05-14 11:30:18 +00007000 } while (1); /* in case we need to retry the :auto: lock file -
7001 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007002 }
7003}
7004
7005/*
7006** If pFile holds a lock on a conch file, then release that lock.
7007*/
7008static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007009 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007010 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7011 unixFile *conchFile; /* Name of the conch file */
7012
7013 pCtx = (proxyLockingContext *)pFile->lockingContext;
7014 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007015 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007016 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00007017 getpid()));
drh7ed97b92010-01-20 13:07:21 +00007018 if( pCtx->conchHeld>0 ){
7019 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7020 }
drh715ff302008-12-03 22:32:44 +00007021 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007022 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7023 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007024 return rc;
7025}
7026
7027/*
7028** Given the name of a database file, compute the name of its conch file.
7029** Store the conch filename in memory obtained from sqlite3_malloc().
7030** Make *pConchPath point to the new name. Return SQLITE_OK on success
7031** or SQLITE_NOMEM if unable to obtain memory.
7032**
7033** The caller is responsible for ensuring that the allocated memory
7034** space is eventually freed.
7035**
7036** *pConchPath is set to NULL if a memory allocation error occurs.
7037*/
7038static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7039 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007040 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007041 char *conchPath; /* buffer in which to construct conch name */
7042
7043 /* Allocate space for the conch filename and initialize the name to
7044 ** the name of the original database file. */
7045 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
7046 if( conchPath==0 ){
7047 return SQLITE_NOMEM;
7048 }
7049 memcpy(conchPath, dbPath, len+1);
7050
7051 /* now insert a "." before the last / character */
7052 for( i=(len-1); i>=0; i-- ){
7053 if( conchPath[i]=='/' ){
7054 i++;
7055 break;
7056 }
7057 }
7058 conchPath[i]='.';
7059 while ( i<len ){
7060 conchPath[i+1]=dbPath[i];
7061 i++;
7062 }
7063
7064 /* append the "-conch" suffix to the file */
7065 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007066 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007067
7068 return SQLITE_OK;
7069}
7070
7071
7072/* Takes a fully configured proxy locking-style unix file and switches
7073** the local lock file path
7074*/
7075static int switchLockProxyPath(unixFile *pFile, const char *path) {
7076 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7077 char *oldPath = pCtx->lockProxyPath;
7078 int rc = SQLITE_OK;
7079
drh308c2a52010-05-14 11:30:18 +00007080 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007081 return SQLITE_BUSY;
7082 }
7083
7084 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7085 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7086 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7087 return SQLITE_OK;
7088 }else{
7089 unixFile *lockProxy = pCtx->lockProxy;
7090 pCtx->lockProxy=NULL;
7091 pCtx->conchHeld = 0;
7092 if( lockProxy!=NULL ){
7093 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7094 if( rc ) return rc;
7095 sqlite3_free(lockProxy);
7096 }
7097 sqlite3_free(oldPath);
7098 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7099 }
7100
7101 return rc;
7102}
7103
7104/*
7105** pFile is a file that has been opened by a prior xOpen call. dbPath
7106** is a string buffer at least MAXPATHLEN+1 characters in size.
7107**
7108** This routine find the filename associated with pFile and writes it
7109** int dbPath.
7110*/
7111static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007112#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007113 if( pFile->pMethod == &afpIoMethods ){
7114 /* afp style keeps a reference to the db path in the filePath field
7115 ** of the struct */
drhea678832008-12-10 19:26:22 +00007116 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007117 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7118 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007119 } else
drh715ff302008-12-03 22:32:44 +00007120#endif
7121 if( pFile->pMethod == &dotlockIoMethods ){
7122 /* dot lock style uses the locking context to store the dot lock
7123 ** file path */
7124 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7125 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7126 }else{
7127 /* all other styles use the locking context to store the db file path */
7128 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007129 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007130 }
7131 return SQLITE_OK;
7132}
7133
7134/*
7135** Takes an already filled in unix file and alters it so all file locking
7136** will be performed on the local proxy lock file. The following fields
7137** are preserved in the locking context so that they can be restored and
7138** the unix structure properly cleaned up at close time:
7139** ->lockingContext
7140** ->pMethod
7141*/
7142static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7143 proxyLockingContext *pCtx;
7144 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7145 char *lockPath=NULL;
7146 int rc = SQLITE_OK;
7147
drh308c2a52010-05-14 11:30:18 +00007148 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007149 return SQLITE_BUSY;
7150 }
7151 proxyGetDbPathForUnixFile(pFile, dbPath);
7152 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7153 lockPath=NULL;
7154 }else{
7155 lockPath=(char *)path;
7156 }
7157
drh308c2a52010-05-14 11:30:18 +00007158 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7159 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007160
7161 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7162 if( pCtx==0 ){
7163 return SQLITE_NOMEM;
7164 }
7165 memset(pCtx, 0, sizeof(*pCtx));
7166
7167 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7168 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007169 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7170 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7171 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7172 ** (c) the file system is read-only, then enable no-locking access.
7173 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7174 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7175 */
7176 struct statfs fsInfo;
7177 struct stat conchInfo;
7178 int goLockless = 0;
7179
drh99ab3b12011-03-02 15:09:07 +00007180 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007181 int err = errno;
7182 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7183 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7184 }
7185 }
7186 if( goLockless ){
7187 pCtx->conchHeld = -1; /* read only FS/ lockless */
7188 rc = SQLITE_OK;
7189 }
7190 }
drh715ff302008-12-03 22:32:44 +00007191 }
7192 if( rc==SQLITE_OK && lockPath ){
7193 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7194 }
7195
7196 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007197 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7198 if( pCtx->dbPath==NULL ){
7199 rc = SQLITE_NOMEM;
7200 }
7201 }
7202 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007203 /* all memory is allocated, proxys are created and assigned,
7204 ** switch the locking context and pMethod then return.
7205 */
drh715ff302008-12-03 22:32:44 +00007206 pCtx->oldLockingContext = pFile->lockingContext;
7207 pFile->lockingContext = pCtx;
7208 pCtx->pOldMethod = pFile->pMethod;
7209 pFile->pMethod = &proxyIoMethods;
7210 }else{
7211 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007212 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007213 sqlite3_free(pCtx->conchFile);
7214 }
drhd56b1212010-08-11 06:14:15 +00007215 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007216 sqlite3_free(pCtx->conchFilePath);
7217 sqlite3_free(pCtx);
7218 }
drh308c2a52010-05-14 11:30:18 +00007219 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7220 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007221 return rc;
7222}
7223
7224
7225/*
7226** This routine handles sqlite3_file_control() calls that are specific
7227** to proxy locking.
7228*/
7229static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7230 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007231 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007232 unixFile *pFile = (unixFile*)id;
7233 if( pFile->pMethod == &proxyIoMethods ){
7234 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7235 proxyTakeConch(pFile);
7236 if( pCtx->lockProxyPath ){
7237 *(const char **)pArg = pCtx->lockProxyPath;
7238 }else{
7239 *(const char **)pArg = ":auto: (not held)";
7240 }
7241 } else {
7242 *(const char **)pArg = NULL;
7243 }
7244 return SQLITE_OK;
7245 }
drh4bf66fd2015-02-19 02:43:02 +00007246 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007247 unixFile *pFile = (unixFile*)id;
7248 int rc = SQLITE_OK;
7249 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7250 if( pArg==NULL || (const char *)pArg==0 ){
7251 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007252 /* turn off proxy locking - not supported. If support is added for
7253 ** switching proxy locking mode off then it will need to fail if
7254 ** the journal mode is WAL mode.
7255 */
drh715ff302008-12-03 22:32:44 +00007256 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7257 }else{
7258 /* turn off proxy locking - already off - NOOP */
7259 rc = SQLITE_OK;
7260 }
7261 }else{
7262 const char *proxyPath = (const char *)pArg;
7263 if( isProxyStyle ){
7264 proxyLockingContext *pCtx =
7265 (proxyLockingContext*)pFile->lockingContext;
7266 if( !strcmp(pArg, ":auto:")
7267 || (pCtx->lockProxyPath &&
7268 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7269 ){
7270 rc = SQLITE_OK;
7271 }else{
7272 rc = switchLockProxyPath(pFile, proxyPath);
7273 }
7274 }else{
7275 /* turn on proxy file locking */
7276 rc = proxyTransformUnixFile(pFile, proxyPath);
7277 }
7278 }
7279 return rc;
7280 }
7281 default: {
7282 assert( 0 ); /* The call assures that only valid opcodes are sent */
7283 }
7284 }
7285 /*NOTREACHED*/
7286 return SQLITE_ERROR;
7287}
7288
7289/*
7290** Within this division (the proxying locking implementation) the procedures
7291** above this point are all utilities. The lock-related methods of the
7292** proxy-locking sqlite3_io_method object follow.
7293*/
7294
7295
7296/*
7297** This routine checks if there is a RESERVED lock held on the specified
7298** file by this or any other process. If such a lock is held, set *pResOut
7299** to a non-zero value otherwise *pResOut is set to zero. The return value
7300** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7301*/
7302static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7303 unixFile *pFile = (unixFile*)id;
7304 int rc = proxyTakeConch(pFile);
7305 if( rc==SQLITE_OK ){
7306 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007307 if( pCtx->conchHeld>0 ){
7308 unixFile *proxy = pCtx->lockProxy;
7309 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7310 }else{ /* conchHeld < 0 is lockless */
7311 pResOut=0;
7312 }
drh715ff302008-12-03 22:32:44 +00007313 }
7314 return rc;
7315}
7316
7317/*
drh308c2a52010-05-14 11:30:18 +00007318** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007319** of the following:
7320**
7321** (1) SHARED_LOCK
7322** (2) RESERVED_LOCK
7323** (3) PENDING_LOCK
7324** (4) EXCLUSIVE_LOCK
7325**
7326** Sometimes when requesting one lock state, additional lock states
7327** are inserted in between. The locking might fail on one of the later
7328** transitions leaving the lock state different from what it started but
7329** still short of its goal. The following chart shows the allowed
7330** transitions and the inserted intermediate states:
7331**
7332** UNLOCKED -> SHARED
7333** SHARED -> RESERVED
7334** SHARED -> (PENDING) -> EXCLUSIVE
7335** RESERVED -> (PENDING) -> EXCLUSIVE
7336** PENDING -> EXCLUSIVE
7337**
7338** This routine will only increase a lock. Use the sqlite3OsUnlock()
7339** routine to lower a locking level.
7340*/
drh308c2a52010-05-14 11:30:18 +00007341static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007342 unixFile *pFile = (unixFile*)id;
7343 int rc = proxyTakeConch(pFile);
7344 if( rc==SQLITE_OK ){
7345 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007346 if( pCtx->conchHeld>0 ){
7347 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007348 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7349 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007350 }else{
7351 /* conchHeld < 0 is lockless */
7352 }
drh715ff302008-12-03 22:32:44 +00007353 }
7354 return rc;
7355}
7356
7357
7358/*
drh308c2a52010-05-14 11:30:18 +00007359** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007360** must be either NO_LOCK or SHARED_LOCK.
7361**
7362** If the locking level of the file descriptor is already at or below
7363** the requested locking level, this routine is a no-op.
7364*/
drh308c2a52010-05-14 11:30:18 +00007365static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007366 unixFile *pFile = (unixFile*)id;
7367 int rc = proxyTakeConch(pFile);
7368 if( rc==SQLITE_OK ){
7369 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007370 if( pCtx->conchHeld>0 ){
7371 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007372 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7373 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007374 }else{
7375 /* conchHeld < 0 is lockless */
7376 }
drh715ff302008-12-03 22:32:44 +00007377 }
7378 return rc;
7379}
7380
7381/*
7382** Close a file that uses proxy locks.
7383*/
7384static int proxyClose(sqlite3_file *id) {
7385 if( id ){
7386 unixFile *pFile = (unixFile*)id;
7387 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7388 unixFile *lockProxy = pCtx->lockProxy;
7389 unixFile *conchFile = pCtx->conchFile;
7390 int rc = SQLITE_OK;
7391
7392 if( lockProxy ){
7393 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7394 if( rc ) return rc;
7395 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7396 if( rc ) return rc;
7397 sqlite3_free(lockProxy);
7398 pCtx->lockProxy = 0;
7399 }
7400 if( conchFile ){
7401 if( pCtx->conchHeld ){
7402 rc = proxyReleaseConch(pFile);
7403 if( rc ) return rc;
7404 }
7405 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7406 if( rc ) return rc;
7407 sqlite3_free(conchFile);
7408 }
drhd56b1212010-08-11 06:14:15 +00007409 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007410 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007411 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007412 /* restore the original locking context and pMethod then close it */
7413 pFile->lockingContext = pCtx->oldLockingContext;
7414 pFile->pMethod = pCtx->pOldMethod;
7415 sqlite3_free(pCtx);
7416 return pFile->pMethod->xClose(id);
7417 }
7418 return SQLITE_OK;
7419}
7420
7421
7422
drhd2cb50b2009-01-09 21:41:17 +00007423#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007424/*
7425** The proxy locking style is intended for use with AFP filesystems.
7426** And since AFP is only supported on MacOSX, the proxy locking is also
7427** restricted to MacOSX.
7428**
7429**
7430******************* End of the proxy lock implementation **********************
7431******************************************************************************/
7432
drh734c9862008-11-28 15:37:20 +00007433/*
danielk1977e339d652008-06-28 11:23:00 +00007434** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007435**
7436** This routine registers all VFS implementations for unix-like operating
7437** systems. This routine, and the sqlite3_os_end() routine that follows,
7438** should be the only routines in this file that are visible from other
7439** files.
drh6b9d6dd2008-12-03 19:34:47 +00007440**
7441** This routine is called once during SQLite initialization and by a
7442** single thread. The memory allocation and mutex subsystems have not
7443** necessarily been initialized when this routine is called, and so they
7444** should not be used.
drh153c62c2007-08-24 03:51:33 +00007445*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007446int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007447 /*
7448 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007449 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7450 ** to the "finder" function. (pAppData is a pointer to a pointer because
7451 ** silly C90 rules prohibit a void* from being cast to a function pointer
7452 ** and so we have to go through the intermediate pointer to avoid problems
7453 ** when compiling with -pedantic-errors on GCC.)
7454 **
7455 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007456 ** finder-function. The finder-function returns a pointer to the
7457 ** sqlite_io_methods object that implements the desired locking
7458 ** behaviors. See the division above that contains the IOMETHODS
7459 ** macro for addition information on finder-functions.
7460 **
7461 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7462 ** object. But the "autolockIoFinder" available on MacOSX does a little
7463 ** more than that; it looks at the filesystem type that hosts the
7464 ** database file and tries to choose an locking method appropriate for
7465 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007466 */
drh7708e972008-11-29 00:56:52 +00007467 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007468 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007469 sizeof(unixFile), /* szOsFile */ \
7470 MAX_PATHNAME, /* mxPathname */ \
7471 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007472 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007473 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007474 unixOpen, /* xOpen */ \
7475 unixDelete, /* xDelete */ \
7476 unixAccess, /* xAccess */ \
7477 unixFullPathname, /* xFullPathname */ \
7478 unixDlOpen, /* xDlOpen */ \
7479 unixDlError, /* xDlError */ \
7480 unixDlSym, /* xDlSym */ \
7481 unixDlClose, /* xDlClose */ \
7482 unixRandomness, /* xRandomness */ \
7483 unixSleep, /* xSleep */ \
7484 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007485 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007486 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007487 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007488 unixGetSystemCall, /* xGetSystemCall */ \
7489 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007490 }
7491
drh6b9d6dd2008-12-03 19:34:47 +00007492 /*
7493 ** All default VFSes for unix are contained in the following array.
7494 **
7495 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7496 ** by the SQLite core when the VFS is registered. So the following
7497 ** array cannot be const.
7498 */
danielk1977e339d652008-06-28 11:23:00 +00007499 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007500#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007501 UNIXVFS("unix", autolockIoFinder ),
7502#else
7503 UNIXVFS("unix", posixIoFinder ),
7504#endif
7505 UNIXVFS("unix-none", nolockIoFinder ),
7506 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007507 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007508#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007509 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007510#endif
7511#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007512 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007513#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007514 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007515#endif
chw78a13182009-04-07 05:35:03 +00007516#endif
drhd2cb50b2009-01-09 21:41:17 +00007517#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007518 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007519 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007520 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007521#endif
drh153c62c2007-08-24 03:51:33 +00007522 };
drh6b9d6dd2008-12-03 19:34:47 +00007523 unsigned int i; /* Loop counter */
7524
drh2aa5a002011-04-13 13:42:25 +00007525 /* Double-check that the aSyscall[] array has been constructed
7526 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007527 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007528
drh6b9d6dd2008-12-03 19:34:47 +00007529 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007530 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007531 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007532 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007533 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007534}
danielk1977e339d652008-06-28 11:23:00 +00007535
7536/*
drh6b9d6dd2008-12-03 19:34:47 +00007537** Shutdown the operating system interface.
7538**
7539** Some operating systems might need to do some cleanup in this routine,
7540** to release dynamically allocated objects. But not on unix.
7541** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007542*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007543int sqlite3_os_end(void){
7544 return SQLITE_OK;
7545}
drhdce8bdb2007-08-16 13:01:44 +00007546
danielk197729bafea2008-06-26 10:41:19 +00007547#endif /* SQLITE_OS_UNIX */