blob: d80a706b9383178f57c1acbcd4d4529d0c88ba02 [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 */
drhfbc7e882013-04-11 01:16:15 +0000257#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been 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
642** binaries. This returns the string represetation of the supplied
643** 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**
720** All calls to ftruncate() within this file should be made through this wrapper.
721** On the Android platform, bypassing the logic below could lead to a corrupt
722** 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
729 ** truncate a file to any size smaller than 2GiB. Silently ignore any
730 ** 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/*
danb0ac3e32010-06-16 10:55:42 +00001182** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001183*/
drh0e9365c2011-03-02 02:08:13 +00001184static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001185 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001186 UnixUnusedFd *p;
1187 UnixUnusedFd *pNext;
1188 for(p=pInode->pUnused; p; p=pNext){
1189 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001190 robust_close(pFile, p->fd, __LINE__);
1191 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001192 }
drh0e9365c2011-03-02 02:08:13 +00001193 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001194}
1195
1196/*
drh8af6c222010-05-14 12:43:01 +00001197** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001198**
1199** The mutex entered using the unixEnterMutex() function must be held
1200** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001201*/
danb0ac3e32010-06-16 10:55:42 +00001202static void releaseInodeInfo(unixFile *pFile){
1203 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001204 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001205 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001206 pInode->nRef--;
1207 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001208 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001209 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001210 if( pInode->pPrev ){
1211 assert( pInode->pPrev->pNext==pInode );
1212 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001213 }else{
drh8af6c222010-05-14 12:43:01 +00001214 assert( inodeList==pInode );
1215 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001216 }
drh8af6c222010-05-14 12:43:01 +00001217 if( pInode->pNext ){
1218 assert( pInode->pNext->pPrev==pInode );
1219 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001220 }
drh8af6c222010-05-14 12:43:01 +00001221 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001222 }
drhbbd42a62004-05-22 17:41:58 +00001223 }
1224}
1225
1226/*
drh8af6c222010-05-14 12:43:01 +00001227** Given a file descriptor, locate the unixInodeInfo object that
1228** describes that file descriptor. Create a new one if necessary. The
1229** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001230**
dan9359c7b2009-08-21 08:29:10 +00001231** The mutex entered using the unixEnterMutex() function must be held
1232** when this function is called.
1233**
drh6c7d5c52008-11-21 20:32:33 +00001234** Return an appropriate error code.
1235*/
drh8af6c222010-05-14 12:43:01 +00001236static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001237 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001238 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001239){
1240 int rc; /* System call return code */
1241 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001242 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1243 struct stat statbuf; /* Low-level file information */
1244 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001245
dan9359c7b2009-08-21 08:29:10 +00001246 assert( unixMutexHeld() );
1247
drh6c7d5c52008-11-21 20:32:33 +00001248 /* Get low-level information about the file that we can used to
1249 ** create a unique name for the file.
1250 */
1251 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001252 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001253 if( rc!=0 ){
1254 pFile->lastErrno = errno;
1255#ifdef EOVERFLOW
1256 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1257#endif
1258 return SQLITE_IOERR;
1259 }
1260
drheb0d74f2009-02-03 15:27:02 +00001261#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001262 /* On OS X on an msdos filesystem, the inode number is reported
1263 ** incorrectly for zero-size files. See ticket #3260. To work
1264 ** around this problem (we consider it a bug in OS X, not SQLite)
1265 ** we always increase the file size to 1 by writing a single byte
1266 ** prior to accessing the inode number. The one byte written is
1267 ** an ASCII 'S' character which also happens to be the first byte
1268 ** in the header of every SQLite database. In this way, if there
1269 ** is a race condition such that another thread has already populated
1270 ** the first page of the database, no damage is done.
1271 */
drh7ed97b92010-01-20 13:07:21 +00001272 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001273 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001274 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001275 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001276 return SQLITE_IOERR;
1277 }
drh99ab3b12011-03-02 15:09:07 +00001278 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001279 if( rc!=0 ){
1280 pFile->lastErrno = errno;
1281 return SQLITE_IOERR;
1282 }
1283 }
drheb0d74f2009-02-03 15:27:02 +00001284#endif
drh6c7d5c52008-11-21 20:32:33 +00001285
drh8af6c222010-05-14 12:43:01 +00001286 memset(&fileId, 0, sizeof(fileId));
1287 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001288#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001289 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001290#else
drh8af6c222010-05-14 12:43:01 +00001291 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001292#endif
drh8af6c222010-05-14 12:43:01 +00001293 pInode = inodeList;
1294 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1295 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001296 }
drh8af6c222010-05-14 12:43:01 +00001297 if( pInode==0 ){
1298 pInode = sqlite3_malloc( sizeof(*pInode) );
1299 if( pInode==0 ){
1300 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001301 }
drh8af6c222010-05-14 12:43:01 +00001302 memset(pInode, 0, sizeof(*pInode));
1303 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1304 pInode->nRef = 1;
1305 pInode->pNext = inodeList;
1306 pInode->pPrev = 0;
1307 if( inodeList ) inodeList->pPrev = pInode;
1308 inodeList = pInode;
1309 }else{
1310 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001311 }
drh8af6c222010-05-14 12:43:01 +00001312 *ppInode = pInode;
1313 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001314}
drh6c7d5c52008-11-21 20:32:33 +00001315
drhb959a012013-12-07 12:29:22 +00001316/*
1317** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1318*/
1319static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001320#if OS_VXWORKS
1321 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1322#else
drhb959a012013-12-07 12:29:22 +00001323 struct stat buf;
1324 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001325 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001326#endif
drhb959a012013-12-07 12:29:22 +00001327}
1328
aswift5b1a2562008-08-22 00:22:35 +00001329
1330/*
drhfbc7e882013-04-11 01:16:15 +00001331** Check a unixFile that is a database. Verify the following:
1332**
1333** (1) There is exactly one hard link on the file
1334** (2) The file is not a symbolic link
1335** (3) The file has not been renamed or unlinked
1336**
1337** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1338*/
1339static void verifyDbFile(unixFile *pFile){
1340 struct stat buf;
1341 int rc;
drh3044b512014-06-16 16:41:52 +00001342 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1343 /* One or more of the following warnings have already been issued. Do not
1344 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001345 return;
1346 }
1347 rc = osFstat(pFile->h, &buf);
1348 if( rc!=0 ){
1349 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1350 pFile->ctrlFlags |= UNIXFILE_WARNED;
1351 return;
1352 }
drh3044b512014-06-16 16:41:52 +00001353 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001354 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1355 pFile->ctrlFlags |= UNIXFILE_WARNED;
1356 return;
1357 }
1358 if( buf.st_nlink>1 ){
1359 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1360 pFile->ctrlFlags |= UNIXFILE_WARNED;
1361 return;
1362 }
drhb959a012013-12-07 12:29:22 +00001363 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001364 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1365 pFile->ctrlFlags |= UNIXFILE_WARNED;
1366 return;
1367 }
1368}
1369
1370
1371/*
danielk197713adf8a2004-06-03 16:08:41 +00001372** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001373** file by this or any other process. If such a lock is held, set *pResOut
1374** to a non-zero value otherwise *pResOut is set to zero. The return value
1375** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001376*/
danielk1977861f7452008-06-05 11:39:11 +00001377static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001378 int rc = SQLITE_OK;
1379 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001380 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001381
danielk1977861f7452008-06-05 11:39:11 +00001382 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1383
drh054889e2005-11-30 03:20:31 +00001384 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001385 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001386
1387 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001388 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001389 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001390 }
1391
drh2ac3ee92004-06-07 16:27:46 +00001392 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001393 */
danielk197709480a92009-02-09 05:32:32 +00001394#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001395 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001396 struct flock lock;
1397 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001398 lock.l_start = RESERVED_BYTE;
1399 lock.l_len = 1;
1400 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001401 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1402 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1403 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001404 } else if( lock.l_type!=F_UNLCK ){
1405 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001406 }
1407 }
danielk197709480a92009-02-09 05:32:32 +00001408#endif
danielk197713adf8a2004-06-03 16:08:41 +00001409
drh6c7d5c52008-11-21 20:32:33 +00001410 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001411 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001412
aswift5b1a2562008-08-22 00:22:35 +00001413 *pResOut = reserved;
1414 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001415}
1416
1417/*
drha7e61d82011-03-12 17:02:57 +00001418** Attempt to set a system-lock on the file pFile. The lock is
1419** described by pLock.
1420**
drh77197112011-03-15 19:08:48 +00001421** If the pFile was opened read/write from unix-excl, then the only lock
1422** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001423** the first time any lock is attempted. All subsequent system locking
1424** operations become no-ops. Locking operations still happen internally,
1425** in order to coordinate access between separate database connections
1426** within this process, but all of that is handled in memory and the
1427** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001428**
1429** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1430** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1431** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001432**
1433** Zero is returned if the call completes successfully, or -1 if a call
1434** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001435*/
1436static int unixFileLock(unixFile *pFile, struct flock *pLock){
1437 int rc;
drh3cb93392011-03-12 18:10:44 +00001438 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001439 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001440 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001441 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1442 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1443 ){
drh3cb93392011-03-12 18:10:44 +00001444 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001445 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001446 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001447 lock.l_whence = SEEK_SET;
1448 lock.l_start = SHARED_FIRST;
1449 lock.l_len = SHARED_SIZE;
1450 lock.l_type = F_WRLCK;
1451 rc = osFcntl(pFile->h, F_SETLK, &lock);
1452 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001453 pInode->bProcessLock = 1;
1454 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001455 }else{
1456 rc = 0;
1457 }
1458 }else{
1459 rc = osFcntl(pFile->h, F_SETLK, pLock);
1460 }
1461 return rc;
1462}
1463
1464/*
drh308c2a52010-05-14 11:30:18 +00001465** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001466** of the following:
1467**
drh2ac3ee92004-06-07 16:27:46 +00001468** (1) SHARED_LOCK
1469** (2) RESERVED_LOCK
1470** (3) PENDING_LOCK
1471** (4) EXCLUSIVE_LOCK
1472**
drhb3e04342004-06-08 00:47:47 +00001473** Sometimes when requesting one lock state, additional lock states
1474** are inserted in between. The locking might fail on one of the later
1475** transitions leaving the lock state different from what it started but
1476** still short of its goal. The following chart shows the allowed
1477** transitions and the inserted intermediate states:
1478**
1479** UNLOCKED -> SHARED
1480** SHARED -> RESERVED
1481** SHARED -> (PENDING) -> EXCLUSIVE
1482** RESERVED -> (PENDING) -> EXCLUSIVE
1483** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001484**
drha6abd042004-06-09 17:37:22 +00001485** This routine will only increase a lock. Use the sqlite3OsUnlock()
1486** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001487*/
drh308c2a52010-05-14 11:30:18 +00001488static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001489 /* The following describes the implementation of the various locks and
1490 ** lock transitions in terms of the POSIX advisory shared and exclusive
1491 ** lock primitives (called read-locks and write-locks below, to avoid
1492 ** confusion with SQLite lock names). The algorithms are complicated
1493 ** slightly in order to be compatible with windows systems simultaneously
1494 ** accessing the same database file, in case that is ever required.
1495 **
1496 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1497 ** byte', each single bytes at well known offsets, and the 'shared byte
1498 ** range', a range of 510 bytes at a well known offset.
1499 **
1500 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1501 ** byte'. If this is successful, a random byte from the 'shared byte
1502 ** range' is read-locked and the lock on the 'pending byte' released.
1503 **
danielk197790ba3bd2004-06-25 08:32:25 +00001504 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1505 ** A RESERVED lock is implemented by grabbing a write-lock on the
1506 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001507 **
1508 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001509 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1510 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1511 ** obtained, but existing SHARED locks are allowed to persist. A process
1512 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1513 ** This property is used by the algorithm for rolling back a journal file
1514 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001515 **
danielk197790ba3bd2004-06-25 08:32:25 +00001516 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1517 ** implemented by obtaining a write-lock on the entire 'shared byte
1518 ** range'. Since all other locks require a read-lock on one of the bytes
1519 ** within this range, this ensures that no other locks are held on the
1520 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001521 **
1522 ** The reason a single byte cannot be used instead of the 'shared byte
1523 ** range' is that some versions of windows do not support read-locks. By
1524 ** locking a random byte from a range, concurrent SHARED locks may exist
1525 ** even if the locking primitive used is always a write-lock.
1526 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001527 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001528 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001529 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001530 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001531 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001532
drh054889e2005-11-30 03:20:31 +00001533 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001534 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1535 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001536 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001537
1538 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001539 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001540 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001541 */
drh308c2a52010-05-14 11:30:18 +00001542 if( pFile->eFileLock>=eFileLock ){
1543 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1544 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001545 return SQLITE_OK;
1546 }
1547
drh0c2694b2009-09-03 16:23:44 +00001548 /* Make sure the locking sequence is correct.
1549 ** (1) We never move from unlocked to anything higher than shared lock.
1550 ** (2) SQLite never explicitly requests a pendig lock.
1551 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001552 */
drh308c2a52010-05-14 11:30:18 +00001553 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1554 assert( eFileLock!=PENDING_LOCK );
1555 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001556
drh8af6c222010-05-14 12:43:01 +00001557 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001558 */
drh6c7d5c52008-11-21 20:32:33 +00001559 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001560 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001561
danielk1977ad94b582007-08-20 06:44:22 +00001562 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001563 ** handle that precludes the requested lock, return BUSY.
1564 */
drh8af6c222010-05-14 12:43:01 +00001565 if( (pFile->eFileLock!=pInode->eFileLock &&
1566 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001567 ){
1568 rc = SQLITE_BUSY;
1569 goto end_lock;
1570 }
1571
1572 /* If a SHARED lock is requested, and some thread using this PID already
1573 ** has a SHARED or RESERVED lock, then increment reference counts and
1574 ** return SQLITE_OK.
1575 */
drh308c2a52010-05-14 11:30:18 +00001576 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001577 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001578 assert( eFileLock==SHARED_LOCK );
1579 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001580 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001581 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001582 pInode->nShared++;
1583 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001584 goto end_lock;
1585 }
1586
danielk19779a1d0ab2004-06-01 14:09:28 +00001587
drh3cde3bb2004-06-12 02:17:14 +00001588 /* A PENDING lock is needed before acquiring a SHARED lock and before
1589 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1590 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001591 */
drh0c2694b2009-09-03 16:23:44 +00001592 lock.l_len = 1L;
1593 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001594 if( eFileLock==SHARED_LOCK
1595 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001596 ){
drh308c2a52010-05-14 11:30:18 +00001597 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001598 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001599 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001600 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001601 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001602 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001603 pFile->lastErrno = tErrno;
1604 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001605 goto end_lock;
1606 }
drh3cde3bb2004-06-12 02:17:14 +00001607 }
1608
1609
1610 /* If control gets to this point, then actually go ahead and make
1611 ** operating system calls for the specified lock.
1612 */
drh308c2a52010-05-14 11:30:18 +00001613 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001614 assert( pInode->nShared==0 );
1615 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001616 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001617
drh2ac3ee92004-06-07 16:27:46 +00001618 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001619 lock.l_start = SHARED_FIRST;
1620 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001621 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001622 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001623 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001624 }
dan661d71a2011-03-30 19:08:03 +00001625
drh2ac3ee92004-06-07 16:27:46 +00001626 /* Drop the temporary PENDING lock */
1627 lock.l_start = PENDING_BYTE;
1628 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001629 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001630 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1631 /* This could happen with a network mount */
1632 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001633 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001634 }
dan661d71a2011-03-30 19:08:03 +00001635
1636 if( rc ){
1637 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001638 pFile->lastErrno = tErrno;
1639 }
dan661d71a2011-03-30 19:08:03 +00001640 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001641 }else{
drh308c2a52010-05-14 11:30:18 +00001642 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001643 pInode->nLock++;
1644 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001645 }
drh8af6c222010-05-14 12:43:01 +00001646 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001647 /* We are trying for an exclusive lock but another thread in this
1648 ** same process is still holding a shared lock. */
1649 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001650 }else{
drh3cde3bb2004-06-12 02:17:14 +00001651 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001652 ** assumed that there is a SHARED or greater lock on the file
1653 ** already.
1654 */
drh308c2a52010-05-14 11:30:18 +00001655 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001656 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001657
1658 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1659 if( eFileLock==RESERVED_LOCK ){
1660 lock.l_start = RESERVED_BYTE;
1661 lock.l_len = 1L;
1662 }else{
1663 lock.l_start = SHARED_FIRST;
1664 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001665 }
dan661d71a2011-03-30 19:08:03 +00001666
1667 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001668 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001669 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001670 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001671 pFile->lastErrno = tErrno;
1672 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001673 }
drhbbd42a62004-05-22 17:41:58 +00001674 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001675
drh8f941bc2009-01-14 23:03:40 +00001676
drhd3d8c042012-05-29 17:02:40 +00001677#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001678 /* Set up the transaction-counter change checking flags when
1679 ** transitioning from a SHARED to a RESERVED lock. The change
1680 ** from SHARED to RESERVED marks the beginning of a normal
1681 ** write operation (not a hot journal rollback).
1682 */
1683 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001684 && pFile->eFileLock<=SHARED_LOCK
1685 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001686 ){
1687 pFile->transCntrChng = 0;
1688 pFile->dbUpdate = 0;
1689 pFile->inNormalWrite = 1;
1690 }
1691#endif
1692
1693
danielk1977ecb2a962004-06-02 06:30:16 +00001694 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001695 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001696 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001697 }else if( eFileLock==EXCLUSIVE_LOCK ){
1698 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001699 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001700 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001701
1702end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001703 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001704 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1705 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001706 return rc;
1707}
1708
1709/*
dan08da86a2009-08-21 17:18:03 +00001710** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001711** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001712*/
1713static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001714 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001715 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001716 p->pNext = pInode->pUnused;
1717 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001718 pFile->h = -1;
1719 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001720}
1721
1722/*
drh308c2a52010-05-14 11:30:18 +00001723** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001724** must be either NO_LOCK or SHARED_LOCK.
1725**
1726** If the locking level of the file descriptor is already at or below
1727** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001728**
1729** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1730** the byte range is divided into 2 parts and the first part is unlocked then
1731** set to a read lock, then the other part is simply unlocked. This works
1732** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1733** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001734*/
drha7e61d82011-03-12 17:02:57 +00001735static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001736 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001737 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001738 struct flock lock;
1739 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001740
drh054889e2005-11-30 03:20:31 +00001741 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001742 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001743 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001744 getpid()));
drha6abd042004-06-09 17:37:22 +00001745
drh308c2a52010-05-14 11:30:18 +00001746 assert( eFileLock<=SHARED_LOCK );
1747 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001748 return SQLITE_OK;
1749 }
drh6c7d5c52008-11-21 20:32:33 +00001750 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001751 pInode = pFile->pInode;
1752 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001753 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001754 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001755
drhd3d8c042012-05-29 17:02:40 +00001756#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001757 /* When reducing a lock such that other processes can start
1758 ** reading the database file again, make sure that the
1759 ** transaction counter was updated if any part of the database
1760 ** file changed. If the transaction counter is not updated,
1761 ** other connections to the same file might not realize that
1762 ** the file has changed and hence might not know to flush their
1763 ** cache. The use of a stale cache can lead to database corruption.
1764 */
drh8f941bc2009-01-14 23:03:40 +00001765 pFile->inNormalWrite = 0;
1766#endif
1767
drh7ed97b92010-01-20 13:07:21 +00001768 /* downgrading to a shared lock on NFS involves clearing the write lock
1769 ** before establishing the readlock - to avoid a race condition we downgrade
1770 ** the lock in 2 blocks, so that part of the range will be covered by a
1771 ** write lock until the rest is covered by a read lock:
1772 ** 1: [WWWWW]
1773 ** 2: [....W]
1774 ** 3: [RRRRW]
1775 ** 4: [RRRR.]
1776 */
drh308c2a52010-05-14 11:30:18 +00001777 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001778
1779#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001780 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001781 assert( handleNFSUnlock==0 );
1782#endif
1783#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001784 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001785 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001786 off_t divSize = SHARED_SIZE - 1;
1787
1788 lock.l_type = F_UNLCK;
1789 lock.l_whence = SEEK_SET;
1790 lock.l_start = SHARED_FIRST;
1791 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001792 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001793 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001794 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001795 if( IS_LOCK_ERROR(rc) ){
1796 pFile->lastErrno = tErrno;
1797 }
1798 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001799 }
drh7ed97b92010-01-20 13:07:21 +00001800 lock.l_type = F_RDLCK;
1801 lock.l_whence = SEEK_SET;
1802 lock.l_start = SHARED_FIRST;
1803 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001804 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001805 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001806 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1807 if( IS_LOCK_ERROR(rc) ){
1808 pFile->lastErrno = tErrno;
1809 }
1810 goto end_unlock;
1811 }
1812 lock.l_type = F_UNLCK;
1813 lock.l_whence = SEEK_SET;
1814 lock.l_start = SHARED_FIRST+divSize;
1815 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001816 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001817 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001818 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001819 if( IS_LOCK_ERROR(rc) ){
1820 pFile->lastErrno = tErrno;
1821 }
1822 goto end_unlock;
1823 }
drh30f776f2011-02-25 03:25:07 +00001824 }else
1825#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1826 {
drh7ed97b92010-01-20 13:07:21 +00001827 lock.l_type = F_RDLCK;
1828 lock.l_whence = SEEK_SET;
1829 lock.l_start = SHARED_FIRST;
1830 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001831 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001832 /* In theory, the call to unixFileLock() cannot fail because another
1833 ** process is holding an incompatible lock. If it does, this
1834 ** indicates that the other process is not following the locking
1835 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1836 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1837 ** an assert to fail). */
1838 rc = SQLITE_IOERR_RDLOCK;
1839 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001840 goto end_unlock;
1841 }
drh9c105bb2004-10-02 20:38:28 +00001842 }
1843 }
drhbbd42a62004-05-22 17:41:58 +00001844 lock.l_type = F_UNLCK;
1845 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001846 lock.l_start = PENDING_BYTE;
1847 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001848 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001849 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001850 }else{
danea83bc62011-04-01 11:56:32 +00001851 rc = SQLITE_IOERR_UNLOCK;
1852 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001853 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001854 }
drhbbd42a62004-05-22 17:41:58 +00001855 }
drh308c2a52010-05-14 11:30:18 +00001856 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001857 /* Decrement the shared lock counter. Release the lock using an
1858 ** OS call only when all threads in this same process have released
1859 ** the lock.
1860 */
drh8af6c222010-05-14 12:43:01 +00001861 pInode->nShared--;
1862 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001863 lock.l_type = F_UNLCK;
1864 lock.l_whence = SEEK_SET;
1865 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001866 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001867 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001868 }else{
danea83bc62011-04-01 11:56:32 +00001869 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001870 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001871 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001872 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001873 }
drha6abd042004-06-09 17:37:22 +00001874 }
1875
drhbbd42a62004-05-22 17:41:58 +00001876 /* Decrement the count of locks against this same file. When the
1877 ** count reaches zero, close any other file descriptors whose close
1878 ** was deferred because of outstanding locks.
1879 */
drh8af6c222010-05-14 12:43:01 +00001880 pInode->nLock--;
1881 assert( pInode->nLock>=0 );
1882 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001883 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001884 }
1885 }
drhf2f105d2012-08-20 15:53:54 +00001886
aswift5b1a2562008-08-22 00:22:35 +00001887end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001888 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001889 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001890 return rc;
drhbbd42a62004-05-22 17:41:58 +00001891}
1892
1893/*
drh308c2a52010-05-14 11:30:18 +00001894** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001895** must be either NO_LOCK or SHARED_LOCK.
1896**
1897** If the locking level of the file descriptor is already at or below
1898** the requested locking level, this routine is a no-op.
1899*/
drh308c2a52010-05-14 11:30:18 +00001900static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001901#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001902 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001903#endif
drha7e61d82011-03-12 17:02:57 +00001904 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001905}
1906
mistachkine98844f2013-08-24 00:59:24 +00001907#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001908static int unixMapfile(unixFile *pFd, i64 nByte);
1909static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001910#endif
danf23da962013-03-23 21:00:41 +00001911
drh7ed97b92010-01-20 13:07:21 +00001912/*
danielk1977e339d652008-06-28 11:23:00 +00001913** This function performs the parts of the "close file" operation
1914** common to all locking schemes. It closes the directory and file
1915** handles, if they are valid, and sets all fields of the unixFile
1916** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001917**
1918** It is *not* necessary to hold the mutex when this routine is called,
1919** even on VxWorks. A mutex will be acquired on VxWorks by the
1920** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001921*/
1922static int closeUnixFile(sqlite3_file *id){
1923 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001924#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001925 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001926#endif
dan661d71a2011-03-30 19:08:03 +00001927 if( pFile->h>=0 ){
1928 robust_close(pFile, pFile->h, __LINE__);
1929 pFile->h = -1;
1930 }
1931#if OS_VXWORKS
1932 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001933 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001934 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001935 }
1936 vxworksReleaseFileId(pFile->pId);
1937 pFile->pId = 0;
1938 }
1939#endif
drh0bdbc902014-06-16 18:35:06 +00001940#ifdef SQLITE_UNLINK_AFTER_CLOSE
1941 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1942 osUnlink(pFile->zPath);
1943 sqlite3_free(*(char**)&pFile->zPath);
1944 pFile->zPath = 0;
1945 }
1946#endif
dan661d71a2011-03-30 19:08:03 +00001947 OSTRACE(("CLOSE %-3d\n", pFile->h));
1948 OpenCounter(-1);
1949 sqlite3_free(pFile->pUnused);
1950 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001951 return SQLITE_OK;
1952}
1953
1954/*
danielk1977e3026632004-06-22 11:29:02 +00001955** Close a file.
1956*/
danielk197762079062007-08-15 17:08:46 +00001957static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001958 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001959 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001960 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001961 unixUnlock(id, NO_LOCK);
1962 unixEnterMutex();
1963
1964 /* unixFile.pInode is always valid here. Otherwise, a different close
1965 ** routine (e.g. nolockClose()) would be called instead.
1966 */
1967 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1968 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1969 /* If there are outstanding locks, do not actually close the file just
1970 ** yet because that would clear those locks. Instead, add the file
1971 ** descriptor to pInode->pUnused list. It will be automatically closed
1972 ** when the last lock is cleared.
1973 */
1974 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001975 }
dan661d71a2011-03-30 19:08:03 +00001976 releaseInodeInfo(pFile);
1977 rc = closeUnixFile(id);
1978 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001979 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001980}
1981
drh734c9862008-11-28 15:37:20 +00001982/************** End of the posix advisory lock implementation *****************
1983******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001984
drh734c9862008-11-28 15:37:20 +00001985/******************************************************************************
1986****************************** No-op Locking **********************************
1987**
1988** Of the various locking implementations available, this is by far the
1989** simplest: locking is ignored. No attempt is made to lock the database
1990** file for reading or writing.
1991**
1992** This locking mode is appropriate for use on read-only databases
1993** (ex: databases that are burned into CD-ROM, for example.) It can
1994** also be used if the application employs some external mechanism to
1995** prevent simultaneous access of the same database by two or more
1996** database connections. But there is a serious risk of database
1997** corruption if this locking mode is used in situations where multiple
1998** database connections are accessing the same database file at the same
1999** time and one or more of those connections are writing.
2000*/
drhbfe66312006-10-03 17:40:40 +00002001
drh734c9862008-11-28 15:37:20 +00002002static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2003 UNUSED_PARAMETER(NotUsed);
2004 *pResOut = 0;
2005 return SQLITE_OK;
2006}
drh734c9862008-11-28 15:37:20 +00002007static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2008 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2009 return SQLITE_OK;
2010}
drh734c9862008-11-28 15:37:20 +00002011static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2012 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2013 return SQLITE_OK;
2014}
2015
2016/*
drh9b35ea62008-11-29 02:20:26 +00002017** Close the file.
drh734c9862008-11-28 15:37:20 +00002018*/
2019static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002020 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002021}
2022
2023/******************* End of the no-op lock implementation *********************
2024******************************************************************************/
2025
2026/******************************************************************************
2027************************* Begin dot-file Locking ******************************
2028**
mistachkin48864df2013-03-21 21:20:32 +00002029** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002030** files (really a directory) to control access to the database. This works
2031** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002032**
2033** (1) There is zero concurrency. A single reader blocks all other
2034** connections from reading or writing the database.
2035**
2036** (2) An application crash or power loss can leave stale lock files
2037** sitting around that need to be cleared manually.
2038**
2039** Nevertheless, a dotlock is an appropriate locking mode for use if no
2040** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002041**
drh9ef6bc42011-11-04 02:24:02 +00002042** Dotfile locking works by creating a subdirectory in the same directory as
2043** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002044** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002045** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002046*/
2047
2048/*
2049** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002050** lock directory.
drh734c9862008-11-28 15:37:20 +00002051*/
2052#define DOTLOCK_SUFFIX ".lock"
2053
drh7708e972008-11-29 00:56:52 +00002054/*
2055** This routine checks if there is a RESERVED lock held on the specified
2056** file by this or any other process. If such a lock is held, set *pResOut
2057** to a non-zero value otherwise *pResOut is set to zero. The return value
2058** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2059**
2060** In dotfile locking, either a lock exists or it does not. So in this
2061** variation of CheckReservedLock(), *pResOut is set to true if any lock
2062** is held on the file and false if the file is unlocked.
2063*/
drh734c9862008-11-28 15:37:20 +00002064static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2065 int rc = SQLITE_OK;
2066 int reserved = 0;
2067 unixFile *pFile = (unixFile*)id;
2068
2069 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2070
2071 assert( pFile );
2072
2073 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002074 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002075 /* Either this connection or some other connection in the same process
2076 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002077 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002078 }else{
2079 /* The lock is held if and only if the lockfile exists */
2080 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002081 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002082 }
drh308c2a52010-05-14 11:30:18 +00002083 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002084 *pResOut = reserved;
2085 return rc;
2086}
2087
drh7708e972008-11-29 00:56:52 +00002088/*
drh308c2a52010-05-14 11:30:18 +00002089** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002090** of the following:
2091**
2092** (1) SHARED_LOCK
2093** (2) RESERVED_LOCK
2094** (3) PENDING_LOCK
2095** (4) EXCLUSIVE_LOCK
2096**
2097** Sometimes when requesting one lock state, additional lock states
2098** are inserted in between. The locking might fail on one of the later
2099** transitions leaving the lock state different from what it started but
2100** still short of its goal. The following chart shows the allowed
2101** transitions and the inserted intermediate states:
2102**
2103** UNLOCKED -> SHARED
2104** SHARED -> RESERVED
2105** SHARED -> (PENDING) -> EXCLUSIVE
2106** RESERVED -> (PENDING) -> EXCLUSIVE
2107** PENDING -> EXCLUSIVE
2108**
2109** This routine will only increase a lock. Use the sqlite3OsUnlock()
2110** routine to lower a locking level.
2111**
2112** With dotfile locking, we really only support state (4): EXCLUSIVE.
2113** But we track the other locking levels internally.
2114*/
drh308c2a52010-05-14 11:30:18 +00002115static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002116 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002117 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002118 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002119
drh7708e972008-11-29 00:56:52 +00002120
2121 /* If we have any lock, then the lock file already exists. All we have
2122 ** to do is adjust our internal record of the lock level.
2123 */
drh308c2a52010-05-14 11:30:18 +00002124 if( pFile->eFileLock > NO_LOCK ){
2125 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002126 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002127#ifdef HAVE_UTIME
2128 utime(zLockFile, NULL);
2129#else
drh734c9862008-11-28 15:37:20 +00002130 utimes(zLockFile, NULL);
2131#endif
drh7708e972008-11-29 00:56:52 +00002132 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002133 }
2134
2135 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002136 rc = osMkdir(zLockFile, 0777);
2137 if( rc<0 ){
2138 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002139 int tErrno = errno;
2140 if( EEXIST == tErrno ){
2141 rc = SQLITE_BUSY;
2142 } else {
2143 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2144 if( IS_LOCK_ERROR(rc) ){
2145 pFile->lastErrno = tErrno;
2146 }
2147 }
drh7708e972008-11-29 00:56:52 +00002148 return rc;
drh734c9862008-11-28 15:37:20 +00002149 }
drh734c9862008-11-28 15:37:20 +00002150
2151 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002152 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002153 return rc;
2154}
2155
drh7708e972008-11-29 00:56:52 +00002156/*
drh308c2a52010-05-14 11:30:18 +00002157** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002158** must be either NO_LOCK or SHARED_LOCK.
2159**
2160** If the locking level of the file descriptor is already at or below
2161** the requested locking level, this routine is a no-op.
2162**
2163** When the locking level reaches NO_LOCK, delete the lock file.
2164*/
drh308c2a52010-05-14 11:30:18 +00002165static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002166 unixFile *pFile = (unixFile*)id;
2167 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002168 int rc;
drh734c9862008-11-28 15:37:20 +00002169
2170 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002171 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002172 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002173 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002174
2175 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002176 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002177 return SQLITE_OK;
2178 }
drh7708e972008-11-29 00:56:52 +00002179
2180 /* To downgrade to shared, simply update our internal notion of the
2181 ** lock state. No need to mess with the file on disk.
2182 */
drh308c2a52010-05-14 11:30:18 +00002183 if( eFileLock==SHARED_LOCK ){
2184 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002185 return SQLITE_OK;
2186 }
2187
drh7708e972008-11-29 00:56:52 +00002188 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002189 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002190 rc = osRmdir(zLockFile);
2191 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2192 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002193 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002194 rc = 0;
drh734c9862008-11-28 15:37:20 +00002195 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002196 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002197 }
2198 if( IS_LOCK_ERROR(rc) ){
2199 pFile->lastErrno = tErrno;
2200 }
2201 return rc;
2202 }
drh308c2a52010-05-14 11:30:18 +00002203 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002204 return SQLITE_OK;
2205}
2206
2207/*
drh9b35ea62008-11-29 02:20:26 +00002208** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002209*/
2210static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002211 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002212 if( id ){
2213 unixFile *pFile = (unixFile*)id;
2214 dotlockUnlock(id, NO_LOCK);
2215 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002216 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002217 }
drh734c9862008-11-28 15:37:20 +00002218 return rc;
2219}
2220/****************** End of the dot-file lock implementation *******************
2221******************************************************************************/
2222
2223/******************************************************************************
2224************************** Begin flock Locking ********************************
2225**
2226** Use the flock() system call to do file locking.
2227**
drh6b9d6dd2008-12-03 19:34:47 +00002228** flock() locking is like dot-file locking in that the various
2229** fine-grain locking levels supported by SQLite are collapsed into
2230** a single exclusive lock. In other words, SHARED, RESERVED, and
2231** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2232** still works when you do this, but concurrency is reduced since
2233** only a single process can be reading the database at a time.
2234**
drh734c9862008-11-28 15:37:20 +00002235** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2236** compiling for VXWORKS.
2237*/
2238#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002239
drh6b9d6dd2008-12-03 19:34:47 +00002240/*
drhff812312011-02-23 13:33:46 +00002241** Retry flock() calls that fail with EINTR
2242*/
2243#ifdef EINTR
2244static int robust_flock(int fd, int op){
2245 int rc;
2246 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2247 return rc;
2248}
2249#else
drh5c819272011-02-23 14:00:12 +00002250# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002251#endif
2252
2253
2254/*
drh6b9d6dd2008-12-03 19:34:47 +00002255** This routine checks if there is a RESERVED lock held on the specified
2256** file by this or any other process. If such a lock is held, set *pResOut
2257** to a non-zero value otherwise *pResOut is set to zero. The return value
2258** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2259*/
drh734c9862008-11-28 15:37:20 +00002260static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2261 int rc = SQLITE_OK;
2262 int reserved = 0;
2263 unixFile *pFile = (unixFile*)id;
2264
2265 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2266
2267 assert( pFile );
2268
2269 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002270 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002271 reserved = 1;
2272 }
2273
2274 /* Otherwise see if some other process holds it. */
2275 if( !reserved ){
2276 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002277 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002278 if( !lrc ){
2279 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002280 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002281 if ( lrc ) {
2282 int tErrno = errno;
2283 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002284 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002285 if( IS_LOCK_ERROR(lrc) ){
2286 pFile->lastErrno = tErrno;
2287 rc = lrc;
2288 }
2289 }
2290 } else {
2291 int tErrno = errno;
2292 reserved = 1;
2293 /* someone else might have it reserved */
2294 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2295 if( IS_LOCK_ERROR(lrc) ){
2296 pFile->lastErrno = tErrno;
2297 rc = lrc;
2298 }
2299 }
2300 }
drh308c2a52010-05-14 11:30:18 +00002301 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002302
2303#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2304 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2305 rc = SQLITE_OK;
2306 reserved=1;
2307 }
2308#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2309 *pResOut = reserved;
2310 return rc;
2311}
2312
drh6b9d6dd2008-12-03 19:34:47 +00002313/*
drh308c2a52010-05-14 11:30:18 +00002314** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002315** of the following:
2316**
2317** (1) SHARED_LOCK
2318** (2) RESERVED_LOCK
2319** (3) PENDING_LOCK
2320** (4) EXCLUSIVE_LOCK
2321**
2322** Sometimes when requesting one lock state, additional lock states
2323** are inserted in between. The locking might fail on one of the later
2324** transitions leaving the lock state different from what it started but
2325** still short of its goal. The following chart shows the allowed
2326** transitions and the inserted intermediate states:
2327**
2328** UNLOCKED -> SHARED
2329** SHARED -> RESERVED
2330** SHARED -> (PENDING) -> EXCLUSIVE
2331** RESERVED -> (PENDING) -> EXCLUSIVE
2332** PENDING -> EXCLUSIVE
2333**
2334** flock() only really support EXCLUSIVE locks. We track intermediate
2335** lock states in the sqlite3_file structure, but all locks SHARED or
2336** above are really EXCLUSIVE locks and exclude all other processes from
2337** access the file.
2338**
2339** This routine will only increase a lock. Use the sqlite3OsUnlock()
2340** routine to lower a locking level.
2341*/
drh308c2a52010-05-14 11:30:18 +00002342static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002343 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002344 unixFile *pFile = (unixFile*)id;
2345
2346 assert( pFile );
2347
2348 /* if we already have a lock, it is exclusive.
2349 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002350 if (pFile->eFileLock > NO_LOCK) {
2351 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002352 return SQLITE_OK;
2353 }
2354
2355 /* grab an exclusive lock */
2356
drhff812312011-02-23 13:33:46 +00002357 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002358 int tErrno = errno;
2359 /* didn't get, must be busy */
2360 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2361 if( IS_LOCK_ERROR(rc) ){
2362 pFile->lastErrno = tErrno;
2363 }
2364 } else {
2365 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002366 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002367 }
drh308c2a52010-05-14 11:30:18 +00002368 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2369 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002370#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2371 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2372 rc = SQLITE_BUSY;
2373 }
2374#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2375 return rc;
2376}
2377
drh6b9d6dd2008-12-03 19:34:47 +00002378
2379/*
drh308c2a52010-05-14 11:30:18 +00002380** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002381** must be either NO_LOCK or SHARED_LOCK.
2382**
2383** If the locking level of the file descriptor is already at or below
2384** the requested locking level, this routine is a no-op.
2385*/
drh308c2a52010-05-14 11:30:18 +00002386static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002387 unixFile *pFile = (unixFile*)id;
2388
2389 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002390 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2391 pFile->eFileLock, getpid()));
2392 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002393
2394 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002395 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002396 return SQLITE_OK;
2397 }
2398
2399 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002400 if (eFileLock==SHARED_LOCK) {
2401 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002402 return SQLITE_OK;
2403 }
2404
2405 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002406 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002407#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002408 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002409#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002410 return SQLITE_IOERR_UNLOCK;
2411 }else{
drh308c2a52010-05-14 11:30:18 +00002412 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002413 return SQLITE_OK;
2414 }
2415}
2416
2417/*
2418** Close a file.
2419*/
2420static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002421 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002422 if( id ){
2423 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002424 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002425 }
drh5a05be12012-10-09 18:51:44 +00002426 return rc;
drh734c9862008-11-28 15:37:20 +00002427}
2428
2429#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2430
2431/******************* End of the flock lock implementation *********************
2432******************************************************************************/
2433
2434/******************************************************************************
2435************************ Begin Named Semaphore Locking ************************
2436**
2437** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002438**
2439** Semaphore locking is like dot-lock and flock in that it really only
2440** supports EXCLUSIVE locking. Only a single process can read or write
2441** the database file at a time. This reduces potential concurrency, but
2442** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002443*/
2444#if OS_VXWORKS
2445
drh6b9d6dd2008-12-03 19:34:47 +00002446/*
2447** This routine checks if there is a RESERVED lock held on the specified
2448** file by this or any other process. If such a lock is held, set *pResOut
2449** to a non-zero value otherwise *pResOut is set to zero. The return value
2450** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2451*/
drh734c9862008-11-28 15:37:20 +00002452static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2453 int rc = SQLITE_OK;
2454 int reserved = 0;
2455 unixFile *pFile = (unixFile*)id;
2456
2457 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2458
2459 assert( pFile );
2460
2461 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002462 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002463 reserved = 1;
2464 }
2465
2466 /* Otherwise see if some other process holds it. */
2467 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002468 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002469
2470 if( sem_trywait(pSem)==-1 ){
2471 int tErrno = errno;
2472 if( EAGAIN != tErrno ){
2473 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2474 pFile->lastErrno = tErrno;
2475 } else {
2476 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002477 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002478 }
2479 }else{
2480 /* we could have it if we want it */
2481 sem_post(pSem);
2482 }
2483 }
drh308c2a52010-05-14 11:30:18 +00002484 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002485
2486 *pResOut = reserved;
2487 return rc;
2488}
2489
drh6b9d6dd2008-12-03 19:34:47 +00002490/*
drh308c2a52010-05-14 11:30:18 +00002491** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002492** of the following:
2493**
2494** (1) SHARED_LOCK
2495** (2) RESERVED_LOCK
2496** (3) PENDING_LOCK
2497** (4) EXCLUSIVE_LOCK
2498**
2499** Sometimes when requesting one lock state, additional lock states
2500** are inserted in between. The locking might fail on one of the later
2501** transitions leaving the lock state different from what it started but
2502** still short of its goal. The following chart shows the allowed
2503** transitions and the inserted intermediate states:
2504**
2505** UNLOCKED -> SHARED
2506** SHARED -> RESERVED
2507** SHARED -> (PENDING) -> EXCLUSIVE
2508** RESERVED -> (PENDING) -> EXCLUSIVE
2509** PENDING -> EXCLUSIVE
2510**
2511** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2512** lock states in the sqlite3_file structure, but all locks SHARED or
2513** above are really EXCLUSIVE locks and exclude all other processes from
2514** access the file.
2515**
2516** This routine will only increase a lock. Use the sqlite3OsUnlock()
2517** routine to lower a locking level.
2518*/
drh308c2a52010-05-14 11:30:18 +00002519static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002520 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002521 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002522 int rc = SQLITE_OK;
2523
2524 /* if we already have a lock, it is exclusive.
2525 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002526 if (pFile->eFileLock > NO_LOCK) {
2527 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002528 rc = SQLITE_OK;
2529 goto sem_end_lock;
2530 }
2531
2532 /* lock semaphore now but bail out when already locked. */
2533 if( sem_trywait(pSem)==-1 ){
2534 rc = SQLITE_BUSY;
2535 goto sem_end_lock;
2536 }
2537
2538 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002539 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002540
2541 sem_end_lock:
2542 return rc;
2543}
2544
drh6b9d6dd2008-12-03 19:34:47 +00002545/*
drh308c2a52010-05-14 11:30:18 +00002546** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002547** must be either NO_LOCK or SHARED_LOCK.
2548**
2549** If the locking level of the file descriptor is already at or below
2550** the requested locking level, this routine is a no-op.
2551*/
drh308c2a52010-05-14 11:30:18 +00002552static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002553 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002554 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002555
2556 assert( pFile );
2557 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002558 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002559 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002560 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002561
2562 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002563 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002564 return SQLITE_OK;
2565 }
2566
2567 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002568 if (eFileLock==SHARED_LOCK) {
2569 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002570 return SQLITE_OK;
2571 }
2572
2573 /* no, really unlock. */
2574 if ( sem_post(pSem)==-1 ) {
2575 int rc, tErrno = errno;
2576 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2577 if( IS_LOCK_ERROR(rc) ){
2578 pFile->lastErrno = tErrno;
2579 }
2580 return rc;
2581 }
drh308c2a52010-05-14 11:30:18 +00002582 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002583 return SQLITE_OK;
2584}
2585
2586/*
2587 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002588 */
drh734c9862008-11-28 15:37:20 +00002589static int semClose(sqlite3_file *id) {
2590 if( id ){
2591 unixFile *pFile = (unixFile*)id;
2592 semUnlock(id, NO_LOCK);
2593 assert( pFile );
2594 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002595 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002596 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002597 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002598 }
2599 return SQLITE_OK;
2600}
2601
2602#endif /* OS_VXWORKS */
2603/*
2604** Named semaphore locking is only available on VxWorks.
2605**
2606*************** End of the named semaphore lock implementation ****************
2607******************************************************************************/
2608
2609
2610/******************************************************************************
2611*************************** Begin AFP Locking *********************************
2612**
2613** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2614** on Apple Macintosh computers - both OS9 and OSX.
2615**
2616** Third-party implementations of AFP are available. But this code here
2617** only works on OSX.
2618*/
2619
drhd2cb50b2009-01-09 21:41:17 +00002620#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002621/*
2622** The afpLockingContext structure contains all afp lock specific state
2623*/
drhbfe66312006-10-03 17:40:40 +00002624typedef struct afpLockingContext afpLockingContext;
2625struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002626 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002627 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002628};
2629
2630struct ByteRangeLockPB2
2631{
2632 unsigned long long offset; /* offset to first byte to lock */
2633 unsigned long long length; /* nbr of bytes to lock */
2634 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2635 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2636 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2637 int fd; /* file desc to assoc this lock with */
2638};
2639
drhfd131da2007-08-07 17:13:03 +00002640#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002641
drh6b9d6dd2008-12-03 19:34:47 +00002642/*
2643** This is a utility for setting or clearing a bit-range lock on an
2644** AFP filesystem.
2645**
2646** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2647*/
2648static int afpSetLock(
2649 const char *path, /* Name of the file to be locked or unlocked */
2650 unixFile *pFile, /* Open file descriptor on path */
2651 unsigned long long offset, /* First byte to be locked */
2652 unsigned long long length, /* Number of bytes to lock */
2653 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002654){
drh6b9d6dd2008-12-03 19:34:47 +00002655 struct ByteRangeLockPB2 pb;
2656 int err;
drhbfe66312006-10-03 17:40:40 +00002657
2658 pb.unLockFlag = setLockFlag ? 0 : 1;
2659 pb.startEndFlag = 0;
2660 pb.offset = offset;
2661 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002662 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002663
drh308c2a52010-05-14 11:30:18 +00002664 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002665 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002666 offset, length));
drhbfe66312006-10-03 17:40:40 +00002667 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2668 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002669 int rc;
2670 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002671 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2672 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002673#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2674 rc = SQLITE_BUSY;
2675#else
drh734c9862008-11-28 15:37:20 +00002676 rc = sqliteErrorFromPosixError(tErrno,
2677 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002678#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002679 if( IS_LOCK_ERROR(rc) ){
2680 pFile->lastErrno = tErrno;
2681 }
2682 return rc;
drhbfe66312006-10-03 17:40:40 +00002683 } else {
aswift5b1a2562008-08-22 00:22:35 +00002684 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002685 }
2686}
2687
drh6b9d6dd2008-12-03 19:34:47 +00002688/*
2689** This routine checks if there is a RESERVED lock held on the specified
2690** file by this or any other process. If such a lock is held, set *pResOut
2691** to a non-zero value otherwise *pResOut is set to zero. The return value
2692** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2693*/
danielk1977e339d652008-06-28 11:23:00 +00002694static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002695 int rc = SQLITE_OK;
2696 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002697 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002698 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002699
aswift5b1a2562008-08-22 00:22:35 +00002700 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2701
2702 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002703 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002704 if( context->reserved ){
2705 *pResOut = 1;
2706 return SQLITE_OK;
2707 }
drh8af6c222010-05-14 12:43:01 +00002708 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002709
2710 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002711 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002712 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002713 }
2714
2715 /* Otherwise see if some other process holds it.
2716 */
aswift5b1a2562008-08-22 00:22:35 +00002717 if( !reserved ){
2718 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002719 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002720 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002721 /* if we succeeded in taking the reserved lock, unlock it to restore
2722 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002723 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002724 } else {
2725 /* if we failed to get the lock then someone else must have it */
2726 reserved = 1;
2727 }
2728 if( IS_LOCK_ERROR(lrc) ){
2729 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002730 }
2731 }
drhbfe66312006-10-03 17:40:40 +00002732
drh7ed97b92010-01-20 13:07:21 +00002733 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002734 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002735
2736 *pResOut = reserved;
2737 return rc;
drhbfe66312006-10-03 17:40:40 +00002738}
2739
drh6b9d6dd2008-12-03 19:34:47 +00002740/*
drh308c2a52010-05-14 11:30:18 +00002741** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002742** of the following:
2743**
2744** (1) SHARED_LOCK
2745** (2) RESERVED_LOCK
2746** (3) PENDING_LOCK
2747** (4) EXCLUSIVE_LOCK
2748**
2749** Sometimes when requesting one lock state, additional lock states
2750** are inserted in between. The locking might fail on one of the later
2751** transitions leaving the lock state different from what it started but
2752** still short of its goal. The following chart shows the allowed
2753** transitions and the inserted intermediate states:
2754**
2755** UNLOCKED -> SHARED
2756** SHARED -> RESERVED
2757** SHARED -> (PENDING) -> EXCLUSIVE
2758** RESERVED -> (PENDING) -> EXCLUSIVE
2759** PENDING -> EXCLUSIVE
2760**
2761** This routine will only increase a lock. Use the sqlite3OsUnlock()
2762** routine to lower a locking level.
2763*/
drh308c2a52010-05-14 11:30:18 +00002764static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002765 int rc = SQLITE_OK;
2766 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002767 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002768 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002769
2770 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002771 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2772 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002773 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002774
drhbfe66312006-10-03 17:40:40 +00002775 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002776 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002777 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002778 */
drh308c2a52010-05-14 11:30:18 +00002779 if( pFile->eFileLock>=eFileLock ){
2780 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2781 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002782 return SQLITE_OK;
2783 }
2784
2785 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002786 ** (1) We never move from unlocked to anything higher than shared lock.
2787 ** (2) SQLite never explicitly requests a pendig lock.
2788 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002789 */
drh308c2a52010-05-14 11:30:18 +00002790 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2791 assert( eFileLock!=PENDING_LOCK );
2792 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002793
drh8af6c222010-05-14 12:43:01 +00002794 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002795 */
drh6c7d5c52008-11-21 20:32:33 +00002796 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002797 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002798
2799 /* If some thread using this PID has a lock via a different unixFile*
2800 ** handle that precludes the requested lock, return BUSY.
2801 */
drh8af6c222010-05-14 12:43:01 +00002802 if( (pFile->eFileLock!=pInode->eFileLock &&
2803 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002804 ){
2805 rc = SQLITE_BUSY;
2806 goto afp_end_lock;
2807 }
2808
2809 /* If a SHARED lock is requested, and some thread using this PID already
2810 ** has a SHARED or RESERVED lock, then increment reference counts and
2811 ** return SQLITE_OK.
2812 */
drh308c2a52010-05-14 11:30:18 +00002813 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002814 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002815 assert( eFileLock==SHARED_LOCK );
2816 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002817 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002818 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002819 pInode->nShared++;
2820 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002821 goto afp_end_lock;
2822 }
drhbfe66312006-10-03 17:40:40 +00002823
2824 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002825 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2826 ** be released.
2827 */
drh308c2a52010-05-14 11:30:18 +00002828 if( eFileLock==SHARED_LOCK
2829 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002830 ){
2831 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002832 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002833 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002834 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002835 goto afp_end_lock;
2836 }
2837 }
2838
2839 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002840 ** operating system calls for the specified lock.
2841 */
drh308c2a52010-05-14 11:30:18 +00002842 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002843 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002844 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002845
drh8af6c222010-05-14 12:43:01 +00002846 assert( pInode->nShared==0 );
2847 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002848
2849 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002850 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002851 /* note that the quality of the randomness doesn't matter that much */
2852 lk = random();
drh8af6c222010-05-14 12:43:01 +00002853 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002854 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002855 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002856 if( IS_LOCK_ERROR(lrc1) ){
2857 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002858 }
aswift5b1a2562008-08-22 00:22:35 +00002859 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002860 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002861
aswift5b1a2562008-08-22 00:22:35 +00002862 if( IS_LOCK_ERROR(lrc1) ) {
2863 pFile->lastErrno = lrc1Errno;
2864 rc = lrc1;
2865 goto afp_end_lock;
2866 } else if( IS_LOCK_ERROR(lrc2) ){
2867 rc = lrc2;
2868 goto afp_end_lock;
2869 } else if( lrc1 != SQLITE_OK ) {
2870 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002871 } else {
drh308c2a52010-05-14 11:30:18 +00002872 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002873 pInode->nLock++;
2874 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002875 }
drh8af6c222010-05-14 12:43:01 +00002876 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002877 /* We are trying for an exclusive lock but another thread in this
2878 ** same process is still holding a shared lock. */
2879 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002880 }else{
2881 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2882 ** assumed that there is a SHARED or greater lock on the file
2883 ** already.
2884 */
2885 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002886 assert( 0!=pFile->eFileLock );
2887 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002888 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002889 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002890 if( !failed ){
2891 context->reserved = 1;
2892 }
drhbfe66312006-10-03 17:40:40 +00002893 }
drh308c2a52010-05-14 11:30:18 +00002894 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002895 /* Acquire an EXCLUSIVE lock */
2896
2897 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002898 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002899 */
drh6b9d6dd2008-12-03 19:34:47 +00002900 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002901 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002902 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002903 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002904 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002905 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002906 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002907 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002908 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2909 ** a critical I/O error
2910 */
2911 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2912 SQLITE_IOERR_LOCK;
2913 goto afp_end_lock;
2914 }
2915 }else{
aswift5b1a2562008-08-22 00:22:35 +00002916 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002917 }
2918 }
aswift5b1a2562008-08-22 00:22:35 +00002919 if( failed ){
2920 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002921 }
2922 }
2923
2924 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002925 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002926 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002927 }else if( eFileLock==EXCLUSIVE_LOCK ){
2928 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002929 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002930 }
2931
2932afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002933 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002934 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2935 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002936 return rc;
2937}
2938
2939/*
drh308c2a52010-05-14 11:30:18 +00002940** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002941** must be either NO_LOCK or SHARED_LOCK.
2942**
2943** If the locking level of the file descriptor is already at or below
2944** the requested locking level, this routine is a no-op.
2945*/
drh308c2a52010-05-14 11:30:18 +00002946static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002947 int rc = SQLITE_OK;
2948 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002949 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002950 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2951 int skipShared = 0;
2952#ifdef SQLITE_TEST
2953 int h = pFile->h;
2954#endif
drhbfe66312006-10-03 17:40:40 +00002955
2956 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002957 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002958 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002959 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002960
drh308c2a52010-05-14 11:30:18 +00002961 assert( eFileLock<=SHARED_LOCK );
2962 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002963 return SQLITE_OK;
2964 }
drh6c7d5c52008-11-21 20:32:33 +00002965 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002966 pInode = pFile->pInode;
2967 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002968 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002969 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002970 SimulateIOErrorBenign(1);
2971 SimulateIOError( h=(-1) )
2972 SimulateIOErrorBenign(0);
2973
drhd3d8c042012-05-29 17:02:40 +00002974#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002975 /* When reducing a lock such that other processes can start
2976 ** reading the database file again, make sure that the
2977 ** transaction counter was updated if any part of the database
2978 ** file changed. If the transaction counter is not updated,
2979 ** other connections to the same file might not realize that
2980 ** the file has changed and hence might not know to flush their
2981 ** cache. The use of a stale cache can lead to database corruption.
2982 */
2983 assert( pFile->inNormalWrite==0
2984 || pFile->dbUpdate==0
2985 || pFile->transCntrChng==1 );
2986 pFile->inNormalWrite = 0;
2987#endif
aswiftaebf4132008-11-21 00:10:35 +00002988
drh308c2a52010-05-14 11:30:18 +00002989 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002990 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002991 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002992 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002993 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002994 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2995 } else {
2996 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002997 }
2998 }
drh308c2a52010-05-14 11:30:18 +00002999 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003000 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003001 }
drh308c2a52010-05-14 11:30:18 +00003002 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003003 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3004 if( !rc ){
3005 context->reserved = 0;
3006 }
aswiftaebf4132008-11-21 00:10:35 +00003007 }
drh8af6c222010-05-14 12:43:01 +00003008 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3009 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003010 }
aswiftaebf4132008-11-21 00:10:35 +00003011 }
drh308c2a52010-05-14 11:30:18 +00003012 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003013
drh7ed97b92010-01-20 13:07:21 +00003014 /* Decrement the shared lock counter. Release the lock using an
3015 ** OS call only when all threads in this same process have released
3016 ** the lock.
3017 */
drh8af6c222010-05-14 12:43:01 +00003018 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3019 pInode->nShared--;
3020 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003021 SimulateIOErrorBenign(1);
3022 SimulateIOError( h=(-1) )
3023 SimulateIOErrorBenign(0);
3024 if( !skipShared ){
3025 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3026 }
3027 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003028 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003029 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003030 }
3031 }
3032 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003033 pInode->nLock--;
3034 assert( pInode->nLock>=0 );
3035 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003036 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003037 }
3038 }
drhbfe66312006-10-03 17:40:40 +00003039 }
drh7ed97b92010-01-20 13:07:21 +00003040
drh6c7d5c52008-11-21 20:32:33 +00003041 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003042 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003043 return rc;
3044}
3045
3046/*
drh339eb0b2008-03-07 15:34:11 +00003047** Close a file & cleanup AFP specific locking context
3048*/
danielk1977e339d652008-06-28 11:23:00 +00003049static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003050 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003051 if( id ){
3052 unixFile *pFile = (unixFile*)id;
3053 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003054 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003055 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003056 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003057 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003058 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003059 ** the last lock is cleared.
3060 */
dan08da86a2009-08-21 17:18:03 +00003061 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003062 }
danb0ac3e32010-06-16 10:55:42 +00003063 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003064 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003065 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003066 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003067 }
drh7ed97b92010-01-20 13:07:21 +00003068 return rc;
drhbfe66312006-10-03 17:40:40 +00003069}
3070
drhd2cb50b2009-01-09 21:41:17 +00003071#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003072/*
3073** The code above is the AFP lock implementation. The code is specific
3074** to MacOSX and does not work on other unix platforms. No alternative
3075** is available. If you don't compile for a mac, then the "unix-afp"
3076** VFS is not available.
3077**
3078********************* End of the AFP lock implementation **********************
3079******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003080
drh7ed97b92010-01-20 13:07:21 +00003081/******************************************************************************
3082*************************** Begin NFS Locking ********************************/
3083
3084#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3085/*
drh308c2a52010-05-14 11:30:18 +00003086 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003087 ** must be either NO_LOCK or SHARED_LOCK.
3088 **
3089 ** If the locking level of the file descriptor is already at or below
3090 ** the requested locking level, this routine is a no-op.
3091 */
drh308c2a52010-05-14 11:30:18 +00003092static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003093 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003094}
3095
3096#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3097/*
3098** The code above is the NFS lock implementation. The code is specific
3099** to MacOSX and does not work on other unix platforms. No alternative
3100** is available.
3101**
3102********************* End of the NFS lock implementation **********************
3103******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003104
3105/******************************************************************************
3106**************** Non-locking sqlite3_file methods *****************************
3107**
3108** The next division contains implementations for all methods of the
3109** sqlite3_file object other than the locking methods. The locking
3110** methods were defined in divisions above (one locking method per
3111** division). Those methods that are common to all locking modes
3112** are gather together into this division.
3113*/
drhbfe66312006-10-03 17:40:40 +00003114
3115/*
drh734c9862008-11-28 15:37:20 +00003116** Seek to the offset passed as the second argument, then read cnt
3117** bytes into pBuf. Return the number of bytes actually read.
3118**
3119** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3120** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3121** one system to another. Since SQLite does not define USE_PREAD
3122** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3123** See tickets #2741 and #2681.
3124**
3125** To avoid stomping the errno value on a failed read the lastErrno value
3126** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003127*/
drh734c9862008-11-28 15:37:20 +00003128static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3129 int got;
drh58024642011-11-07 18:16:00 +00003130 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003131#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003132 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003133#endif
drh734c9862008-11-28 15:37:20 +00003134 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003135 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003136 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003137 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003138 do{
drh734c9862008-11-28 15:37:20 +00003139#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003140 got = osPread(id->h, pBuf, cnt, offset);
3141 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003142#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003143 got = osPread64(id->h, pBuf, cnt, offset);
3144 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003145#else
drh58024642011-11-07 18:16:00 +00003146 newOffset = lseek(id->h, offset, SEEK_SET);
3147 SimulateIOError( newOffset-- );
3148 if( newOffset!=offset ){
3149 if( newOffset == -1 ){
3150 ((unixFile*)id)->lastErrno = errno;
3151 }else{
drhf2f105d2012-08-20 15:53:54 +00003152 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003153 }
3154 return -1;
drh734c9862008-11-28 15:37:20 +00003155 }
drh58024642011-11-07 18:16:00 +00003156 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003157#endif
drh58024642011-11-07 18:16:00 +00003158 if( got==cnt ) break;
3159 if( got<0 ){
3160 if( errno==EINTR ){ got = 1; continue; }
3161 prior = 0;
3162 ((unixFile*)id)->lastErrno = errno;
3163 break;
3164 }else if( got>0 ){
3165 cnt -= got;
3166 offset += got;
3167 prior += got;
3168 pBuf = (void*)(got + (char*)pBuf);
3169 }
3170 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003171 TIMER_END;
drh58024642011-11-07 18:16:00 +00003172 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3173 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3174 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003175}
3176
3177/*
drh734c9862008-11-28 15:37:20 +00003178** Read data from a file into a buffer. Return SQLITE_OK if all
3179** bytes were read successfully and SQLITE_IOERR if anything goes
3180** wrong.
drh339eb0b2008-03-07 15:34:11 +00003181*/
drh734c9862008-11-28 15:37:20 +00003182static int unixRead(
3183 sqlite3_file *id,
3184 void *pBuf,
3185 int amt,
3186 sqlite3_int64 offset
3187){
dan08da86a2009-08-21 17:18:03 +00003188 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003189 int got;
3190 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003191 assert( offset>=0 );
3192 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003193
dan08da86a2009-08-21 17:18:03 +00003194 /* If this is a database file (not a journal, master-journal or temp
3195 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003196#if 0
dane946c392009-08-22 11:39:46 +00003197 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003198 || offset>=PENDING_BYTE+512
3199 || offset+amt<=PENDING_BYTE
3200 );
dan7c246102010-04-12 19:00:29 +00003201#endif
drh08c6d442009-02-09 17:34:07 +00003202
drh9b4c59f2013-04-15 17:03:42 +00003203#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003204 /* Deal with as much of this read request as possible by transfering
3205 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003206 if( offset<pFile->mmapSize ){
3207 if( offset+amt <= pFile->mmapSize ){
3208 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3209 return SQLITE_OK;
3210 }else{
3211 int nCopy = pFile->mmapSize - offset;
3212 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3213 pBuf = &((u8 *)pBuf)[nCopy];
3214 amt -= nCopy;
3215 offset += nCopy;
3216 }
3217 }
drh6e0b6d52013-04-09 16:19:20 +00003218#endif
danf23da962013-03-23 21:00:41 +00003219
dan08da86a2009-08-21 17:18:03 +00003220 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003221 if( got==amt ){
3222 return SQLITE_OK;
3223 }else if( got<0 ){
3224 /* lastErrno set by seekAndRead */
3225 return SQLITE_IOERR_READ;
3226 }else{
dan08da86a2009-08-21 17:18:03 +00003227 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003228 /* Unread parts of the buffer must be zero-filled */
3229 memset(&((char*)pBuf)[got], 0, amt-got);
3230 return SQLITE_IOERR_SHORT_READ;
3231 }
3232}
3233
3234/*
dan47a2b4a2013-04-26 16:09:29 +00003235** Attempt to seek the file-descriptor passed as the first argument to
3236** absolute offset iOff, then attempt to write nBuf bytes of data from
3237** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3238** return the actual number of bytes written (which may be less than
3239** nBuf).
3240*/
3241static int seekAndWriteFd(
3242 int fd, /* File descriptor to write to */
3243 i64 iOff, /* File offset to begin writing at */
3244 const void *pBuf, /* Copy data from this buffer to the file */
3245 int nBuf, /* Size of buffer pBuf in bytes */
3246 int *piErrno /* OUT: Error number if error occurs */
3247){
3248 int rc = 0; /* Value returned by system call */
3249
3250 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003251 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003252 nBuf &= 0x1ffff;
3253 TIMER_START;
3254
3255#if defined(USE_PREAD)
3256 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3257#elif defined(USE_PREAD64)
3258 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3259#else
3260 do{
3261 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3262 SimulateIOError( iSeek-- );
3263
3264 if( iSeek!=iOff ){
3265 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3266 return -1;
3267 }
3268 rc = osWrite(fd, pBuf, nBuf);
3269 }while( rc<0 && errno==EINTR );
3270#endif
3271
3272 TIMER_END;
3273 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3274
3275 if( rc<0 && piErrno ) *piErrno = errno;
3276 return rc;
3277}
3278
3279
3280/*
drh734c9862008-11-28 15:37:20 +00003281** Seek to the offset in id->offset then read cnt bytes into pBuf.
3282** Return the number of bytes actually read. Update the offset.
3283**
3284** To avoid stomping the errno value on a failed write the lastErrno value
3285** is set before returning.
3286*/
3287static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003288 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003289}
3290
3291
3292/*
3293** Write data from a buffer into a file. Return SQLITE_OK on success
3294** or some other error code on failure.
3295*/
3296static int unixWrite(
3297 sqlite3_file *id,
3298 const void *pBuf,
3299 int amt,
3300 sqlite3_int64 offset
3301){
dan08da86a2009-08-21 17:18:03 +00003302 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003303 int wrote = 0;
3304 assert( id );
3305 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003306
dan08da86a2009-08-21 17:18:03 +00003307 /* If this is a database file (not a journal, master-journal or temp
3308 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003309#if 0
dane946c392009-08-22 11:39:46 +00003310 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003311 || offset>=PENDING_BYTE+512
3312 || offset+amt<=PENDING_BYTE
3313 );
dan7c246102010-04-12 19:00:29 +00003314#endif
drh08c6d442009-02-09 17:34:07 +00003315
drhd3d8c042012-05-29 17:02:40 +00003316#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003317 /* If we are doing a normal write to a database file (as opposed to
3318 ** doing a hot-journal rollback or a write to some file other than a
3319 ** normal database file) then record the fact that the database
3320 ** has changed. If the transaction counter is modified, record that
3321 ** fact too.
3322 */
dan08da86a2009-08-21 17:18:03 +00003323 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003324 pFile->dbUpdate = 1; /* The database has been modified */
3325 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003326 int rc;
drh8f941bc2009-01-14 23:03:40 +00003327 char oldCntr[4];
3328 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003329 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003330 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003331 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003332 pFile->transCntrChng = 1; /* The transaction counter has changed */
3333 }
3334 }
3335 }
3336#endif
3337
drh9b4c59f2013-04-15 17:03:42 +00003338#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003339 /* Deal with as much of this write request as possible by transfering
3340 ** data from the memory mapping using memcpy(). */
3341 if( offset<pFile->mmapSize ){
3342 if( offset+amt <= pFile->mmapSize ){
3343 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3344 return SQLITE_OK;
3345 }else{
3346 int nCopy = pFile->mmapSize - offset;
3347 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3348 pBuf = &((u8 *)pBuf)[nCopy];
3349 amt -= nCopy;
3350 offset += nCopy;
3351 }
3352 }
drh6e0b6d52013-04-09 16:19:20 +00003353#endif
danf23da962013-03-23 21:00:41 +00003354
dan08da86a2009-08-21 17:18:03 +00003355 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003356 amt -= wrote;
3357 offset += wrote;
3358 pBuf = &((char*)pBuf)[wrote];
3359 }
3360 SimulateIOError(( wrote=(-1), amt=1 ));
3361 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003362
drh734c9862008-11-28 15:37:20 +00003363 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003364 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003365 /* lastErrno set by seekAndWrite */
3366 return SQLITE_IOERR_WRITE;
3367 }else{
dan08da86a2009-08-21 17:18:03 +00003368 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003369 return SQLITE_FULL;
3370 }
3371 }
dan6e09d692010-07-27 18:34:15 +00003372
drh734c9862008-11-28 15:37:20 +00003373 return SQLITE_OK;
3374}
3375
3376#ifdef SQLITE_TEST
3377/*
3378** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003379** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003380*/
3381int sqlite3_sync_count = 0;
3382int sqlite3_fullsync_count = 0;
3383#endif
3384
3385/*
drh89240432009-03-25 01:06:01 +00003386** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003387** Others do no. To be safe, we will stick with the (slightly slower)
3388** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003389** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003390*/
drh20f8e132011-08-31 21:01:55 +00003391#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003392# define fdatasync fsync
3393#endif
3394
3395/*
3396** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3397** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3398** only available on Mac OS X. But that could change.
3399*/
3400#ifdef F_FULLFSYNC
3401# define HAVE_FULLFSYNC 1
3402#else
3403# define HAVE_FULLFSYNC 0
3404#endif
3405
3406
3407/*
3408** The fsync() system call does not work as advertised on many
3409** unix systems. The following procedure is an attempt to make
3410** it work better.
3411**
3412** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3413** for testing when we want to run through the test suite quickly.
3414** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3415** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3416** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003417**
3418** SQLite sets the dataOnly flag if the size of the file is unchanged.
3419** The idea behind dataOnly is that it should only write the file content
3420** to disk, not the inode. We only set dataOnly if the file size is
3421** unchanged since the file size is part of the inode. However,
3422** Ted Ts'o tells us that fdatasync() will also write the inode if the
3423** file size has changed. The only real difference between fdatasync()
3424** and fsync(), Ted tells us, is that fdatasync() will not flush the
3425** inode if the mtime or owner or other inode attributes have changed.
3426** We only care about the file size, not the other file attributes, so
3427** as far as SQLite is concerned, an fdatasync() is always adequate.
3428** So, we always use fdatasync() if it is available, regardless of
3429** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003430*/
3431static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003432 int rc;
drh734c9862008-11-28 15:37:20 +00003433
3434 /* The following "ifdef/elif/else/" block has the same structure as
3435 ** the one below. It is replicated here solely to avoid cluttering
3436 ** up the real code with the UNUSED_PARAMETER() macros.
3437 */
3438#ifdef SQLITE_NO_SYNC
3439 UNUSED_PARAMETER(fd);
3440 UNUSED_PARAMETER(fullSync);
3441 UNUSED_PARAMETER(dataOnly);
3442#elif HAVE_FULLFSYNC
3443 UNUSED_PARAMETER(dataOnly);
3444#else
3445 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003446 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003447#endif
3448
3449 /* Record the number of times that we do a normal fsync() and
3450 ** FULLSYNC. This is used during testing to verify that this procedure
3451 ** gets called with the correct arguments.
3452 */
3453#ifdef SQLITE_TEST
3454 if( fullSync ) sqlite3_fullsync_count++;
3455 sqlite3_sync_count++;
3456#endif
3457
3458 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3459 ** no-op
3460 */
3461#ifdef SQLITE_NO_SYNC
3462 rc = SQLITE_OK;
3463#elif HAVE_FULLFSYNC
3464 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003465 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003466 }else{
3467 rc = 1;
3468 }
3469 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003470 ** It shouldn't be possible for fullfsync to fail on the local
3471 ** file system (on OSX), so failure indicates that FULLFSYNC
3472 ** isn't supported for this file system. So, attempt an fsync
3473 ** and (for now) ignore the overhead of a superfluous fcntl call.
3474 ** It'd be better to detect fullfsync support once and avoid
3475 ** the fcntl call every time sync is called.
3476 */
drh734c9862008-11-28 15:37:20 +00003477 if( rc ) rc = fsync(fd);
3478
drh7ed97b92010-01-20 13:07:21 +00003479#elif defined(__APPLE__)
3480 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3481 ** so currently we default to the macro that redefines fdatasync to fsync
3482 */
3483 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003484#else
drh0b647ff2009-03-21 14:41:04 +00003485 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003486#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003487 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003488 rc = fsync(fd);
3489 }
drh0b647ff2009-03-21 14:41:04 +00003490#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003491#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3492
3493 if( OS_VXWORKS && rc!= -1 ){
3494 rc = 0;
3495 }
chw97185482008-11-17 08:05:31 +00003496 return rc;
drhbfe66312006-10-03 17:40:40 +00003497}
3498
drh734c9862008-11-28 15:37:20 +00003499/*
drh0059eae2011-08-08 23:48:40 +00003500** Open a file descriptor to the directory containing file zFilename.
3501** If successful, *pFd is set to the opened file descriptor and
3502** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3503** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3504** value.
3505**
drh90315a22011-08-10 01:52:12 +00003506** The directory file descriptor is used for only one thing - to
3507** fsync() a directory to make sure file creation and deletion events
3508** are flushed to disk. Such fsyncs are not needed on newer
3509** journaling filesystems, but are required on older filesystems.
3510**
3511** This routine can be overridden using the xSetSysCall interface.
3512** The ability to override this routine was added in support of the
3513** chromium sandbox. Opening a directory is a security risk (we are
3514** told) so making it overrideable allows the chromium sandbox to
3515** replace this routine with a harmless no-op. To make this routine
3516** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3517** *pFd set to a negative number.
3518**
drh0059eae2011-08-08 23:48:40 +00003519** If SQLITE_OK is returned, the caller is responsible for closing
3520** the file descriptor *pFd using close().
3521*/
3522static int openDirectory(const char *zFilename, int *pFd){
3523 int ii;
3524 int fd = -1;
3525 char zDirname[MAX_PATHNAME+1];
3526
3527 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3528 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3529 if( ii>0 ){
3530 zDirname[ii] = '\0';
3531 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3532 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003533 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3534 }
3535 }
3536 *pFd = fd;
3537 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3538}
3539
3540/*
drh734c9862008-11-28 15:37:20 +00003541** Make sure all writes to a particular file are committed to disk.
3542**
3543** If dataOnly==0 then both the file itself and its metadata (file
3544** size, access time, etc) are synced. If dataOnly!=0 then only the
3545** file data is synced.
3546**
3547** Under Unix, also make sure that the directory entry for the file
3548** has been created by fsync-ing the directory that contains the file.
3549** If we do not do this and we encounter a power failure, the directory
3550** entry for the journal might not exist after we reboot. The next
3551** SQLite to access the file will not know that the journal exists (because
3552** the directory entry for the journal was never created) and the transaction
3553** will not roll back - possibly leading to database corruption.
3554*/
3555static int unixSync(sqlite3_file *id, int flags){
3556 int rc;
3557 unixFile *pFile = (unixFile*)id;
3558
3559 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3560 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3561
3562 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3563 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3564 || (flags&0x0F)==SQLITE_SYNC_FULL
3565 );
3566
3567 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3568 ** line is to test that doing so does not cause any problems.
3569 */
3570 SimulateDiskfullError( return SQLITE_FULL );
3571
3572 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003573 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003574 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3575 SimulateIOError( rc=1 );
3576 if( rc ){
3577 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003578 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003579 }
drh0059eae2011-08-08 23:48:40 +00003580
3581 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003582 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003583 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003584 */
3585 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3586 int dirfd;
3587 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003588 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003589 rc = osOpenDirectory(pFile->zPath, &dirfd);
3590 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003591 full_fsync(dirfd, 0, 0);
3592 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003593 }else if( rc==SQLITE_CANTOPEN ){
3594 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003595 }
drh0059eae2011-08-08 23:48:40 +00003596 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003597 }
3598 return rc;
3599}
3600
3601/*
3602** Truncate an open file to a specified size
3603*/
3604static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003605 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003606 int rc;
dan6e09d692010-07-27 18:34:15 +00003607 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003608 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003609
3610 /* If the user has configured a chunk-size for this file, truncate the
3611 ** file so that it consists of an integer number of chunks (i.e. the
3612 ** actual file size after the operation may be larger than the requested
3613 ** size).
3614 */
drhb8af4b72012-04-05 20:04:39 +00003615 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003616 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3617 }
3618
dan2ee53412014-09-06 16:49:40 +00003619 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003620 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003621 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003622 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003623 }else{
drhd3d8c042012-05-29 17:02:40 +00003624#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003625 /* If we are doing a normal write to a database file (as opposed to
3626 ** doing a hot-journal rollback or a write to some file other than a
3627 ** normal database file) and we truncate the file to zero length,
3628 ** that effectively updates the change counter. This might happen
3629 ** when restoring a database using the backup API from a zero-length
3630 ** source.
3631 */
dan6e09d692010-07-27 18:34:15 +00003632 if( pFile->inNormalWrite && nByte==0 ){
3633 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003634 }
danf23da962013-03-23 21:00:41 +00003635#endif
danc0003312013-03-22 17:46:11 +00003636
mistachkine98844f2013-08-24 00:59:24 +00003637#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003638 /* If the file was just truncated to a size smaller than the currently
3639 ** mapped region, reduce the effective mapping size as well. SQLite will
3640 ** use read() and write() to access data beyond this point from now on.
3641 */
3642 if( nByte<pFile->mmapSize ){
3643 pFile->mmapSize = nByte;
3644 }
mistachkine98844f2013-08-24 00:59:24 +00003645#endif
drh3313b142009-11-06 04:13:18 +00003646
drh734c9862008-11-28 15:37:20 +00003647 return SQLITE_OK;
3648 }
3649}
3650
3651/*
3652** Determine the current size of a file in bytes
3653*/
3654static int unixFileSize(sqlite3_file *id, i64 *pSize){
3655 int rc;
3656 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003657 assert( id );
3658 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003659 SimulateIOError( rc=1 );
3660 if( rc!=0 ){
drh3044b512014-06-16 16:41:52 +00003661 ((unixFile*)id)->lastErrno = errno;
drh734c9862008-11-28 15:37:20 +00003662 return SQLITE_IOERR_FSTAT;
3663 }
3664 *pSize = buf.st_size;
3665
drh8af6c222010-05-14 12:43:01 +00003666 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003667 ** writes a single byte into that file in order to work around a bug
3668 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3669 ** layers, we need to report this file size as zero even though it is
3670 ** really 1. Ticket #3260.
3671 */
3672 if( *pSize==1 ) *pSize = 0;
3673
3674
3675 return SQLITE_OK;
3676}
3677
drhd2cb50b2009-01-09 21:41:17 +00003678#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003679/*
3680** Handler for proxy-locking file-control verbs. Defined below in the
3681** proxying locking division.
3682*/
3683static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003684#endif
drh715ff302008-12-03 22:32:44 +00003685
dan502019c2010-07-28 14:26:17 +00003686/*
3687** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003688** file-control operation. Enlarge the database to nBytes in size
3689** (rounded up to the next chunk-size). If the database is already
3690** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003691*/
3692static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003693 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003694 i64 nSize; /* Required file size */
3695 struct stat buf; /* Used to hold return values of fstat() */
3696
drh99ab3b12011-03-02 15:09:07 +00003697 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003698
3699 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3700 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003701
dan502019c2010-07-28 14:26:17 +00003702#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003703 /* The code below is handling the return value of osFallocate()
3704 ** correctly. posix_fallocate() is defined to "returns zero on success,
3705 ** or an error number on failure". See the manpage for details. */
3706 int err;
drhff812312011-02-23 13:33:46 +00003707 do{
dan661d71a2011-03-30 19:08:03 +00003708 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3709 }while( err==EINTR );
3710 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003711#else
3712 /* If the OS does not have posix_fallocate(), fake it. First use
3713 ** ftruncate() to set the file size, then write a single byte to
3714 ** the last byte in each block within the extended region. This
3715 ** is the same technique used by glibc to implement posix_fallocate()
3716 ** on systems that do not have a real fallocate() system call.
3717 */
3718 int nBlk = buf.st_blksize; /* File-system block size */
3719 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003720
drhff812312011-02-23 13:33:46 +00003721 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003722 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003723 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003724 }
3725 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003726 while( iWrite<nSize ){
3727 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3728 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003729 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003730 }
dan502019c2010-07-28 14:26:17 +00003731#endif
3732 }
3733 }
3734
mistachkine98844f2013-08-24 00:59:24 +00003735#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003736 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003737 int rc;
3738 if( pFile->szChunk<=0 ){
3739 if( robust_ftruncate(pFile->h, nByte) ){
3740 pFile->lastErrno = errno;
3741 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3742 }
3743 }
3744
3745 rc = unixMapfile(pFile, nByte);
3746 return rc;
3747 }
mistachkine98844f2013-08-24 00:59:24 +00003748#endif
danf23da962013-03-23 21:00:41 +00003749
dan502019c2010-07-28 14:26:17 +00003750 return SQLITE_OK;
3751}
danielk1977ad94b582007-08-20 06:44:22 +00003752
danielk1977e3026632004-06-22 11:29:02 +00003753/*
drhf12b3f62011-12-21 14:42:29 +00003754** If *pArg is inititially negative then this is a query. Set *pArg to
3755** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3756**
3757** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3758*/
3759static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3760 if( *pArg<0 ){
3761 *pArg = (pFile->ctrlFlags & mask)!=0;
3762 }else if( (*pArg)==0 ){
3763 pFile->ctrlFlags &= ~mask;
3764 }else{
3765 pFile->ctrlFlags |= mask;
3766 }
3767}
3768
drh696b33e2012-12-06 19:01:42 +00003769/* Forward declaration */
3770static int unixGetTempname(int nBuf, char *zBuf);
3771
drhf12b3f62011-12-21 14:42:29 +00003772/*
drh9e33c2c2007-08-31 18:34:59 +00003773** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003774*/
drhcc6bb3e2007-08-31 16:11:35 +00003775static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003776 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003777 switch( op ){
3778 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003779 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003780 return SQLITE_OK;
3781 }
drh7708e972008-11-29 00:56:52 +00003782 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003783 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003784 return SQLITE_OK;
3785 }
dan6e09d692010-07-27 18:34:15 +00003786 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003787 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003788 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003789 }
drh9ff27ec2010-05-19 19:26:05 +00003790 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003791 int rc;
3792 SimulateIOErrorBenign(1);
3793 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3794 SimulateIOErrorBenign(0);
3795 return rc;
drhf0b190d2011-07-26 16:03:07 +00003796 }
3797 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003798 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3799 return SQLITE_OK;
3800 }
drhcb15f352011-12-23 01:04:17 +00003801 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3802 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003803 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003804 }
drhde60fc22011-12-14 17:53:36 +00003805 case SQLITE_FCNTL_VFSNAME: {
3806 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3807 return SQLITE_OK;
3808 }
drh696b33e2012-12-06 19:01:42 +00003809 case SQLITE_FCNTL_TEMPFILENAME: {
3810 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3811 if( zTFile ){
3812 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3813 *(char**)pArg = zTFile;
3814 }
3815 return SQLITE_OK;
3816 }
drhb959a012013-12-07 12:29:22 +00003817 case SQLITE_FCNTL_HAS_MOVED: {
3818 *(int*)pArg = fileHasMoved(pFile);
3819 return SQLITE_OK;
3820 }
mistachkine98844f2013-08-24 00:59:24 +00003821#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003822 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003823 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003824 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003825 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3826 newLimit = sqlite3GlobalConfig.mxMmap;
3827 }
3828 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003829 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003830 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003831 if( pFile->mmapSize>0 ){
3832 unixUnmapfile(pFile);
3833 rc = unixMapfile(pFile, -1);
3834 }
danbcb8a862013-04-08 15:30:41 +00003835 }
drh34e258c2013-05-23 01:40:53 +00003836 return rc;
danb2d3de32013-03-14 18:34:37 +00003837 }
mistachkine98844f2013-08-24 00:59:24 +00003838#endif
drhd3d8c042012-05-29 17:02:40 +00003839#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003840 /* The pager calls this method to signal that it has done
3841 ** a rollback and that the database is therefore unchanged and
3842 ** it hence it is OK for the transaction change counter to be
3843 ** unchanged.
3844 */
3845 case SQLITE_FCNTL_DB_UNCHANGED: {
3846 ((unixFile*)id)->dbUpdate = 0;
3847 return SQLITE_OK;
3848 }
3849#endif
drhd2cb50b2009-01-09 21:41:17 +00003850#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003851 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003852 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003853 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003854 }
drhd2cb50b2009-01-09 21:41:17 +00003855#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003856 }
drh0b52b7d2011-01-26 19:46:22 +00003857 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003858}
3859
3860/*
danielk1977a3d4c882007-03-23 10:08:38 +00003861** Return the sector size in bytes of the underlying block device for
3862** the specified file. This is almost always 512 bytes, but may be
3863** larger for some devices.
3864**
3865** SQLite code assumes this function cannot fail. It also assumes that
3866** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003867** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003868** same for both.
3869*/
drh537dddf2012-10-26 13:46:24 +00003870#ifndef __QNXNTO__
3871static int unixSectorSize(sqlite3_file *NotUsed){
3872 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003873 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003874}
drh537dddf2012-10-26 13:46:24 +00003875#endif
3876
3877/*
3878** The following version of unixSectorSize() is optimized for QNX.
3879*/
3880#ifdef __QNXNTO__
3881#include <sys/dcmd_blk.h>
3882#include <sys/statvfs.h>
3883static int unixSectorSize(sqlite3_file *id){
3884 unixFile *pFile = (unixFile*)id;
3885 if( pFile->sectorSize == 0 ){
3886 struct statvfs fsInfo;
3887
3888 /* Set defaults for non-supported filesystems */
3889 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3890 pFile->deviceCharacteristics = 0;
3891 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3892 return pFile->sectorSize;
3893 }
3894
3895 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3896 pFile->sectorSize = fsInfo.f_bsize;
3897 pFile->deviceCharacteristics =
3898 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3899 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3900 ** the write succeeds */
3901 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3902 ** so it is ordered */
3903 0;
3904 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3905 pFile->sectorSize = fsInfo.f_bsize;
3906 pFile->deviceCharacteristics =
3907 /* etfs cluster size writes are atomic */
3908 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3909 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3910 ** the write succeeds */
3911 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3912 ** so it is ordered */
3913 0;
3914 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3915 pFile->sectorSize = fsInfo.f_bsize;
3916 pFile->deviceCharacteristics =
3917 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3918 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3919 ** the write succeeds */
3920 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3921 ** so it is ordered */
3922 0;
3923 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3924 pFile->sectorSize = fsInfo.f_bsize;
3925 pFile->deviceCharacteristics =
3926 /* full bitset of atomics from max sector size and smaller */
3927 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3928 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3929 ** so it is ordered */
3930 0;
3931 }else if( strstr(fsInfo.f_basetype, "dos") ){
3932 pFile->sectorSize = fsInfo.f_bsize;
3933 pFile->deviceCharacteristics =
3934 /* full bitset of atomics from max sector size and smaller */
3935 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3936 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3937 ** so it is ordered */
3938 0;
3939 }else{
3940 pFile->deviceCharacteristics =
3941 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3942 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3943 ** the write succeeds */
3944 0;
3945 }
3946 }
3947 /* Last chance verification. If the sector size isn't a multiple of 512
3948 ** then it isn't valid.*/
3949 if( pFile->sectorSize % 512 != 0 ){
3950 pFile->deviceCharacteristics = 0;
3951 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3952 }
3953 return pFile->sectorSize;
3954}
3955#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003956
danielk197790949c22007-08-17 16:50:38 +00003957/*
drhf12b3f62011-12-21 14:42:29 +00003958** Return the device characteristics for the file.
3959**
drhcb15f352011-12-23 01:04:17 +00003960** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3961** However, that choice is contraversial since technically the underlying
3962** file system does not always provide powersafe overwrites. (In other
3963** words, after a power-loss event, parts of the file that were never
3964** written might end up being altered.) However, non-PSOW behavior is very,
3965** very rare. And asserting PSOW makes a large reduction in the amount
3966** of required I/O for journaling, since a lot of padding is eliminated.
3967** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3968** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003969*/
drhf12b3f62011-12-21 14:42:29 +00003970static int unixDeviceCharacteristics(sqlite3_file *id){
3971 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003972 int rc = 0;
3973#ifdef __QNXNTO__
3974 if( p->sectorSize==0 ) unixSectorSize(id);
3975 rc = p->deviceCharacteristics;
3976#endif
drhcb15f352011-12-23 01:04:17 +00003977 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003978 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003979 }
drh537dddf2012-10-26 13:46:24 +00003980 return rc;
danielk197762079062007-08-15 17:08:46 +00003981}
3982
dan702eec12014-06-23 10:04:58 +00003983#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003984
dan702eec12014-06-23 10:04:58 +00003985/*
3986** Return the system page size.
3987**
3988** This function should not be called directly by other code in this file.
3989** Instead, it should be called via macro osGetpagesize().
3990*/
3991static int unixGetpagesize(void){
3992#if defined(_BSD_SOURCE)
3993 return getpagesize();
3994#else
3995 return (int)sysconf(_SC_PAGESIZE);
3996#endif
3997}
3998
3999#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4000
4001#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004002
4003/*
drhd91c68f2010-05-14 14:52:25 +00004004** Object used to represent an shared memory buffer.
4005**
4006** When multiple threads all reference the same wal-index, each thread
4007** has its own unixShm object, but they all point to a single instance
4008** of this unixShmNode object. In other words, each wal-index is opened
4009** only once per process.
4010**
4011** Each unixShmNode object is connected to a single unixInodeInfo object.
4012** We could coalesce this object into unixInodeInfo, but that would mean
4013** every open file that does not use shared memory (in other words, most
4014** open files) would have to carry around this extra information. So
4015** the unixInodeInfo object contains a pointer to this unixShmNode object
4016** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004017**
4018** unixMutexHeld() must be true when creating or destroying
4019** this object or while reading or writing the following fields:
4020**
4021** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004022**
4023** The following fields are read-only after the object is created:
4024**
4025** fid
4026** zFilename
4027**
drhd91c68f2010-05-14 14:52:25 +00004028** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004029** unixMutexHeld() is true when reading or writing any other field
4030** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004031*/
drhd91c68f2010-05-14 14:52:25 +00004032struct unixShmNode {
4033 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004034 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004035 char *zFilename; /* Name of the mmapped file */
4036 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004037 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004038 u16 nRegion; /* Size of array apRegion */
4039 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004040 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004041 int nRef; /* Number of unixShm objects pointing to this */
4042 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004043#ifdef SQLITE_DEBUG
4044 u8 exclMask; /* Mask of exclusive locks held */
4045 u8 sharedMask; /* Mask of shared locks held */
4046 u8 nextShmId; /* Next available unixShm.id value */
4047#endif
4048};
4049
4050/*
drhd9e5c4f2010-05-12 18:01:39 +00004051** Structure used internally by this VFS to record the state of an
4052** open shared memory connection.
4053**
drhd91c68f2010-05-14 14:52:25 +00004054** The following fields are initialized when this object is created and
4055** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004056**
drhd91c68f2010-05-14 14:52:25 +00004057** unixShm.pFile
4058** unixShm.id
4059**
4060** All other fields are read/write. The unixShm.pFile->mutex must be held
4061** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004062*/
4063struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004064 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4065 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004066 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004067 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004068 u16 sharedMask; /* Mask of shared locks held */
4069 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004070};
4071
4072/*
drhd9e5c4f2010-05-12 18:01:39 +00004073** Constants used for locking
4074*/
drhbd9676c2010-06-23 17:58:38 +00004075#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004076#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004077
drhd9e5c4f2010-05-12 18:01:39 +00004078/*
drh73b64e42010-05-30 19:55:15 +00004079** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004080**
4081** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4082** otherwise.
4083*/
4084static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004085 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4086 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004087 int ofst, /* First byte of the locking range */
4088 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004089){
4090 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004091 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004092
drhd91c68f2010-05-14 14:52:25 +00004093 /* Access to the unixShmNode object is serialized by the caller */
4094 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004095
drh73b64e42010-05-30 19:55:15 +00004096 /* Shared locks never span more than one byte */
4097 assert( n==1 || lockType!=F_RDLCK );
4098
4099 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004100 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004101
drh3cb93392011-03-12 18:10:44 +00004102 if( pShmNode->h>=0 ){
4103 /* Initialize the locking parameters */
4104 memset(&f, 0, sizeof(f));
4105 f.l_type = lockType;
4106 f.l_whence = SEEK_SET;
4107 f.l_start = ofst;
4108 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004109
drh3cb93392011-03-12 18:10:44 +00004110 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4111 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4112 }
drhd9e5c4f2010-05-12 18:01:39 +00004113
4114 /* Update the global lock state and do debug tracing */
4115#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004116 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004117 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004118 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004119 if( rc==SQLITE_OK ){
4120 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004121 OSTRACE(("unlock %d ok", ofst));
4122 pShmNode->exclMask &= ~mask;
4123 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004124 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004125 OSTRACE(("read-lock %d ok", ofst));
4126 pShmNode->exclMask &= ~mask;
4127 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004128 }else{
4129 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004130 OSTRACE(("write-lock %d ok", ofst));
4131 pShmNode->exclMask |= mask;
4132 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004133 }
4134 }else{
4135 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004136 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004137 }else if( lockType==F_RDLCK ){
4138 OSTRACE(("read-lock failed"));
4139 }else{
4140 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004141 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004142 }
4143 }
drh20e1f082010-05-31 16:10:12 +00004144 OSTRACE((" - afterwards %03x,%03x\n",
4145 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004146 }
drhd9e5c4f2010-05-12 18:01:39 +00004147#endif
4148
4149 return rc;
4150}
4151
dan781e34c2014-03-20 08:59:47 +00004152/*
dan781e34c2014-03-20 08:59:47 +00004153** Return the minimum number of 32KB shm regions that should be mapped at
4154** a time, assuming that each mapping must be an integer multiple of the
4155** current system page-size.
4156**
4157** Usually, this is 1. The exception seems to be systems that are configured
4158** to use 64KB pages - in this case each mapping must cover at least two
4159** shm regions.
4160*/
4161static int unixShmRegionPerMap(void){
4162 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004163 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004164 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4165 if( pgsz<shmsz ) return 1;
4166 return pgsz/shmsz;
4167}
drhd9e5c4f2010-05-12 18:01:39 +00004168
4169/*
drhd91c68f2010-05-14 14:52:25 +00004170** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004171**
4172** This is not a VFS shared-memory method; it is a utility function called
4173** by VFS shared-memory methods.
4174*/
drhd91c68f2010-05-14 14:52:25 +00004175static void unixShmPurge(unixFile *pFd){
4176 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004177 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004178 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004179 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004180 int i;
drhd91c68f2010-05-14 14:52:25 +00004181 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004182 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004183 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004184 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004185 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004186 }else{
4187 sqlite3_free(p->apRegion[i]);
4188 }
dan13a3cb82010-06-11 19:04:21 +00004189 }
dan18801912010-06-14 14:07:50 +00004190 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004191 if( p->h>=0 ){
4192 robust_close(pFd, p->h, __LINE__);
4193 p->h = -1;
4194 }
drhd91c68f2010-05-14 14:52:25 +00004195 p->pInode->pShmNode = 0;
4196 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004197 }
4198}
4199
4200/*
danda9fe0c2010-07-13 18:44:03 +00004201** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004202** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004203**
drh7234c6d2010-06-19 15:10:09 +00004204** The file used to implement shared-memory is in the same directory
4205** as the open database file and has the same name as the open database
4206** file with the "-shm" suffix added. For example, if the database file
4207** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004208** for shared memory will be called "/home/user1/config.db-shm".
4209**
4210** Another approach to is to use files in /dev/shm or /dev/tmp or an
4211** some other tmpfs mount. But if a file in a different directory
4212** from the database file is used, then differing access permissions
4213** or a chroot() might cause two different processes on the same
4214** database to end up using different files for shared memory -
4215** meaning that their memory would not really be shared - resulting
4216** in database corruption. Nevertheless, this tmpfs file usage
4217** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4218** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4219** option results in an incompatible build of SQLite; builds of SQLite
4220** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4221** same database file at the same time, database corruption will likely
4222** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4223** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004224**
4225** When opening a new shared-memory file, if no other instances of that
4226** file are currently open, in this process or in other processes, then
4227** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004228**
4229** If the original database file (pDbFd) is using the "unix-excl" VFS
4230** that means that an exclusive lock is held on the database file and
4231** that no other processes are able to read or write the database. In
4232** that case, we do not really need shared memory. No shared memory
4233** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004234*/
danda9fe0c2010-07-13 18:44:03 +00004235static int unixOpenSharedMemory(unixFile *pDbFd){
4236 struct unixShm *p = 0; /* The connection to be opened */
4237 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4238 int rc; /* Result code */
4239 unixInodeInfo *pInode; /* The inode of fd */
4240 char *zShmFilename; /* Name of the file used for SHM */
4241 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004242
danda9fe0c2010-07-13 18:44:03 +00004243 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004244 p = sqlite3_malloc( sizeof(*p) );
4245 if( p==0 ) return SQLITE_NOMEM;
4246 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004247 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004248
danda9fe0c2010-07-13 18:44:03 +00004249 /* Check to see if a unixShmNode object already exists. Reuse an existing
4250 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004251 */
4252 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004253 pInode = pDbFd->pInode;
4254 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004255 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004256 struct stat sStat; /* fstat() info for database file */
4257
4258 /* Call fstat() to figure out the permissions on the database file. If
4259 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004260 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004261 */
drh3cb93392011-03-12 18:10:44 +00004262 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004263 rc = SQLITE_IOERR_FSTAT;
4264 goto shm_open_err;
4265 }
4266
drha4ced192010-07-15 18:32:40 +00004267#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004268 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004269#else
drh52bcde02012-01-03 14:50:45 +00004270 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004271#endif
drh7234c6d2010-06-19 15:10:09 +00004272 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004273 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004274 rc = SQLITE_NOMEM;
4275 goto shm_open_err;
4276 }
drh9cb5a0d2012-01-05 21:19:54 +00004277 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004278 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004279#ifdef SQLITE_SHM_DIRECTORY
4280 sqlite3_snprintf(nShmFilename, zShmFilename,
4281 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4282 (u32)sStat.st_ino, (u32)sStat.st_dev);
4283#else
drh7234c6d2010-06-19 15:10:09 +00004284 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004285 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004286#endif
drhd91c68f2010-05-14 14:52:25 +00004287 pShmNode->h = -1;
4288 pDbFd->pInode->pShmNode = pShmNode;
4289 pShmNode->pInode = pDbFd->pInode;
4290 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4291 if( pShmNode->mutex==0 ){
4292 rc = SQLITE_NOMEM;
4293 goto shm_open_err;
4294 }
drhd9e5c4f2010-05-12 18:01:39 +00004295
drh3cb93392011-03-12 18:10:44 +00004296 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004297 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004298 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004299 openFlags = O_RDONLY;
4300 pShmNode->isReadonly = 1;
4301 }
4302 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004303 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004304 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4305 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004306 }
drhac7c3ac2012-02-11 19:23:48 +00004307
4308 /* If this process is running as root, make sure that the SHM file
4309 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004310 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004311 */
drhed466822012-05-31 13:10:49 +00004312 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004313
4314 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004315 ** If not, truncate the file to zero length.
4316 */
4317 rc = SQLITE_OK;
4318 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4319 if( robust_ftruncate(pShmNode->h, 0) ){
4320 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004321 }
4322 }
drh66dfec8b2011-06-01 20:01:49 +00004323 if( rc==SQLITE_OK ){
4324 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4325 }
4326 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004327 }
drhd9e5c4f2010-05-12 18:01:39 +00004328 }
4329
drhd91c68f2010-05-14 14:52:25 +00004330 /* Make the new connection a child of the unixShmNode */
4331 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004332#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004333 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004334#endif
drhd91c68f2010-05-14 14:52:25 +00004335 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004336 pDbFd->pShm = p;
4337 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004338
4339 /* The reference count on pShmNode has already been incremented under
4340 ** the cover of the unixEnterMutex() mutex and the pointer from the
4341 ** new (struct unixShm) object to the pShmNode has been set. All that is
4342 ** left to do is to link the new object into the linked list starting
4343 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4344 ** mutex.
4345 */
4346 sqlite3_mutex_enter(pShmNode->mutex);
4347 p->pNext = pShmNode->pFirst;
4348 pShmNode->pFirst = p;
4349 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004350 return SQLITE_OK;
4351
4352 /* Jump here on any error */
4353shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004354 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004355 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004356 unixLeaveMutex();
4357 return rc;
4358}
4359
4360/*
danda9fe0c2010-07-13 18:44:03 +00004361** This function is called to obtain a pointer to region iRegion of the
4362** shared-memory associated with the database file fd. Shared-memory regions
4363** are numbered starting from zero. Each shared-memory region is szRegion
4364** bytes in size.
4365**
4366** If an error occurs, an error code is returned and *pp is set to NULL.
4367**
4368** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4369** region has not been allocated (by any client, including one running in a
4370** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4371** bExtend is non-zero and the requested shared-memory region has not yet
4372** been allocated, it is allocated by this function.
4373**
4374** If the shared-memory region has already been allocated or is allocated by
4375** this call as described above, then it is mapped into this processes
4376** address space (if it is not already), *pp is set to point to the mapped
4377** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004378*/
danda9fe0c2010-07-13 18:44:03 +00004379static int unixShmMap(
4380 sqlite3_file *fd, /* Handle open on database file */
4381 int iRegion, /* Region to retrieve */
4382 int szRegion, /* Size of regions */
4383 int bExtend, /* True to extend file if necessary */
4384 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004385){
danda9fe0c2010-07-13 18:44:03 +00004386 unixFile *pDbFd = (unixFile*)fd;
4387 unixShm *p;
4388 unixShmNode *pShmNode;
4389 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004390 int nShmPerMap = unixShmRegionPerMap();
4391 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004392
danda9fe0c2010-07-13 18:44:03 +00004393 /* If the shared-memory file has not yet been opened, open it now. */
4394 if( pDbFd->pShm==0 ){
4395 rc = unixOpenSharedMemory(pDbFd);
4396 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004397 }
drhd9e5c4f2010-05-12 18:01:39 +00004398
danda9fe0c2010-07-13 18:44:03 +00004399 p = pDbFd->pShm;
4400 pShmNode = p->pShmNode;
4401 sqlite3_mutex_enter(pShmNode->mutex);
4402 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004403 assert( pShmNode->pInode==pDbFd->pInode );
4404 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4405 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004406
dan781e34c2014-03-20 08:59:47 +00004407 /* Minimum number of regions required to be mapped. */
4408 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4409
4410 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004411 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004412 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004413 struct stat sStat; /* Used by fstat() */
4414
4415 pShmNode->szRegion = szRegion;
4416
drh3cb93392011-03-12 18:10:44 +00004417 if( pShmNode->h>=0 ){
4418 /* The requested region is not mapped into this processes address space.
4419 ** Check to see if it has been allocated (i.e. if the wal-index file is
4420 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004421 */
drh3cb93392011-03-12 18:10:44 +00004422 if( osFstat(pShmNode->h, &sStat) ){
4423 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004424 goto shmpage_out;
4425 }
drh3cb93392011-03-12 18:10:44 +00004426
4427 if( sStat.st_size<nByte ){
4428 /* The requested memory region does not exist. If bExtend is set to
4429 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004430 */
dan47a2b4a2013-04-26 16:09:29 +00004431 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004432 goto shmpage_out;
4433 }
dan47a2b4a2013-04-26 16:09:29 +00004434
4435 /* Alternatively, if bExtend is true, extend the file. Do this by
4436 ** writing a single byte to the end of each (OS) page being
4437 ** allocated or extended. Technically, we need only write to the
4438 ** last page in order to extend the file. But writing to all new
4439 ** pages forces the OS to allocate them immediately, which reduces
4440 ** the chances of SIGBUS while accessing the mapped region later on.
4441 */
4442 else{
4443 static const int pgsz = 4096;
4444 int iPg;
4445
4446 /* Write to the last byte of each newly allocated or extended page */
4447 assert( (nByte % pgsz)==0 );
4448 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4449 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4450 const char *zFile = pShmNode->zFilename;
4451 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4452 goto shmpage_out;
4453 }
4454 }
drh3cb93392011-03-12 18:10:44 +00004455 }
4456 }
danda9fe0c2010-07-13 18:44:03 +00004457 }
4458
4459 /* Map the requested memory region into this processes address space. */
4460 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004461 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004462 );
4463 if( !apNew ){
4464 rc = SQLITE_IOERR_NOMEM;
4465 goto shmpage_out;
4466 }
4467 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004468 while( pShmNode->nRegion<nReqRegion ){
4469 int nMap = szRegion*nShmPerMap;
4470 int i;
drh3cb93392011-03-12 18:10:44 +00004471 void *pMem;
4472 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004473 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004474 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004475 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004476 );
4477 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004478 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004479 goto shmpage_out;
4480 }
4481 }else{
4482 pMem = sqlite3_malloc(szRegion);
4483 if( pMem==0 ){
4484 rc = SQLITE_NOMEM;
4485 goto shmpage_out;
4486 }
4487 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004488 }
dan781e34c2014-03-20 08:59:47 +00004489
4490 for(i=0; i<nShmPerMap; i++){
4491 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4492 }
4493 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004494 }
4495 }
4496
4497shmpage_out:
4498 if( pShmNode->nRegion>iRegion ){
4499 *pp = pShmNode->apRegion[iRegion];
4500 }else{
4501 *pp = 0;
4502 }
drh66dfec8b2011-06-01 20:01:49 +00004503 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004504 sqlite3_mutex_leave(pShmNode->mutex);
4505 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004506}
4507
4508/*
drhd9e5c4f2010-05-12 18:01:39 +00004509** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004510**
4511** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4512** different here than in posix. In xShmLock(), one can go from unlocked
4513** to shared and back or from unlocked to exclusive and back. But one may
4514** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004515*/
4516static int unixShmLock(
4517 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004518 int ofst, /* First lock to acquire or release */
4519 int n, /* Number of locks to acquire or release */
4520 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004521){
drh73b64e42010-05-30 19:55:15 +00004522 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4523 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4524 unixShm *pX; /* For looping over all siblings */
4525 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4526 int rc = SQLITE_OK; /* Result code */
4527 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004528
drhd91c68f2010-05-14 14:52:25 +00004529 assert( pShmNode==pDbFd->pInode->pShmNode );
4530 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004531 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004532 assert( n>=1 );
4533 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4534 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4535 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4536 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4537 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004538 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4539 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004540
drhc99597c2010-05-31 01:41:15 +00004541 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004542 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004543 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004544 if( flags & SQLITE_SHM_UNLOCK ){
4545 u16 allMask = 0; /* Mask of locks held by siblings */
4546
4547 /* See if any siblings hold this same lock */
4548 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4549 if( pX==p ) continue;
4550 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4551 allMask |= pX->sharedMask;
4552 }
4553
4554 /* Unlock the system-level locks */
4555 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004556 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004557 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004558 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004559 }
drh73b64e42010-05-30 19:55:15 +00004560
4561 /* Undo the local locks */
4562 if( rc==SQLITE_OK ){
4563 p->exclMask &= ~mask;
4564 p->sharedMask &= ~mask;
4565 }
4566 }else if( flags & SQLITE_SHM_SHARED ){
4567 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4568
4569 /* Find out which shared locks are already held by sibling connections.
4570 ** If any sibling already holds an exclusive lock, go ahead and return
4571 ** SQLITE_BUSY.
4572 */
4573 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004574 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004575 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004576 break;
4577 }
4578 allShared |= pX->sharedMask;
4579 }
4580
4581 /* Get shared locks at the system level, if necessary */
4582 if( rc==SQLITE_OK ){
4583 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004584 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004585 }else{
drh73b64e42010-05-30 19:55:15 +00004586 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004587 }
drhd9e5c4f2010-05-12 18:01:39 +00004588 }
drh73b64e42010-05-30 19:55:15 +00004589
4590 /* Get the local shared locks */
4591 if( rc==SQLITE_OK ){
4592 p->sharedMask |= mask;
4593 }
4594 }else{
4595 /* Make sure no sibling connections hold locks that will block this
4596 ** lock. If any do, return SQLITE_BUSY right away.
4597 */
4598 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004599 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4600 rc = SQLITE_BUSY;
4601 break;
4602 }
4603 }
4604
4605 /* Get the exclusive locks at the system level. Then if successful
4606 ** also mark the local connection as being locked.
4607 */
4608 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004609 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004610 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004611 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004612 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004613 }
drhd9e5c4f2010-05-12 18:01:39 +00004614 }
4615 }
drhd91c68f2010-05-14 14:52:25 +00004616 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004617 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4618 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004619 return rc;
4620}
4621
drh286a2882010-05-20 23:51:06 +00004622/*
4623** Implement a memory barrier or memory fence on shared memory.
4624**
4625** All loads and stores begun before the barrier must complete before
4626** any load or store begun after the barrier.
4627*/
4628static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004629 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004630){
drhff828942010-06-26 21:34:06 +00004631 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004632 unixEnterMutex();
4633 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004634}
4635
dan18801912010-06-14 14:07:50 +00004636/*
danda9fe0c2010-07-13 18:44:03 +00004637** Close a connection to shared-memory. Delete the underlying
4638** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004639**
4640** If there is no shared memory associated with the connection then this
4641** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004642*/
danda9fe0c2010-07-13 18:44:03 +00004643static int unixShmUnmap(
4644 sqlite3_file *fd, /* The underlying database file */
4645 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004646){
danda9fe0c2010-07-13 18:44:03 +00004647 unixShm *p; /* The connection to be closed */
4648 unixShmNode *pShmNode; /* The underlying shared-memory file */
4649 unixShm **pp; /* For looping over sibling connections */
4650 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004651
danda9fe0c2010-07-13 18:44:03 +00004652 pDbFd = (unixFile*)fd;
4653 p = pDbFd->pShm;
4654 if( p==0 ) return SQLITE_OK;
4655 pShmNode = p->pShmNode;
4656
4657 assert( pShmNode==pDbFd->pInode->pShmNode );
4658 assert( pShmNode->pInode==pDbFd->pInode );
4659
4660 /* Remove connection p from the set of connections associated
4661 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004662 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004663 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4664 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004665
danda9fe0c2010-07-13 18:44:03 +00004666 /* Free the connection p */
4667 sqlite3_free(p);
4668 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004669 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004670
4671 /* If pShmNode->nRef has reached 0, then close the underlying
4672 ** shared-memory file, too */
4673 unixEnterMutex();
4674 assert( pShmNode->nRef>0 );
4675 pShmNode->nRef--;
4676 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004677 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004678 unixShmPurge(pDbFd);
4679 }
4680 unixLeaveMutex();
4681
4682 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004683}
drh286a2882010-05-20 23:51:06 +00004684
danda9fe0c2010-07-13 18:44:03 +00004685
drhd9e5c4f2010-05-12 18:01:39 +00004686#else
drh6b017cc2010-06-14 18:01:46 +00004687# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004688# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004689# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004690# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004691#endif /* #ifndef SQLITE_OMIT_WAL */
4692
mistachkine98844f2013-08-24 00:59:24 +00004693#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004694/*
danaef49d72013-03-25 16:28:54 +00004695** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004696*/
danf23da962013-03-23 21:00:41 +00004697static void unixUnmapfile(unixFile *pFd){
4698 assert( pFd->nFetchOut==0 );
4699 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004700 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004701 pFd->pMapRegion = 0;
4702 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004703 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004704 }
4705}
dan5d8a1372013-03-19 19:28:06 +00004706
danaef49d72013-03-25 16:28:54 +00004707/*
dane6ecd662013-04-01 17:56:59 +00004708** Attempt to set the size of the memory mapping maintained by file
4709** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4710**
4711** If successful, this function sets the following variables:
4712**
4713** unixFile.pMapRegion
4714** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004715** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004716**
4717** If unsuccessful, an error message is logged via sqlite3_log() and
4718** the three variables above are zeroed. In this case SQLite should
4719** continue accessing the database using the xRead() and xWrite()
4720** methods.
4721*/
4722static void unixRemapfile(
4723 unixFile *pFd, /* File descriptor object */
4724 i64 nNew /* Required mapping size */
4725){
dan4ff7bc42013-04-02 12:04:09 +00004726 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004727 int h = pFd->h; /* File descriptor open on db file */
4728 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004729 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004730 u8 *pNew = 0; /* Location of new mapping */
4731 int flags = PROT_READ; /* Flags to pass to mmap() */
4732
4733 assert( pFd->nFetchOut==0 );
4734 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004735 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004736 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004737 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004738 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004739
4740 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4741
4742 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004743#if HAVE_MREMAP
4744 i64 nReuse = pFd->mmapSize;
4745#else
danbc760632014-03-20 09:42:09 +00004746 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004747 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004748#endif
dane6ecd662013-04-01 17:56:59 +00004749 u8 *pReq = &pOrig[nReuse];
4750
4751 /* Unmap any pages of the existing mapping that cannot be reused. */
4752 if( nReuse!=nOrig ){
4753 osMunmap(pReq, nOrig-nReuse);
4754 }
4755
4756#if HAVE_MREMAP
4757 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004758 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004759#else
4760 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4761 if( pNew!=MAP_FAILED ){
4762 if( pNew!=pReq ){
4763 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004764 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004765 }else{
4766 pNew = pOrig;
4767 }
4768 }
4769#endif
4770
dan48ccef82013-04-02 20:55:01 +00004771 /* The attempt to extend the existing mapping failed. Free it. */
4772 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004773 osMunmap(pOrig, nReuse);
4774 }
4775 }
4776
4777 /* If pNew is still NULL, try to create an entirely new mapping. */
4778 if( pNew==0 ){
4779 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004780 }
4781
dan4ff7bc42013-04-02 12:04:09 +00004782 if( pNew==MAP_FAILED ){
4783 pNew = 0;
4784 nNew = 0;
4785 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4786
4787 /* If the mmap() above failed, assume that all subsequent mmap() calls
4788 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4789 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004790 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004791 }
dane6ecd662013-04-01 17:56:59 +00004792 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004793 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004794}
4795
4796/*
danaef49d72013-03-25 16:28:54 +00004797** Memory map or remap the file opened by file-descriptor pFd (if the file
4798** is already mapped, the existing mapping is replaced by the new). Or, if
4799** there already exists a mapping for this file, and there are still
4800** outstanding xFetch() references to it, this function is a no-op.
4801**
4802** If parameter nByte is non-negative, then it is the requested size of
4803** the mapping to create. Otherwise, if nByte is less than zero, then the
4804** requested size is the size of the file on disk. The actual size of the
4805** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004806** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004807**
4808** SQLITE_OK is returned if no error occurs (even if the mapping is not
4809** recreated as a result of outstanding references) or an SQLite error
4810** code otherwise.
4811*/
danf23da962013-03-23 21:00:41 +00004812static int unixMapfile(unixFile *pFd, i64 nByte){
4813 i64 nMap = nByte;
4814 int rc;
daneb97b292013-03-20 14:26:59 +00004815
danf23da962013-03-23 21:00:41 +00004816 assert( nMap>=0 || pFd->nFetchOut==0 );
4817 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4818
4819 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004820 struct stat statbuf; /* Low-level file information */
4821 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004822 if( rc!=SQLITE_OK ){
4823 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004824 }
drh3044b512014-06-16 16:41:52 +00004825 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004826 }
drh9b4c59f2013-04-15 17:03:42 +00004827 if( nMap>pFd->mmapSizeMax ){
4828 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004829 }
4830
danf23da962013-03-23 21:00:41 +00004831 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004832 if( nMap>0 ){
4833 unixRemapfile(pFd, nMap);
4834 }else{
danb7e3a322013-03-25 20:30:13 +00004835 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004836 }
4837 }
4838
danf23da962013-03-23 21:00:41 +00004839 return SQLITE_OK;
4840}
mistachkine98844f2013-08-24 00:59:24 +00004841#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004842
danaef49d72013-03-25 16:28:54 +00004843/*
4844** If possible, return a pointer to a mapping of file fd starting at offset
4845** iOff. The mapping must be valid for at least nAmt bytes.
4846**
4847** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4848** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4849** Finally, if an error does occur, return an SQLite error code. The final
4850** value of *pp is undefined in this case.
4851**
4852** If this function does return a pointer, the caller must eventually
4853** release the reference by calling unixUnfetch().
4854*/
danf23da962013-03-23 21:00:41 +00004855static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004856#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004857 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004858#endif
danf23da962013-03-23 21:00:41 +00004859 *pp = 0;
4860
drh9b4c59f2013-04-15 17:03:42 +00004861#if SQLITE_MAX_MMAP_SIZE>0
4862 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004863 if( pFd->pMapRegion==0 ){
4864 int rc = unixMapfile(pFd, -1);
4865 if( rc!=SQLITE_OK ) return rc;
4866 }
4867 if( pFd->mmapSize >= iOff+nAmt ){
4868 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4869 pFd->nFetchOut++;
4870 }
4871 }
drh6e0b6d52013-04-09 16:19:20 +00004872#endif
danf23da962013-03-23 21:00:41 +00004873 return SQLITE_OK;
4874}
4875
danaef49d72013-03-25 16:28:54 +00004876/*
dandf737fe2013-03-25 17:00:24 +00004877** If the third argument is non-NULL, then this function releases a
4878** reference obtained by an earlier call to unixFetch(). The second
4879** argument passed to this function must be the same as the corresponding
4880** argument that was passed to the unixFetch() invocation.
4881**
4882** Or, if the third argument is NULL, then this function is being called
4883** to inform the VFS layer that, according to POSIX, any existing mapping
4884** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004885*/
dandf737fe2013-03-25 17:00:24 +00004886static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004887#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004888 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004889 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004890
danaef49d72013-03-25 16:28:54 +00004891 /* If p==0 (unmap the entire file) then there must be no outstanding
4892 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4893 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004894 assert( (p==0)==(pFd->nFetchOut==0) );
4895
dandf737fe2013-03-25 17:00:24 +00004896 /* If p!=0, it must match the iOff value. */
4897 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4898
danf23da962013-03-23 21:00:41 +00004899 if( p ){
4900 pFd->nFetchOut--;
4901 }else{
4902 unixUnmapfile(pFd);
4903 }
4904
4905 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004906#else
4907 UNUSED_PARAMETER(fd);
4908 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004909 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004910#endif
danf23da962013-03-23 21:00:41 +00004911 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004912}
4913
4914/*
drh734c9862008-11-28 15:37:20 +00004915** Here ends the implementation of all sqlite3_file methods.
4916**
4917********************** End sqlite3_file Methods *******************************
4918******************************************************************************/
4919
4920/*
drh6b9d6dd2008-12-03 19:34:47 +00004921** This division contains definitions of sqlite3_io_methods objects that
4922** implement various file locking strategies. It also contains definitions
4923** of "finder" functions. A finder-function is used to locate the appropriate
4924** sqlite3_io_methods object for a particular database file. The pAppData
4925** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4926** the correct finder-function for that VFS.
4927**
4928** Most finder functions return a pointer to a fixed sqlite3_io_methods
4929** object. The only interesting finder-function is autolockIoFinder, which
4930** looks at the filesystem type and tries to guess the best locking
4931** strategy from that.
4932**
drh1875f7a2008-12-08 18:19:17 +00004933** For finder-funtion F, two objects are created:
4934**
4935** (1) The real finder-function named "FImpt()".
4936**
dane946c392009-08-22 11:39:46 +00004937** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004938**
4939**
4940** A pointer to the F pointer is used as the pAppData value for VFS
4941** objects. We have to do this instead of letting pAppData point
4942** directly at the finder-function since C90 rules prevent a void*
4943** from be cast into a function pointer.
4944**
drh6b9d6dd2008-12-03 19:34:47 +00004945**
drh7708e972008-11-29 00:56:52 +00004946** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004947**
drh7708e972008-11-29 00:56:52 +00004948** * A constant sqlite3_io_methods object call METHOD that has locking
4949** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4950**
4951** * An I/O method finder function called FINDER that returns a pointer
4952** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004953*/
drhd9e5c4f2010-05-12 18:01:39 +00004954#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004955static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004956 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004957 CLOSE, /* xClose */ \
4958 unixRead, /* xRead */ \
4959 unixWrite, /* xWrite */ \
4960 unixTruncate, /* xTruncate */ \
4961 unixSync, /* xSync */ \
4962 unixFileSize, /* xFileSize */ \
4963 LOCK, /* xLock */ \
4964 UNLOCK, /* xUnlock */ \
4965 CKLOCK, /* xCheckReservedLock */ \
4966 unixFileControl, /* xFileControl */ \
4967 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004968 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004969 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004970 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004971 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004972 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004973 unixFetch, /* xFetch */ \
4974 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004975}; \
drh0c2694b2009-09-03 16:23:44 +00004976static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4977 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004978 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004979} \
drh0c2694b2009-09-03 16:23:44 +00004980static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004981 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004982
4983/*
4984** Here are all of the sqlite3_io_methods objects for each of the
4985** locking strategies. Functions that return pointers to these methods
4986** are also created.
4987*/
4988IOMETHODS(
4989 posixIoFinder, /* Finder function name */
4990 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004991 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004992 unixClose, /* xClose method */
4993 unixLock, /* xLock method */
4994 unixUnlock, /* xUnlock method */
4995 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004996)
drh7708e972008-11-29 00:56:52 +00004997IOMETHODS(
4998 nolockIoFinder, /* Finder function name */
4999 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005000 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005001 nolockClose, /* xClose method */
5002 nolockLock, /* xLock method */
5003 nolockUnlock, /* xUnlock method */
5004 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005005)
drh7708e972008-11-29 00:56:52 +00005006IOMETHODS(
5007 dotlockIoFinder, /* Finder function name */
5008 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005009 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005010 dotlockClose, /* xClose method */
5011 dotlockLock, /* xLock method */
5012 dotlockUnlock, /* xUnlock method */
5013 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005014)
drh7708e972008-11-29 00:56:52 +00005015
chw78a13182009-04-07 05:35:03 +00005016#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005017IOMETHODS(
5018 flockIoFinder, /* Finder function name */
5019 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005020 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005021 flockClose, /* xClose method */
5022 flockLock, /* xLock method */
5023 flockUnlock, /* xUnlock method */
5024 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005025)
drh7708e972008-11-29 00:56:52 +00005026#endif
5027
drh6c7d5c52008-11-21 20:32:33 +00005028#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005029IOMETHODS(
5030 semIoFinder, /* Finder function name */
5031 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005032 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005033 semClose, /* xClose method */
5034 semLock, /* xLock method */
5035 semUnlock, /* xUnlock method */
5036 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005037)
aswiftaebf4132008-11-21 00:10:35 +00005038#endif
drh7708e972008-11-29 00:56:52 +00005039
drhd2cb50b2009-01-09 21:41:17 +00005040#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005041IOMETHODS(
5042 afpIoFinder, /* Finder function name */
5043 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005044 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005045 afpClose, /* xClose method */
5046 afpLock, /* xLock method */
5047 afpUnlock, /* xUnlock method */
5048 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005049)
drh715ff302008-12-03 22:32:44 +00005050#endif
5051
5052/*
5053** The proxy locking method is a "super-method" in the sense that it
5054** opens secondary file descriptors for the conch and lock files and
5055** it uses proxy, dot-file, AFP, and flock() locking methods on those
5056** secondary files. For this reason, the division that implements
5057** proxy locking is located much further down in the file. But we need
5058** to go ahead and define the sqlite3_io_methods and finder function
5059** for proxy locking here. So we forward declare the I/O methods.
5060*/
drhd2cb50b2009-01-09 21:41:17 +00005061#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005062static int proxyClose(sqlite3_file*);
5063static int proxyLock(sqlite3_file*, int);
5064static int proxyUnlock(sqlite3_file*, int);
5065static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005066IOMETHODS(
5067 proxyIoFinder, /* Finder function name */
5068 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005069 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005070 proxyClose, /* xClose method */
5071 proxyLock, /* xLock method */
5072 proxyUnlock, /* xUnlock method */
5073 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005074)
aswiftaebf4132008-11-21 00:10:35 +00005075#endif
drh7708e972008-11-29 00:56:52 +00005076
drh7ed97b92010-01-20 13:07:21 +00005077/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5078#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5079IOMETHODS(
5080 nfsIoFinder, /* Finder function name */
5081 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005082 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005083 unixClose, /* xClose method */
5084 unixLock, /* xLock method */
5085 nfsUnlock, /* xUnlock method */
5086 unixCheckReservedLock /* xCheckReservedLock method */
5087)
5088#endif
drh7708e972008-11-29 00:56:52 +00005089
drhd2cb50b2009-01-09 21:41:17 +00005090#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005091/*
drh6b9d6dd2008-12-03 19:34:47 +00005092** This "finder" function attempts to determine the best locking strategy
5093** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005094** object that implements that strategy.
5095**
5096** This is for MacOSX only.
5097*/
drh1875f7a2008-12-08 18:19:17 +00005098static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005099 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005100 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005101){
5102 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005103 const char *zFilesystem; /* Filesystem type name */
5104 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005105 } aMap[] = {
5106 { "hfs", &posixIoMethods },
5107 { "ufs", &posixIoMethods },
5108 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005109 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005110 { "webdav", &nolockIoMethods },
5111 { 0, 0 }
5112 };
5113 int i;
5114 struct statfs fsInfo;
5115 struct flock lockInfo;
5116
5117 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005118 /* If filePath==NULL that means we are dealing with a transient file
5119 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005120 return &nolockIoMethods;
5121 }
5122 if( statfs(filePath, &fsInfo) != -1 ){
5123 if( fsInfo.f_flags & MNT_RDONLY ){
5124 return &nolockIoMethods;
5125 }
5126 for(i=0; aMap[i].zFilesystem; i++){
5127 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5128 return aMap[i].pMethods;
5129 }
5130 }
5131 }
5132
5133 /* Default case. Handles, amongst others, "nfs".
5134 ** Test byte-range lock using fcntl(). If the call succeeds,
5135 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005136 */
drh7708e972008-11-29 00:56:52 +00005137 lockInfo.l_len = 1;
5138 lockInfo.l_start = 0;
5139 lockInfo.l_whence = SEEK_SET;
5140 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005141 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005142 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5143 return &nfsIoMethods;
5144 } else {
5145 return &posixIoMethods;
5146 }
drh7708e972008-11-29 00:56:52 +00005147 }else{
5148 return &dotlockIoMethods;
5149 }
5150}
drh0c2694b2009-09-03 16:23:44 +00005151static const sqlite3_io_methods
5152 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005153
drhd2cb50b2009-01-09 21:41:17 +00005154#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005155
chw78a13182009-04-07 05:35:03 +00005156#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5157/*
5158** This "finder" function attempts to determine the best locking strategy
5159** for the database file "filePath". It then returns the sqlite3_io_methods
5160** object that implements that strategy.
5161**
5162** This is for VXWorks only.
5163*/
5164static const sqlite3_io_methods *autolockIoFinderImpl(
5165 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005166 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005167){
5168 struct flock lockInfo;
5169
5170 if( !filePath ){
5171 /* If filePath==NULL that means we are dealing with a transient file
5172 ** that does not need to be locked. */
5173 return &nolockIoMethods;
5174 }
5175
5176 /* Test if fcntl() is supported and use POSIX style locks.
5177 ** Otherwise fall back to the named semaphore method.
5178 */
5179 lockInfo.l_len = 1;
5180 lockInfo.l_start = 0;
5181 lockInfo.l_whence = SEEK_SET;
5182 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005183 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005184 return &posixIoMethods;
5185 }else{
5186 return &semIoMethods;
5187 }
5188}
drh0c2694b2009-09-03 16:23:44 +00005189static const sqlite3_io_methods
5190 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005191
5192#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5193
drh7708e972008-11-29 00:56:52 +00005194/*
5195** An abstract type for a pointer to a IO method finder function:
5196*/
drh0c2694b2009-09-03 16:23:44 +00005197typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005198
aswiftaebf4132008-11-21 00:10:35 +00005199
drh734c9862008-11-28 15:37:20 +00005200/****************************************************************************
5201**************************** sqlite3_vfs methods ****************************
5202**
5203** This division contains the implementation of methods on the
5204** sqlite3_vfs object.
5205*/
5206
danielk1977a3d4c882007-03-23 10:08:38 +00005207/*
danielk1977e339d652008-06-28 11:23:00 +00005208** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005209*/
5210static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005211 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005212 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005213 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005214 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005215 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005216){
drh7708e972008-11-29 00:56:52 +00005217 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005218 unixFile *pNew = (unixFile *)pId;
5219 int rc = SQLITE_OK;
5220
drh8af6c222010-05-14 12:43:01 +00005221 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005222
dan00157392010-10-05 11:33:15 +00005223 /* Usually the path zFilename should not be a relative pathname. The
5224 ** exception is when opening the proxy "conch" file in builds that
5225 ** include the special Apple locking styles.
5226 */
dan00157392010-10-05 11:33:15 +00005227#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005228 assert( zFilename==0 || zFilename[0]=='/'
5229 || pVfs->pAppData==(void*)&autolockIoFinder );
5230#else
5231 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005232#endif
dan00157392010-10-05 11:33:15 +00005233
drhb07028f2011-10-14 21:49:18 +00005234 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005235 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005236
drh308c2a52010-05-14 11:30:18 +00005237 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005238 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005239 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005240 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005241 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005242#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005243 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005244#endif
drhc02a43a2012-01-10 23:18:38 +00005245 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5246 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005247 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005248 }
drh503a6862013-03-01 01:07:17 +00005249 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005250 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005251 }
drh339eb0b2008-03-07 15:34:11 +00005252
drh6c7d5c52008-11-21 20:32:33 +00005253#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005254 pNew->pId = vxworksFindFileId(zFilename);
5255 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005256 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005257 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005258 }
5259#endif
5260
drhc02a43a2012-01-10 23:18:38 +00005261 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005262 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005263 }else{
drh0c2694b2009-09-03 16:23:44 +00005264 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005265#if SQLITE_ENABLE_LOCKING_STYLE
5266 /* Cache zFilename in the locking context (AFP and dotlock override) for
5267 ** proxyLock activation is possible (remote proxy is based on db name)
5268 ** zFilename remains valid until file is closed, to support */
5269 pNew->lockingContext = (void*)zFilename;
5270#endif
drhda0e7682008-07-30 15:27:54 +00005271 }
danielk1977e339d652008-06-28 11:23:00 +00005272
drh7ed97b92010-01-20 13:07:21 +00005273 if( pLockingStyle == &posixIoMethods
5274#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5275 || pLockingStyle == &nfsIoMethods
5276#endif
5277 ){
drh7708e972008-11-29 00:56:52 +00005278 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005279 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005280 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005281 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005282 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005283 ** in two scenarios:
5284 **
5285 ** (a) A call to fstat() failed.
5286 ** (b) A malloc failed.
5287 **
5288 ** Scenario (b) may only occur if the process is holding no other
5289 ** file descriptors open on the same file. If there were other file
5290 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005291 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005292 ** handle h - as it is guaranteed that no posix locks will be released
5293 ** by doing so.
5294 **
5295 ** If scenario (a) caused the error then things are not so safe. The
5296 ** implicit assumption here is that if fstat() fails, things are in
5297 ** such bad shape that dropping a lock or two doesn't matter much.
5298 */
drh0e9365c2011-03-02 02:08:13 +00005299 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005300 h = -1;
5301 }
drh7708e972008-11-29 00:56:52 +00005302 unixLeaveMutex();
5303 }
danielk1977e339d652008-06-28 11:23:00 +00005304
drhd2cb50b2009-01-09 21:41:17 +00005305#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005306 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005307 /* AFP locking uses the file path so it needs to be included in
5308 ** the afpLockingContext.
5309 */
5310 afpLockingContext *pCtx;
5311 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5312 if( pCtx==0 ){
5313 rc = SQLITE_NOMEM;
5314 }else{
5315 /* NB: zFilename exists and remains valid until the file is closed
5316 ** according to requirement F11141. So we do not need to make a
5317 ** copy of the filename. */
5318 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005319 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005320 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005321 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005322 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005323 if( rc!=SQLITE_OK ){
5324 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005325 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005326 h = -1;
5327 }
drh7708e972008-11-29 00:56:52 +00005328 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005329 }
drh7708e972008-11-29 00:56:52 +00005330 }
5331#endif
danielk1977e339d652008-06-28 11:23:00 +00005332
drh7708e972008-11-29 00:56:52 +00005333 else if( pLockingStyle == &dotlockIoMethods ){
5334 /* Dotfile locking uses the file path so it needs to be included in
5335 ** the dotlockLockingContext
5336 */
5337 char *zLockFile;
5338 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005339 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005340 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005341 zLockFile = (char *)sqlite3_malloc(nFilename);
5342 if( zLockFile==0 ){
5343 rc = SQLITE_NOMEM;
5344 }else{
5345 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005346 }
drh7708e972008-11-29 00:56:52 +00005347 pNew->lockingContext = zLockFile;
5348 }
danielk1977e339d652008-06-28 11:23:00 +00005349
drh6c7d5c52008-11-21 20:32:33 +00005350#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005351 else if( pLockingStyle == &semIoMethods ){
5352 /* Named semaphore locking uses the file path so it needs to be
5353 ** included in the semLockingContext
5354 */
5355 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005356 rc = findInodeInfo(pNew, &pNew->pInode);
5357 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5358 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005359 int n;
drh2238dcc2009-08-27 17:56:20 +00005360 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005361 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005362 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005363 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005364 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5365 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005366 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005367 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005368 }
chw97185482008-11-17 08:05:31 +00005369 }
drh7708e972008-11-29 00:56:52 +00005370 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005371 }
drh7708e972008-11-29 00:56:52 +00005372#endif
aswift5b1a2562008-08-22 00:22:35 +00005373
5374 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005375#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005376 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005377 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005378 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005379 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005380 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005381 }
chw97185482008-11-17 08:05:31 +00005382#endif
danielk1977e339d652008-06-28 11:23:00 +00005383 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005384 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005385 }else{
drh7708e972008-11-29 00:56:52 +00005386 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005387 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005388 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005389 }
danielk1977e339d652008-06-28 11:23:00 +00005390 return rc;
drh054889e2005-11-30 03:20:31 +00005391}
drh9c06c952005-11-26 00:25:00 +00005392
danielk1977ad94b582007-08-20 06:44:22 +00005393/*
drh8b3cf822010-06-01 21:02:51 +00005394** Return the name of a directory in which to put temporary files.
5395** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005396*/
drh7234c6d2010-06-19 15:10:09 +00005397static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005398 static const char *azDirs[] = {
5399 0,
aswiftaebf4132008-11-21 00:10:35 +00005400 0,
mistachkind95a3d32013-08-30 21:52:38 +00005401 0,
danielk197717b90b52008-06-06 11:11:25 +00005402 "/var/tmp",
5403 "/usr/tmp",
5404 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005405 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005406 };
drh8b3cf822010-06-01 21:02:51 +00005407 unsigned int i;
5408 struct stat buf;
5409 const char *zDir = 0;
5410
5411 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005412 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5413 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005414 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005415 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005416 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005417 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005418 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005419 break;
5420 }
5421 return zDir;
5422}
5423
5424/*
5425** Create a temporary file name in zBuf. zBuf must be allocated
5426** by the calling process and must be big enough to hold at least
5427** pVfs->mxPathname bytes.
5428*/
5429static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005430 static const unsigned char zChars[] =
5431 "abcdefghijklmnopqrstuvwxyz"
5432 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5433 "0123456789";
drh41022642008-11-21 00:24:42 +00005434 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005435 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005436
5437 /* It's odd to simulate an io-error here, but really this is just
5438 ** using the io-error infrastructure to test that SQLite handles this
5439 ** function failing.
5440 */
5441 SimulateIOError( return SQLITE_IOERR );
5442
drh7234c6d2010-06-19 15:10:09 +00005443 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005444 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005445
5446 /* Check that the output buffer is large enough for the temporary file
5447 ** name. If it is not, return SQLITE_ERROR.
5448 */
drhc02a43a2012-01-10 23:18:38 +00005449 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005450 return SQLITE_ERROR;
5451 }
5452
5453 do{
drhc02a43a2012-01-10 23:18:38 +00005454 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005455 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005456 sqlite3_randomness(15, &zBuf[j]);
5457 for(i=0; i<15; i++, j++){
5458 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5459 }
5460 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005461 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005462 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005463 return SQLITE_OK;
5464}
5465
drhd2cb50b2009-01-09 21:41:17 +00005466#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005467/*
5468** Routine to transform a unixFile into a proxy-locking unixFile.
5469** Implementation in the proxy-lock division, but used by unixOpen()
5470** if SQLITE_PREFER_PROXY_LOCKING is defined.
5471*/
5472static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005473#endif
drhc66d5b62008-12-03 22:48:32 +00005474
dan08da86a2009-08-21 17:18:03 +00005475/*
5476** Search for an unused file descriptor that was opened on the database
5477** file (not a journal or master-journal file) identified by pathname
5478** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5479** argument to this function.
5480**
5481** Such a file descriptor may exist if a database connection was closed
5482** but the associated file descriptor could not be closed because some
5483** other file descriptor open on the same file is holding a file-lock.
5484** Refer to comments in the unixClose() function and the lengthy comment
5485** describing "Posix Advisory Locking" at the start of this file for
5486** further details. Also, ticket #4018.
5487**
5488** If a suitable file descriptor is found, then it is returned. If no
5489** such file descriptor is located, -1 is returned.
5490*/
dane946c392009-08-22 11:39:46 +00005491static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5492 UnixUnusedFd *pUnused = 0;
5493
5494 /* Do not search for an unused file descriptor on vxworks. Not because
5495 ** vxworks would not benefit from the change (it might, we're not sure),
5496 ** but because no way to test it is currently available. It is better
5497 ** not to risk breaking vxworks support for the sake of such an obscure
5498 ** feature. */
5499#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005500 struct stat sStat; /* Results of stat() call */
5501
5502 /* A stat() call may fail for various reasons. If this happens, it is
5503 ** almost certain that an open() call on the same path will also fail.
5504 ** For this reason, if an error occurs in the stat() call here, it is
5505 ** ignored and -1 is returned. The caller will try to open a new file
5506 ** descriptor on the same path, fail, and return an error to SQLite.
5507 **
5508 ** Even if a subsequent open() call does succeed, the consequences of
5509 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005510 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005511 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005512
5513 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005514 pInode = inodeList;
5515 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5516 || pInode->fileId.ino!=sStat.st_ino) ){
5517 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005518 }
drh8af6c222010-05-14 12:43:01 +00005519 if( pInode ){
dane946c392009-08-22 11:39:46 +00005520 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005521 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005522 pUnused = *pp;
5523 if( pUnused ){
5524 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005525 }
5526 }
5527 unixLeaveMutex();
5528 }
dane946c392009-08-22 11:39:46 +00005529#endif /* if !OS_VXWORKS */
5530 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005531}
danielk197717b90b52008-06-06 11:11:25 +00005532
5533/*
danddb0ac42010-07-14 14:48:58 +00005534** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005535** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005536** and a value suitable for passing as the third argument to open(2) is
5537** written to *pMode. If an IO error occurs, an SQLite error code is
5538** returned and the value of *pMode is not modified.
5539**
drh8c815d12012-02-13 20:16:37 +00005540** In most cases cases, this routine sets *pMode to 0, which will become
5541** an indication to robust_open() to create the file using
5542** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5543** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005544** this function queries the file-system for the permissions on the
5545** corresponding database file and sets *pMode to this value. Whenever
5546** possible, WAL and journal files are created using the same permissions
5547** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005548**
5549** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5550** original filename is unavailable. But 8_3_NAMES is only used for
5551** FAT filesystems and permissions do not matter there, so just use
5552** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005553*/
5554static int findCreateFileMode(
5555 const char *zPath, /* Path of file (possibly) being created */
5556 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005557 mode_t *pMode, /* OUT: Permissions to open file with */
5558 uid_t *pUid, /* OUT: uid to set on the file */
5559 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005560){
5561 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005562 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005563 *pUid = 0;
5564 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005565 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005566 char zDb[MAX_PATHNAME+1]; /* Database file path */
5567 int nDb; /* Number of valid bytes in zDb */
5568 struct stat sStat; /* Output of stat() on database file */
5569
dana0c989d2010-11-05 18:07:37 +00005570 /* zPath is a path to a WAL or journal file. The following block derives
5571 ** the path to the associated database file from zPath. This block handles
5572 ** the following naming conventions:
5573 **
5574 ** "<path to db>-journal"
5575 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005576 ** "<path to db>-journalNN"
5577 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005578 **
drhd337c5b2011-10-20 18:23:35 +00005579 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005580 ** used by the test_multiplex.c module.
5581 */
5582 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005583#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005584 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005585 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005586#else
5587 while( zPath[nDb]!='-' ){
5588 assert( nDb>0 );
5589 assert( zPath[nDb]!='\n' );
5590 nDb--;
5591 }
5592#endif
danddb0ac42010-07-14 14:48:58 +00005593 memcpy(zDb, zPath, nDb);
5594 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005595
drh58384f12011-07-28 00:14:45 +00005596 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005597 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005598 *pUid = sStat.st_uid;
5599 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005600 }else{
5601 rc = SQLITE_IOERR_FSTAT;
5602 }
5603 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5604 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005605 }
5606 return rc;
5607}
5608
5609/*
danielk1977ad94b582007-08-20 06:44:22 +00005610** Open the file zPath.
5611**
danielk1977b4b47412007-08-17 15:53:36 +00005612** Previously, the SQLite OS layer used three functions in place of this
5613** one:
5614**
5615** sqlite3OsOpenReadWrite();
5616** sqlite3OsOpenReadOnly();
5617** sqlite3OsOpenExclusive();
5618**
5619** These calls correspond to the following combinations of flags:
5620**
5621** ReadWrite() -> (READWRITE | CREATE)
5622** ReadOnly() -> (READONLY)
5623** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5624**
5625** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5626** true, the file was configured to be automatically deleted when the
5627** file handle closed. To achieve the same effect using this new
5628** interface, add the DELETEONCLOSE flag to those specified above for
5629** OpenExclusive().
5630*/
5631static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005632 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5633 const char *zPath, /* Pathname of file to be opened */
5634 sqlite3_file *pFile, /* The file descriptor to be filled in */
5635 int flags, /* Input flags to control the opening */
5636 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005637){
dan08da86a2009-08-21 17:18:03 +00005638 unixFile *p = (unixFile *)pFile;
5639 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005640 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005641 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005642 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005643 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005644 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005645
5646 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5647 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5648 int isCreate = (flags & SQLITE_OPEN_CREATE);
5649 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5650 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005651#if SQLITE_ENABLE_LOCKING_STYLE
5652 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5653#endif
drh3d4435b2011-08-26 20:55:50 +00005654#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5655 struct statfs fsInfo;
5656#endif
danielk1977b4b47412007-08-17 15:53:36 +00005657
danielk1977fee2d252007-08-18 10:59:19 +00005658 /* If creating a master or main-file journal, this function will open
5659 ** a file-descriptor on the directory too. The first time unixSync()
5660 ** is called the directory file descriptor will be fsync()ed and close()d.
5661 */
drh0059eae2011-08-08 23:48:40 +00005662 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005663 eType==SQLITE_OPEN_MASTER_JOURNAL
5664 || eType==SQLITE_OPEN_MAIN_JOURNAL
5665 || eType==SQLITE_OPEN_WAL
5666 ));
danielk1977fee2d252007-08-18 10:59:19 +00005667
danielk197717b90b52008-06-06 11:11:25 +00005668 /* If argument zPath is a NULL pointer, this function is required to open
5669 ** a temporary file. Use this buffer to store the file name in.
5670 */
drhc02a43a2012-01-10 23:18:38 +00005671 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005672 const char *zName = zPath;
5673
danielk1977fee2d252007-08-18 10:59:19 +00005674 /* Check the following statements are true:
5675 **
5676 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5677 ** (b) if CREATE is set, then READWRITE must also be set, and
5678 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005679 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005680 */
danielk1977b4b47412007-08-17 15:53:36 +00005681 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005682 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005683 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005684 assert(isDelete==0 || isCreate);
5685
danddb0ac42010-07-14 14:48:58 +00005686 /* The main DB, main journal, WAL file and master journal are never
5687 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005688 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5689 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5690 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005691 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005692
danielk1977fee2d252007-08-18 10:59:19 +00005693 /* Assert that the upper layer has set one of the "file-type" flags. */
5694 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5695 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5696 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005697 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005698 );
5699
drhb00d8622014-01-01 15:18:36 +00005700 /* Detect a pid change and reset the PRNG. There is a race condition
5701 ** here such that two or more threads all trying to open databases at
5702 ** the same instant might all reset the PRNG. But multiple resets
5703 ** are harmless.
5704 */
5705 if( randomnessPid!=getpid() ){
5706 randomnessPid = getpid();
5707 sqlite3_randomness(0,0);
5708 }
5709
dan08da86a2009-08-21 17:18:03 +00005710 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005711
dan08da86a2009-08-21 17:18:03 +00005712 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005713 UnixUnusedFd *pUnused;
5714 pUnused = findReusableFd(zName, flags);
5715 if( pUnused ){
5716 fd = pUnused->fd;
5717 }else{
dan6aa657f2009-08-24 18:57:58 +00005718 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005719 if( !pUnused ){
5720 return SQLITE_NOMEM;
5721 }
5722 }
5723 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005724
5725 /* Database filenames are double-zero terminated if they are not
5726 ** URIs with parameters. Hence, they can always be passed into
5727 ** sqlite3_uri_parameter(). */
5728 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5729
dan08da86a2009-08-21 17:18:03 +00005730 }else if( !zName ){
5731 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005732 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005733 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005734 if( rc!=SQLITE_OK ){
5735 return rc;
5736 }
5737 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005738
5739 /* Generated temporary filenames are always double-zero terminated
5740 ** for use by sqlite3_uri_parameter(). */
5741 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005742 }
5743
dan08da86a2009-08-21 17:18:03 +00005744 /* Determine the value of the flags parameter passed to POSIX function
5745 ** open(). These must be calculated even if open() is not called, as
5746 ** they may be stored as part of the file handle and used by the
5747 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005748 if( isReadonly ) openFlags |= O_RDONLY;
5749 if( isReadWrite ) openFlags |= O_RDWR;
5750 if( isCreate ) openFlags |= O_CREAT;
5751 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5752 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005753
danielk1977b4b47412007-08-17 15:53:36 +00005754 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005755 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005756 uid_t uid; /* Userid for the file */
5757 gid_t gid; /* Groupid for the file */
5758 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005759 if( rc!=SQLITE_OK ){
5760 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005761 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005762 return rc;
5763 }
drhad4f1e52011-03-04 15:43:57 +00005764 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005765 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005766 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5767 /* Failed to open the file for read/write access. Try read-only. */
5768 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005769 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005770 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005771 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005772 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005773 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005774 }
5775 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005776 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005777 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005778 }
drhac7c3ac2012-02-11 19:23:48 +00005779
5780 /* If this process is running as root and if creating a new rollback
5781 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005782 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005783 */
5784 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005785 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005786 }
danielk1977b4b47412007-08-17 15:53:36 +00005787 }
dan08da86a2009-08-21 17:18:03 +00005788 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005789 if( pOutFlags ){
5790 *pOutFlags = flags;
5791 }
5792
dane946c392009-08-22 11:39:46 +00005793 if( p->pUnused ){
5794 p->pUnused->fd = fd;
5795 p->pUnused->flags = flags;
5796 }
5797
danielk1977b4b47412007-08-17 15:53:36 +00005798 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005799#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005800 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005801#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5802 zPath = sqlite3_mprintf("%s", zName);
5803 if( zPath==0 ){
5804 robust_close(p, fd, __LINE__);
5805 return SQLITE_NOMEM;
5806 }
chw97185482008-11-17 08:05:31 +00005807#else
drh036ac7f2011-08-08 23:18:05 +00005808 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005809#endif
danielk1977b4b47412007-08-17 15:53:36 +00005810 }
drh41022642008-11-21 00:24:42 +00005811#if SQLITE_ENABLE_LOCKING_STYLE
5812 else{
dan08da86a2009-08-21 17:18:03 +00005813 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005814 }
5815#endif
5816
drhda0e7682008-07-30 15:27:54 +00005817 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005818
drh7ed97b92010-01-20 13:07:21 +00005819
5820#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005821 if( fstatfs(fd, &fsInfo) == -1 ){
5822 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005823 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005824 return SQLITE_IOERR_ACCESS;
5825 }
5826 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5827 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5828 }
5829#endif
drhc02a43a2012-01-10 23:18:38 +00005830
5831 /* Set up appropriate ctrlFlags */
5832 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5833 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5834 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5835 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5836 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5837
drh7ed97b92010-01-20 13:07:21 +00005838#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005839#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005840 isAutoProxy = 1;
5841#endif
5842 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005843 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5844 int useProxy = 0;
5845
dan08da86a2009-08-21 17:18:03 +00005846 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5847 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005848 if( envforce!=NULL ){
5849 useProxy = atoi(envforce)>0;
5850 }else{
aswiftaebf4132008-11-21 00:10:35 +00005851 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005852 /* In theory, the close(fd) call is sub-optimal. If the file opened
5853 ** with fd is a database file, and there are other connections open
5854 ** on that file that are currently holding advisory locks on it,
5855 ** then the call to close() will cancel those locks. In practice,
5856 ** we're assuming that statfs() doesn't fail very often. At least
5857 ** not while other file descriptors opened by the same process on
5858 ** the same file are working. */
5859 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005860 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005861 rc = SQLITE_IOERR_ACCESS;
5862 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005863 }
5864 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5865 }
5866 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005867 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005868 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005869 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005870 if( rc!=SQLITE_OK ){
5871 /* Use unixClose to clean up the resources added in fillInUnixFile
5872 ** and clear all the structure's references. Specifically,
5873 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5874 */
5875 unixClose(pFile);
5876 return rc;
5877 }
aswiftaebf4132008-11-21 00:10:35 +00005878 }
dane946c392009-08-22 11:39:46 +00005879 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005880 }
5881 }
5882#endif
5883
drhc02a43a2012-01-10 23:18:38 +00005884 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5885
dane946c392009-08-22 11:39:46 +00005886open_finished:
5887 if( rc!=SQLITE_OK ){
5888 sqlite3_free(p->pUnused);
5889 }
5890 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005891}
5892
dane946c392009-08-22 11:39:46 +00005893
danielk1977b4b47412007-08-17 15:53:36 +00005894/*
danielk1977fee2d252007-08-18 10:59:19 +00005895** Delete the file at zPath. If the dirSync argument is true, fsync()
5896** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005897*/
drh6b9d6dd2008-12-03 19:34:47 +00005898static int unixDelete(
5899 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5900 const char *zPath, /* Name of file to be deleted */
5901 int dirSync /* If true, fsync() directory after deleting file */
5902){
danielk1977fee2d252007-08-18 10:59:19 +00005903 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005904 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005905 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005906 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005907 if( errno==ENOENT
5908#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005909 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005910#endif
5911 ){
dan9fc5b4a2012-11-09 20:17:26 +00005912 rc = SQLITE_IOERR_DELETE_NOENT;
5913 }else{
drhb4308162012-11-09 21:40:02 +00005914 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005915 }
drhb4308162012-11-09 21:40:02 +00005916 return rc;
drh5d4feff2010-07-14 01:45:22 +00005917 }
danielk1977d39fa702008-10-16 13:27:40 +00005918#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005919 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005920 int fd;
drh90315a22011-08-10 01:52:12 +00005921 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005922 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005923#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005924 if( fsync(fd)==-1 )
5925#else
5926 if( fsync(fd) )
5927#endif
5928 {
dane18d4952011-02-21 11:46:24 +00005929 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005930 }
drh0e9365c2011-03-02 02:08:13 +00005931 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005932 }else if( rc==SQLITE_CANTOPEN ){
5933 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005934 }
5935 }
danielk1977d138dd82008-10-15 16:02:48 +00005936#endif
danielk1977fee2d252007-08-18 10:59:19 +00005937 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005938}
5939
danielk197790949c22007-08-17 16:50:38 +00005940/*
mistachkin48864df2013-03-21 21:20:32 +00005941** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005942** test performed depends on the value of flags:
5943**
5944** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5945** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5946** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5947**
5948** Otherwise return 0.
5949*/
danielk1977861f7452008-06-05 11:39:11 +00005950static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005951 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5952 const char *zPath, /* Path of the file to examine */
5953 int flags, /* What do we want to learn about the zPath file? */
5954 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005955){
rse25c0d1a2007-09-20 08:38:14 +00005956 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005957 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005958 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005959 switch( flags ){
5960 case SQLITE_ACCESS_EXISTS:
5961 amode = F_OK;
5962 break;
5963 case SQLITE_ACCESS_READWRITE:
5964 amode = W_OK|R_OK;
5965 break;
drh50d3f902007-08-27 21:10:36 +00005966 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005967 amode = R_OK;
5968 break;
5969
5970 default:
5971 assert(!"Invalid flags argument");
5972 }
drh99ab3b12011-03-02 15:09:07 +00005973 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005974 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5975 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005976 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005977 *pResOut = 0;
5978 }
5979 }
danielk1977861f7452008-06-05 11:39:11 +00005980 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005981}
5982
danielk1977b4b47412007-08-17 15:53:36 +00005983
5984/*
5985** Turn a relative pathname into a full pathname. The relative path
5986** is stored as a nul-terminated string in the buffer pointed to by
5987** zPath.
5988**
5989** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5990** (in this case, MAX_PATHNAME bytes). The full-path is written to
5991** this buffer before returning.
5992*/
danielk1977adfb9b02007-09-17 07:02:56 +00005993static int unixFullPathname(
5994 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5995 const char *zPath, /* Possibly relative input path */
5996 int nOut, /* Size of output buffer in bytes */
5997 char *zOut /* Output buffer */
5998){
danielk1977843e65f2007-09-01 16:16:15 +00005999
6000 /* It's odd to simulate an io-error here, but really this is just
6001 ** using the io-error infrastructure to test that SQLite handles this
6002 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006003 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006004 */
6005 SimulateIOError( return SQLITE_ERROR );
6006
drh153c62c2007-08-24 03:51:33 +00006007 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006008 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006009
drh3c7f2dc2007-12-06 13:26:20 +00006010 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00006011 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00006012 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006013 }else{
6014 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00006015 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006016 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006017 }
drhea678832008-12-10 19:26:22 +00006018 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00006019 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006020 }
6021 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006022}
6023
drh0ccebe72005-06-07 22:22:50 +00006024
drh761df872006-12-21 01:29:22 +00006025#ifndef SQLITE_OMIT_LOAD_EXTENSION
6026/*
6027** Interfaces for opening a shared library, finding entry points
6028** within the shared library, and closing the shared library.
6029*/
6030#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006031static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6032 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006033 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6034}
danielk197795c8a542007-09-01 06:51:27 +00006035
6036/*
6037** SQLite calls this function immediately after a call to unixDlSym() or
6038** unixDlOpen() fails (returns a null pointer). If a more detailed error
6039** message is available, it is written to zBufOut. If no error message
6040** is available, zBufOut is left unmodified and SQLite uses a default
6041** error message.
6042*/
danielk1977397d65f2008-11-19 11:35:39 +00006043static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006044 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006045 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006046 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006047 zErr = dlerror();
6048 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006049 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006050 }
drh6c7d5c52008-11-21 20:32:33 +00006051 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006052}
drh1875f7a2008-12-08 18:19:17 +00006053static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6054 /*
6055 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6056 ** cast into a pointer to a function. And yet the library dlsym() routine
6057 ** returns a void* which is really a pointer to a function. So how do we
6058 ** use dlsym() with -pedantic-errors?
6059 **
6060 ** Variable x below is defined to be a pointer to a function taking
6061 ** parameters void* and const char* and returning a pointer to a function.
6062 ** We initialize x by assigning it a pointer to the dlsym() function.
6063 ** (That assignment requires a cast.) Then we call the function that
6064 ** x points to.
6065 **
6066 ** This work-around is unlikely to work correctly on any system where
6067 ** you really cannot cast a function pointer into void*. But then, on the
6068 ** other hand, dlsym() will not work on such a system either, so we have
6069 ** not really lost anything.
6070 */
6071 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006072 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006073 x = (void(*(*)(void*,const char*))(void))dlsym;
6074 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006075}
danielk1977397d65f2008-11-19 11:35:39 +00006076static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6077 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006078 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006079}
danielk1977b4b47412007-08-17 15:53:36 +00006080#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6081 #define unixDlOpen 0
6082 #define unixDlError 0
6083 #define unixDlSym 0
6084 #define unixDlClose 0
6085#endif
6086
6087/*
danielk197790949c22007-08-17 16:50:38 +00006088** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006089*/
danielk1977397d65f2008-11-19 11:35:39 +00006090static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6091 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006092 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006093
drhbbd42a62004-05-22 17:41:58 +00006094 /* We have to initialize zBuf to prevent valgrind from reporting
6095 ** errors. The reports issued by valgrind are incorrect - we would
6096 ** prefer that the randomness be increased by making use of the
6097 ** uninitialized space in zBuf - but valgrind errors tend to worry
6098 ** some users. Rather than argue, it seems easier just to initialize
6099 ** the whole array and silence valgrind, even if that means less randomness
6100 ** in the random seed.
6101 **
6102 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006103 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006104 ** tests repeatable.
6105 */
danielk1977b4b47412007-08-17 15:53:36 +00006106 memset(zBuf, 0, nBuf);
drhb00d8622014-01-01 15:18:36 +00006107 randomnessPid = getpid();
drhbbd42a62004-05-22 17:41:58 +00006108#if !defined(SQLITE_TEST)
6109 {
drhb00d8622014-01-01 15:18:36 +00006110 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006111 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006112 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006113 time_t t;
6114 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006115 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006116 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6117 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6118 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006119 }else{
drhc18b4042012-02-10 03:10:27 +00006120 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006121 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006122 }
drhbbd42a62004-05-22 17:41:58 +00006123 }
6124#endif
drh72cbd072008-10-14 17:58:38 +00006125 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006126}
6127
danielk1977b4b47412007-08-17 15:53:36 +00006128
drhbbd42a62004-05-22 17:41:58 +00006129/*
6130** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006131** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006132** The return value is the number of microseconds of sleep actually
6133** requested from the underlying operating system, a number which
6134** might be greater than or equal to the argument, but not less
6135** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006136*/
danielk1977397d65f2008-11-19 11:35:39 +00006137static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006138#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006139 struct timespec sp;
6140
6141 sp.tv_sec = microseconds / 1000000;
6142 sp.tv_nsec = (microseconds % 1000000) * 1000;
6143 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006144 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006145 return microseconds;
6146#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006147 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006148 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006149 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006150#else
danielk1977b4b47412007-08-17 15:53:36 +00006151 int seconds = (microseconds+999999)/1000000;
6152 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006153 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006154 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006155#endif
drh88f474a2006-01-02 20:00:12 +00006156}
6157
6158/*
drh6b9d6dd2008-12-03 19:34:47 +00006159** The following variable, if set to a non-zero value, is interpreted as
6160** the number of seconds since 1970 and is used to set the result of
6161** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006162*/
6163#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006164int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006165#endif
6166
6167/*
drhb7e8ea22010-05-03 14:32:30 +00006168** Find the current time (in Universal Coordinated Time). Write into *piNow
6169** the current time and date as a Julian Day number times 86_400_000. In
6170** other words, write into *piNow the number of milliseconds since the Julian
6171** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6172** proleptic Gregorian calendar.
6173**
drh31702252011-10-12 23:13:43 +00006174** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6175** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006176*/
6177static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6178 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006179 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006180#if defined(NO_GETTOD)
6181 time_t t;
6182 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006183 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006184#elif OS_VXWORKS
6185 struct timespec sNow;
6186 clock_gettime(CLOCK_REALTIME, &sNow);
6187 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6188#else
6189 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006190 if( gettimeofday(&sNow, 0)==0 ){
6191 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6192 }else{
6193 rc = SQLITE_ERROR;
6194 }
drhb7e8ea22010-05-03 14:32:30 +00006195#endif
6196
6197#ifdef SQLITE_TEST
6198 if( sqlite3_current_time ){
6199 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6200 }
6201#endif
6202 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006203 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006204}
6205
6206/*
drhbbd42a62004-05-22 17:41:58 +00006207** Find the current time (in Universal Coordinated Time). Write the
6208** current time and date as a Julian Day number into *prNow and
6209** return 0. Return 1 if the time and date cannot be found.
6210*/
danielk1977397d65f2008-11-19 11:35:39 +00006211static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006212 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006213 int rc;
drhff828942010-06-26 21:34:06 +00006214 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006215 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006216 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006217 return rc;
drhbbd42a62004-05-22 17:41:58 +00006218}
danielk1977b4b47412007-08-17 15:53:36 +00006219
drh6b9d6dd2008-12-03 19:34:47 +00006220/*
6221** We added the xGetLastError() method with the intention of providing
6222** better low-level error messages when operating-system problems come up
6223** during SQLite operation. But so far, none of that has been implemented
6224** in the core. So this routine is never called. For now, it is merely
6225** a place-holder.
6226*/
danielk1977397d65f2008-11-19 11:35:39 +00006227static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6228 UNUSED_PARAMETER(NotUsed);
6229 UNUSED_PARAMETER(NotUsed2);
6230 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006231 return 0;
6232}
6233
drhf2424c52010-04-26 00:04:55 +00006234
6235/*
drh734c9862008-11-28 15:37:20 +00006236************************ End of sqlite3_vfs methods ***************************
6237******************************************************************************/
6238
drh715ff302008-12-03 22:32:44 +00006239/******************************************************************************
6240************************** Begin Proxy Locking ********************************
6241**
6242** Proxy locking is a "uber-locking-method" in this sense: It uses the
6243** other locking methods on secondary lock files. Proxy locking is a
6244** meta-layer over top of the primitive locking implemented above. For
6245** this reason, the division that implements of proxy locking is deferred
6246** until late in the file (here) after all of the other I/O methods have
6247** been defined - so that the primitive locking methods are available
6248** as services to help with the implementation of proxy locking.
6249**
6250****
6251**
6252** The default locking schemes in SQLite use byte-range locks on the
6253** database file to coordinate safe, concurrent access by multiple readers
6254** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6255** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6256** as POSIX read & write locks over fixed set of locations (via fsctl),
6257** on AFP and SMB only exclusive byte-range locks are available via fsctl
6258** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6259** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6260** address in the shared range is taken for a SHARED lock, the entire
6261** shared range is taken for an EXCLUSIVE lock):
6262**
drhf2f105d2012-08-20 15:53:54 +00006263** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006264** RESERVED_BYTE 0x40000001
6265** SHARED_RANGE 0x40000002 -> 0x40000200
6266**
6267** This works well on the local file system, but shows a nearly 100x
6268** slowdown in read performance on AFP because the AFP client disables
6269** the read cache when byte-range locks are present. Enabling the read
6270** cache exposes a cache coherency problem that is present on all OS X
6271** supported network file systems. NFS and AFP both observe the
6272** close-to-open semantics for ensuring cache coherency
6273** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6274** address the requirements for concurrent database access by multiple
6275** readers and writers
6276** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6277**
6278** To address the performance and cache coherency issues, proxy file locking
6279** changes the way database access is controlled by limiting access to a
6280** single host at a time and moving file locks off of the database file
6281** and onto a proxy file on the local file system.
6282**
6283**
6284** Using proxy locks
6285** -----------------
6286**
6287** C APIs
6288**
6289** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6290** <proxy_path> | ":auto:");
6291** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6292**
6293**
6294** SQL pragmas
6295**
6296** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6297** PRAGMA [database.]lock_proxy_file
6298**
6299** Specifying ":auto:" means that if there is a conch file with a matching
6300** host ID in it, the proxy path in the conch file will be used, otherwise
6301** a proxy path based on the user's temp dir
6302** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6303** actual proxy file name is generated from the name and path of the
6304** database file. For example:
6305**
6306** For database path "/Users/me/foo.db"
6307** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6308**
6309** Once a lock proxy is configured for a database connection, it can not
6310** be removed, however it may be switched to a different proxy path via
6311** the above APIs (assuming the conch file is not being held by another
6312** connection or process).
6313**
6314**
6315** How proxy locking works
6316** -----------------------
6317**
6318** Proxy file locking relies primarily on two new supporting files:
6319**
6320** * conch file to limit access to the database file to a single host
6321** at a time
6322**
6323** * proxy file to act as a proxy for the advisory locks normally
6324** taken on the database
6325**
6326** The conch file - to use a proxy file, sqlite must first "hold the conch"
6327** by taking an sqlite-style shared lock on the conch file, reading the
6328** contents and comparing the host's unique host ID (see below) and lock
6329** proxy path against the values stored in the conch. The conch file is
6330** stored in the same directory as the database file and the file name
6331** is patterned after the database file name as ".<databasename>-conch".
6332** If the conch file does not exist, or it's contents do not match the
6333** host ID and/or proxy path, then the lock is escalated to an exclusive
6334** lock and the conch file contents is updated with the host ID and proxy
6335** path and the lock is downgraded to a shared lock again. If the conch
6336** is held by another process (with a shared lock), the exclusive lock
6337** will fail and SQLITE_BUSY is returned.
6338**
6339** The proxy file - a single-byte file used for all advisory file locks
6340** normally taken on the database file. This allows for safe sharing
6341** of the database file for multiple readers and writers on the same
6342** host (the conch ensures that they all use the same local lock file).
6343**
drh715ff302008-12-03 22:32:44 +00006344** Requesting the lock proxy does not immediately take the conch, it is
6345** only taken when the first request to lock database file is made.
6346** This matches the semantics of the traditional locking behavior, where
6347** opening a connection to a database file does not take a lock on it.
6348** The shared lock and an open file descriptor are maintained until
6349** the connection to the database is closed.
6350**
6351** The proxy file and the lock file are never deleted so they only need
6352** to be created the first time they are used.
6353**
6354** Configuration options
6355** ---------------------
6356**
6357** SQLITE_PREFER_PROXY_LOCKING
6358**
6359** Database files accessed on non-local file systems are
6360** automatically configured for proxy locking, lock files are
6361** named automatically using the same logic as
6362** PRAGMA lock_proxy_file=":auto:"
6363**
6364** SQLITE_PROXY_DEBUG
6365**
6366** Enables the logging of error messages during host id file
6367** retrieval and creation
6368**
drh715ff302008-12-03 22:32:44 +00006369** LOCKPROXYDIR
6370**
6371** Overrides the default directory used for lock proxy files that
6372** are named automatically via the ":auto:" setting
6373**
6374** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6375**
6376** Permissions to use when creating a directory for storing the
6377** lock proxy files, only used when LOCKPROXYDIR is not set.
6378**
6379**
6380** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6381** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6382** force proxy locking to be used for every database file opened, and 0
6383** will force automatic proxy locking to be disabled for all database
6384** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6385** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6386*/
6387
6388/*
6389** Proxy locking is only available on MacOSX
6390*/
drhd2cb50b2009-01-09 21:41:17 +00006391#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006392
drh715ff302008-12-03 22:32:44 +00006393/*
6394** The proxyLockingContext has the path and file structures for the remote
6395** and local proxy files in it
6396*/
6397typedef struct proxyLockingContext proxyLockingContext;
6398struct proxyLockingContext {
6399 unixFile *conchFile; /* Open conch file */
6400 char *conchFilePath; /* Name of the conch file */
6401 unixFile *lockProxy; /* Open proxy lock file */
6402 char *lockProxyPath; /* Name of the proxy lock file */
6403 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006404 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006405 void *oldLockingContext; /* Original lockingcontext to restore on close */
6406 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6407};
6408
drh7ed97b92010-01-20 13:07:21 +00006409/*
6410** The proxy lock file path for the database at dbPath is written into lPath,
6411** which must point to valid, writable memory large enough for a maxLen length
6412** file path.
drh715ff302008-12-03 22:32:44 +00006413*/
drh715ff302008-12-03 22:32:44 +00006414static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6415 int len;
6416 int dbLen;
6417 int i;
6418
6419#ifdef LOCKPROXYDIR
6420 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6421#else
6422# ifdef _CS_DARWIN_USER_TEMP_DIR
6423 {
drh7ed97b92010-01-20 13:07:21 +00006424 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006425 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6426 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006427 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006428 }
drh7ed97b92010-01-20 13:07:21 +00006429 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006430 }
6431# else
6432 len = strlcpy(lPath, "/tmp/", maxLen);
6433# endif
6434#endif
6435
6436 if( lPath[len-1]!='/' ){
6437 len = strlcat(lPath, "/", maxLen);
6438 }
6439
6440 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006441 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006442 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006443 char c = dbPath[i];
6444 lPath[i+len] = (c=='/')?'_':c;
6445 }
6446 lPath[i+len]='\0';
6447 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006448 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006449 return SQLITE_OK;
6450}
6451
drh7ed97b92010-01-20 13:07:21 +00006452/*
6453 ** Creates the lock file and any missing directories in lockPath
6454 */
6455static int proxyCreateLockPath(const char *lockPath){
6456 int i, len;
6457 char buf[MAXPATHLEN];
6458 int start = 0;
6459
6460 assert(lockPath!=NULL);
6461 /* try to create all the intermediate directories */
6462 len = (int)strlen(lockPath);
6463 buf[0] = lockPath[0];
6464 for( i=1; i<len; i++ ){
6465 if( lockPath[i] == '/' && (i - start > 0) ){
6466 /* only mkdir if leaf dir != "." or "/" or ".." */
6467 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6468 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6469 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006470 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006471 int err=errno;
6472 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006473 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006474 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006475 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006476 return err;
6477 }
6478 }
6479 }
6480 start=i+1;
6481 }
6482 buf[i] = lockPath[i];
6483 }
drh308c2a52010-05-14 11:30:18 +00006484 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006485 return 0;
6486}
6487
drh715ff302008-12-03 22:32:44 +00006488/*
6489** Create a new VFS file descriptor (stored in memory obtained from
6490** sqlite3_malloc) and open the file named "path" in the file descriptor.
6491**
6492** The caller is responsible not only for closing the file descriptor
6493** but also for freeing the memory associated with the file descriptor.
6494*/
drh7ed97b92010-01-20 13:07:21 +00006495static int proxyCreateUnixFile(
6496 const char *path, /* path for the new unixFile */
6497 unixFile **ppFile, /* unixFile created and returned by ref */
6498 int islockfile /* if non zero missing dirs will be created */
6499) {
6500 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006501 unixFile *pNew;
6502 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006503 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006504 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006505 int terrno = 0;
6506 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006507
drh7ed97b92010-01-20 13:07:21 +00006508 /* 1. first try to open/create the file
6509 ** 2. if that fails, and this is a lock file (not-conch), try creating
6510 ** the parent directories and then try again.
6511 ** 3. if that fails, try to open the file read-only
6512 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6513 */
6514 pUnused = findReusableFd(path, openFlags);
6515 if( pUnused ){
6516 fd = pUnused->fd;
6517 }else{
6518 pUnused = sqlite3_malloc(sizeof(*pUnused));
6519 if( !pUnused ){
6520 return SQLITE_NOMEM;
6521 }
6522 }
6523 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006524 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006525 terrno = errno;
6526 if( fd<0 && errno==ENOENT && islockfile ){
6527 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006528 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006529 }
6530 }
6531 }
6532 if( fd<0 ){
6533 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006534 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006535 terrno = errno;
6536 }
6537 if( fd<0 ){
6538 if( islockfile ){
6539 return SQLITE_BUSY;
6540 }
6541 switch (terrno) {
6542 case EACCES:
6543 return SQLITE_PERM;
6544 case EIO:
6545 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6546 default:
drh9978c972010-02-23 17:36:32 +00006547 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006548 }
6549 }
6550
6551 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6552 if( pNew==NULL ){
6553 rc = SQLITE_NOMEM;
6554 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006555 }
6556 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006557 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006558 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006559 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006560 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006561 pUnused->fd = fd;
6562 pUnused->flags = openFlags;
6563 pNew->pUnused = pUnused;
6564
drhc02a43a2012-01-10 23:18:38 +00006565 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006566 if( rc==SQLITE_OK ){
6567 *ppFile = pNew;
6568 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006569 }
drh7ed97b92010-01-20 13:07:21 +00006570end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006571 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006572 sqlite3_free(pNew);
6573 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006574 return rc;
6575}
6576
drh7ed97b92010-01-20 13:07:21 +00006577#ifdef SQLITE_TEST
6578/* simulate multiple hosts by creating unique hostid file paths */
6579int sqlite3_hostid_num = 0;
6580#endif
6581
6582#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6583
drh0ab216a2010-07-02 17:10:40 +00006584/* Not always defined in the headers as it ought to be */
6585extern int gethostuuid(uuid_t id, const struct timespec *wait);
6586
drh7ed97b92010-01-20 13:07:21 +00006587/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6588** bytes of writable memory.
6589*/
6590static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006591 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6592 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006593#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6594 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006595 {
6596 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6597 if( gethostuuid(pHostID, &timeout) ){
6598 int err = errno;
6599 if( pError ){
6600 *pError = err;
6601 }
6602 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006603 }
drh7ed97b92010-01-20 13:07:21 +00006604 }
drh3d4435b2011-08-26 20:55:50 +00006605#else
6606 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006607#endif
drh7ed97b92010-01-20 13:07:21 +00006608#ifdef SQLITE_TEST
6609 /* simulate multiple hosts by creating unique hostid file paths */
6610 if( sqlite3_hostid_num != 0){
6611 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6612 }
6613#endif
6614
6615 return SQLITE_OK;
6616}
6617
6618/* The conch file contains the header, host id and lock file path
6619 */
6620#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6621#define PROXY_HEADERLEN 1 /* conch file header length */
6622#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6623#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6624
6625/*
6626** Takes an open conch file, copies the contents to a new path and then moves
6627** it back. The newly created file's file descriptor is assigned to the
6628** conch file structure and finally the original conch file descriptor is
6629** closed. Returns zero if successful.
6630*/
6631static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6632 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6633 unixFile *conchFile = pCtx->conchFile;
6634 char tPath[MAXPATHLEN];
6635 char buf[PROXY_MAXCONCHLEN];
6636 char *cPath = pCtx->conchFilePath;
6637 size_t readLen = 0;
6638 size_t pathLen = 0;
6639 char errmsg[64] = "";
6640 int fd = -1;
6641 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006642 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006643
6644 /* create a new path by replace the trailing '-conch' with '-break' */
6645 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6646 if( pathLen>MAXPATHLEN || pathLen<6 ||
6647 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006648 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006649 goto end_breaklock;
6650 }
6651 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006652 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006653 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006654 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006655 goto end_breaklock;
6656 }
6657 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006658 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006659 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006660 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006661 goto end_breaklock;
6662 }
drhe562be52011-03-02 18:01:10 +00006663 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006664 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006665 goto end_breaklock;
6666 }
6667 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006668 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006669 goto end_breaklock;
6670 }
6671 rc = 0;
6672 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006673 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006674 conchFile->h = fd;
6675 conchFile->openFlags = O_RDWR | O_CREAT;
6676
6677end_breaklock:
6678 if( rc ){
6679 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006680 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006681 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006682 }
6683 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6684 }
6685 return rc;
6686}
6687
6688/* Take the requested lock on the conch file and break a stale lock if the
6689** host id matches.
6690*/
6691static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6692 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6693 unixFile *conchFile = pCtx->conchFile;
6694 int rc = SQLITE_OK;
6695 int nTries = 0;
6696 struct timespec conchModTime;
6697
drh3d4435b2011-08-26 20:55:50 +00006698 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006699 do {
6700 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6701 nTries ++;
6702 if( rc==SQLITE_BUSY ){
6703 /* If the lock failed (busy):
6704 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6705 * 2nd try: fail if the mod time changed or host id is different, wait
6706 * 10 sec and try again
6707 * 3rd try: break the lock unless the mod time has changed.
6708 */
6709 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006710 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006711 pFile->lastErrno = errno;
6712 return SQLITE_IOERR_LOCK;
6713 }
6714
6715 if( nTries==1 ){
6716 conchModTime = buf.st_mtimespec;
6717 usleep(500000); /* wait 0.5 sec and try the lock again*/
6718 continue;
6719 }
6720
6721 assert( nTries>1 );
6722 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6723 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6724 return SQLITE_BUSY;
6725 }
6726
6727 if( nTries==2 ){
6728 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006729 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006730 if( len<0 ){
6731 pFile->lastErrno = errno;
6732 return SQLITE_IOERR_LOCK;
6733 }
6734 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6735 /* don't break the lock if the host id doesn't match */
6736 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6737 return SQLITE_BUSY;
6738 }
6739 }else{
6740 /* don't break the lock on short read or a version mismatch */
6741 return SQLITE_BUSY;
6742 }
6743 usleep(10000000); /* wait 10 sec and try the lock again */
6744 continue;
6745 }
6746
6747 assert( nTries==3 );
6748 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6749 rc = SQLITE_OK;
6750 if( lockType==EXCLUSIVE_LOCK ){
6751 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6752 }
6753 if( !rc ){
6754 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6755 }
6756 }
6757 }
6758 } while( rc==SQLITE_BUSY && nTries<3 );
6759
6760 return rc;
6761}
6762
6763/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006764** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6765** lockPath means that the lockPath in the conch file will be used if the
6766** host IDs match, or a new lock path will be generated automatically
6767** and written to the conch file.
6768*/
6769static int proxyTakeConch(unixFile *pFile){
6770 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6771
drh7ed97b92010-01-20 13:07:21 +00006772 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006773 return SQLITE_OK;
6774 }else{
6775 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006776 uuid_t myHostID;
6777 int pError = 0;
6778 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006779 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006780 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006781 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006782 int createConch = 0;
6783 int hostIdMatch = 0;
6784 int readLen = 0;
6785 int tryOldLockPath = 0;
6786 int forceNewLockPath = 0;
6787
drh308c2a52010-05-14 11:30:18 +00006788 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6789 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006790
drh7ed97b92010-01-20 13:07:21 +00006791 rc = proxyGetHostID(myHostID, &pError);
6792 if( (rc&0xff)==SQLITE_IOERR ){
6793 pFile->lastErrno = pError;
6794 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006795 }
drh7ed97b92010-01-20 13:07:21 +00006796 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006797 if( rc!=SQLITE_OK ){
6798 goto end_takeconch;
6799 }
drh7ed97b92010-01-20 13:07:21 +00006800 /* read the existing conch file */
6801 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6802 if( readLen<0 ){
6803 /* I/O error: lastErrno set by seekAndRead */
6804 pFile->lastErrno = conchFile->lastErrno;
6805 rc = SQLITE_IOERR_READ;
6806 goto end_takeconch;
6807 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6808 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6809 /* a short read or version format mismatch means we need to create a new
6810 ** conch file.
6811 */
6812 createConch = 1;
6813 }
6814 /* if the host id matches and the lock path already exists in the conch
6815 ** we'll try to use the path there, if we can't open that path, we'll
6816 ** retry with a new auto-generated path
6817 */
6818 do { /* in case we need to try again for an :auto: named lock file */
6819
6820 if( !createConch && !forceNewLockPath ){
6821 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6822 PROXY_HOSTIDLEN);
6823 /* if the conch has data compare the contents */
6824 if( !pCtx->lockProxyPath ){
6825 /* for auto-named local lock file, just check the host ID and we'll
6826 ** use the local lock file path that's already in there
6827 */
6828 if( hostIdMatch ){
6829 size_t pathLen = (readLen - PROXY_PATHINDEX);
6830
6831 if( pathLen>=MAXPATHLEN ){
6832 pathLen=MAXPATHLEN-1;
6833 }
6834 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6835 lockPath[pathLen] = 0;
6836 tempLockPath = lockPath;
6837 tryOldLockPath = 1;
6838 /* create a copy of the lock path if the conch is taken */
6839 goto end_takeconch;
6840 }
6841 }else if( hostIdMatch
6842 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6843 readLen-PROXY_PATHINDEX)
6844 ){
6845 /* conch host and lock path match */
6846 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006847 }
drh7ed97b92010-01-20 13:07:21 +00006848 }
6849
6850 /* if the conch isn't writable and doesn't match, we can't take it */
6851 if( (conchFile->openFlags&O_RDWR) == 0 ){
6852 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006853 goto end_takeconch;
6854 }
drh7ed97b92010-01-20 13:07:21 +00006855
6856 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006857 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006858 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6859 tempLockPath = lockPath;
6860 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006861 }
drh7ed97b92010-01-20 13:07:21 +00006862
6863 /* update conch with host and path (this will fail if other process
6864 ** has a shared lock already), if the host id matches, use the big
6865 ** stick.
drh715ff302008-12-03 22:32:44 +00006866 */
drh7ed97b92010-01-20 13:07:21 +00006867 futimes(conchFile->h, NULL);
6868 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006869 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006870 /* We are trying for an exclusive lock but another thread in this
6871 ** same process is still holding a shared lock. */
6872 rc = SQLITE_BUSY;
6873 } else {
6874 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006875 }
drh715ff302008-12-03 22:32:44 +00006876 }else{
drh7ed97b92010-01-20 13:07:21 +00006877 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006878 }
drh7ed97b92010-01-20 13:07:21 +00006879 if( rc==SQLITE_OK ){
6880 char writeBuffer[PROXY_MAXCONCHLEN];
6881 int writeSize = 0;
6882
6883 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6884 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6885 if( pCtx->lockProxyPath!=NULL ){
6886 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6887 }else{
6888 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6889 }
6890 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006891 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006892 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6893 fsync(conchFile->h);
6894 /* If we created a new conch file (not just updated the contents of a
6895 ** valid conch file), try to match the permissions of the database
6896 */
6897 if( rc==SQLITE_OK && createConch ){
6898 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006899 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006900 if( err==0 ){
6901 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6902 S_IROTH|S_IWOTH);
6903 /* try to match the database file R/W permissions, ignore failure */
6904#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006905 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006906#else
drhff812312011-02-23 13:33:46 +00006907 do{
drhe562be52011-03-02 18:01:10 +00006908 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006909 }while( rc==(-1) && errno==EINTR );
6910 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006911 int code = errno;
6912 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6913 cmode, code, strerror(code));
6914 } else {
6915 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6916 }
6917 }else{
6918 int code = errno;
6919 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6920 err, code, strerror(code));
6921#endif
6922 }
drh715ff302008-12-03 22:32:44 +00006923 }
6924 }
drh7ed97b92010-01-20 13:07:21 +00006925 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6926
6927 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006928 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006929 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006930 int fd;
drh7ed97b92010-01-20 13:07:21 +00006931 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006932 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006933 }
6934 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006935 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006936 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006937 if( fd>=0 ){
6938 pFile->h = fd;
6939 }else{
drh9978c972010-02-23 17:36:32 +00006940 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006941 during locking */
6942 }
6943 }
6944 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6945 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6946 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6947 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6948 /* we couldn't create the proxy lock file with the old lock file path
6949 ** so try again via auto-naming
6950 */
6951 forceNewLockPath = 1;
6952 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006953 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006954 }
6955 }
6956 if( rc==SQLITE_OK ){
6957 /* Need to make a copy of path if we extracted the value
6958 ** from the conch file or the path was allocated on the stack
6959 */
6960 if( tempLockPath ){
6961 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6962 if( !pCtx->lockProxyPath ){
6963 rc = SQLITE_NOMEM;
6964 }
6965 }
6966 }
6967 if( rc==SQLITE_OK ){
6968 pCtx->conchHeld = 1;
6969
6970 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6971 afpLockingContext *afpCtx;
6972 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6973 afpCtx->dbPath = pCtx->lockProxyPath;
6974 }
6975 } else {
6976 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6977 }
drh308c2a52010-05-14 11:30:18 +00006978 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6979 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006980 return rc;
drh308c2a52010-05-14 11:30:18 +00006981 } while (1); /* in case we need to retry the :auto: lock file -
6982 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006983 }
6984}
6985
6986/*
6987** If pFile holds a lock on a conch file, then release that lock.
6988*/
6989static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006990 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006991 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6992 unixFile *conchFile; /* Name of the conch file */
6993
6994 pCtx = (proxyLockingContext *)pFile->lockingContext;
6995 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006996 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006997 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006998 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006999 if( pCtx->conchHeld>0 ){
7000 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7001 }
drh715ff302008-12-03 22:32:44 +00007002 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007003 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7004 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007005 return rc;
7006}
7007
7008/*
7009** Given the name of a database file, compute the name of its conch file.
7010** Store the conch filename in memory obtained from sqlite3_malloc().
7011** Make *pConchPath point to the new name. Return SQLITE_OK on success
7012** or SQLITE_NOMEM if unable to obtain memory.
7013**
7014** The caller is responsible for ensuring that the allocated memory
7015** space is eventually freed.
7016**
7017** *pConchPath is set to NULL if a memory allocation error occurs.
7018*/
7019static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7020 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007021 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007022 char *conchPath; /* buffer in which to construct conch name */
7023
7024 /* Allocate space for the conch filename and initialize the name to
7025 ** the name of the original database file. */
7026 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
7027 if( conchPath==0 ){
7028 return SQLITE_NOMEM;
7029 }
7030 memcpy(conchPath, dbPath, len+1);
7031
7032 /* now insert a "." before the last / character */
7033 for( i=(len-1); i>=0; i-- ){
7034 if( conchPath[i]=='/' ){
7035 i++;
7036 break;
7037 }
7038 }
7039 conchPath[i]='.';
7040 while ( i<len ){
7041 conchPath[i+1]=dbPath[i];
7042 i++;
7043 }
7044
7045 /* append the "-conch" suffix to the file */
7046 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007047 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007048
7049 return SQLITE_OK;
7050}
7051
7052
7053/* Takes a fully configured proxy locking-style unix file and switches
7054** the local lock file path
7055*/
7056static int switchLockProxyPath(unixFile *pFile, const char *path) {
7057 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7058 char *oldPath = pCtx->lockProxyPath;
7059 int rc = SQLITE_OK;
7060
drh308c2a52010-05-14 11:30:18 +00007061 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007062 return SQLITE_BUSY;
7063 }
7064
7065 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7066 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7067 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7068 return SQLITE_OK;
7069 }else{
7070 unixFile *lockProxy = pCtx->lockProxy;
7071 pCtx->lockProxy=NULL;
7072 pCtx->conchHeld = 0;
7073 if( lockProxy!=NULL ){
7074 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7075 if( rc ) return rc;
7076 sqlite3_free(lockProxy);
7077 }
7078 sqlite3_free(oldPath);
7079 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7080 }
7081
7082 return rc;
7083}
7084
7085/*
7086** pFile is a file that has been opened by a prior xOpen call. dbPath
7087** is a string buffer at least MAXPATHLEN+1 characters in size.
7088**
7089** This routine find the filename associated with pFile and writes it
7090** int dbPath.
7091*/
7092static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007093#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007094 if( pFile->pMethod == &afpIoMethods ){
7095 /* afp style keeps a reference to the db path in the filePath field
7096 ** of the struct */
drhea678832008-12-10 19:26:22 +00007097 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007098 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7099 } else
drh715ff302008-12-03 22:32:44 +00007100#endif
7101 if( pFile->pMethod == &dotlockIoMethods ){
7102 /* dot lock style uses the locking context to store the dot lock
7103 ** file path */
7104 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7105 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7106 }else{
7107 /* all other styles use the locking context to store the db file path */
7108 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007109 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007110 }
7111 return SQLITE_OK;
7112}
7113
7114/*
7115** Takes an already filled in unix file and alters it so all file locking
7116** will be performed on the local proxy lock file. The following fields
7117** are preserved in the locking context so that they can be restored and
7118** the unix structure properly cleaned up at close time:
7119** ->lockingContext
7120** ->pMethod
7121*/
7122static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7123 proxyLockingContext *pCtx;
7124 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7125 char *lockPath=NULL;
7126 int rc = SQLITE_OK;
7127
drh308c2a52010-05-14 11:30:18 +00007128 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007129 return SQLITE_BUSY;
7130 }
7131 proxyGetDbPathForUnixFile(pFile, dbPath);
7132 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7133 lockPath=NULL;
7134 }else{
7135 lockPath=(char *)path;
7136 }
7137
drh308c2a52010-05-14 11:30:18 +00007138 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7139 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007140
7141 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7142 if( pCtx==0 ){
7143 return SQLITE_NOMEM;
7144 }
7145 memset(pCtx, 0, sizeof(*pCtx));
7146
7147 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7148 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007149 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7150 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7151 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7152 ** (c) the file system is read-only, then enable no-locking access.
7153 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7154 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7155 */
7156 struct statfs fsInfo;
7157 struct stat conchInfo;
7158 int goLockless = 0;
7159
drh99ab3b12011-03-02 15:09:07 +00007160 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007161 int err = errno;
7162 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7163 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7164 }
7165 }
7166 if( goLockless ){
7167 pCtx->conchHeld = -1; /* read only FS/ lockless */
7168 rc = SQLITE_OK;
7169 }
7170 }
drh715ff302008-12-03 22:32:44 +00007171 }
7172 if( rc==SQLITE_OK && lockPath ){
7173 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7174 }
7175
7176 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007177 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7178 if( pCtx->dbPath==NULL ){
7179 rc = SQLITE_NOMEM;
7180 }
7181 }
7182 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007183 /* all memory is allocated, proxys are created and assigned,
7184 ** switch the locking context and pMethod then return.
7185 */
drh715ff302008-12-03 22:32:44 +00007186 pCtx->oldLockingContext = pFile->lockingContext;
7187 pFile->lockingContext = pCtx;
7188 pCtx->pOldMethod = pFile->pMethod;
7189 pFile->pMethod = &proxyIoMethods;
7190 }else{
7191 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007192 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007193 sqlite3_free(pCtx->conchFile);
7194 }
drhd56b1212010-08-11 06:14:15 +00007195 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007196 sqlite3_free(pCtx->conchFilePath);
7197 sqlite3_free(pCtx);
7198 }
drh308c2a52010-05-14 11:30:18 +00007199 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7200 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007201 return rc;
7202}
7203
7204
7205/*
7206** This routine handles sqlite3_file_control() calls that are specific
7207** to proxy locking.
7208*/
7209static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7210 switch( op ){
7211 case SQLITE_GET_LOCKPROXYFILE: {
7212 unixFile *pFile = (unixFile*)id;
7213 if( pFile->pMethod == &proxyIoMethods ){
7214 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7215 proxyTakeConch(pFile);
7216 if( pCtx->lockProxyPath ){
7217 *(const char **)pArg = pCtx->lockProxyPath;
7218 }else{
7219 *(const char **)pArg = ":auto: (not held)";
7220 }
7221 } else {
7222 *(const char **)pArg = NULL;
7223 }
7224 return SQLITE_OK;
7225 }
7226 case SQLITE_SET_LOCKPROXYFILE: {
7227 unixFile *pFile = (unixFile*)id;
7228 int rc = SQLITE_OK;
7229 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7230 if( pArg==NULL || (const char *)pArg==0 ){
7231 if( isProxyStyle ){
7232 /* turn off proxy locking - not supported */
7233 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7234 }else{
7235 /* turn off proxy locking - already off - NOOP */
7236 rc = SQLITE_OK;
7237 }
7238 }else{
7239 const char *proxyPath = (const char *)pArg;
7240 if( isProxyStyle ){
7241 proxyLockingContext *pCtx =
7242 (proxyLockingContext*)pFile->lockingContext;
7243 if( !strcmp(pArg, ":auto:")
7244 || (pCtx->lockProxyPath &&
7245 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7246 ){
7247 rc = SQLITE_OK;
7248 }else{
7249 rc = switchLockProxyPath(pFile, proxyPath);
7250 }
7251 }else{
7252 /* turn on proxy file locking */
7253 rc = proxyTransformUnixFile(pFile, proxyPath);
7254 }
7255 }
7256 return rc;
7257 }
7258 default: {
7259 assert( 0 ); /* The call assures that only valid opcodes are sent */
7260 }
7261 }
7262 /*NOTREACHED*/
7263 return SQLITE_ERROR;
7264}
7265
7266/*
7267** Within this division (the proxying locking implementation) the procedures
7268** above this point are all utilities. The lock-related methods of the
7269** proxy-locking sqlite3_io_method object follow.
7270*/
7271
7272
7273/*
7274** This routine checks if there is a RESERVED lock held on the specified
7275** file by this or any other process. If such a lock is held, set *pResOut
7276** to a non-zero value otherwise *pResOut is set to zero. The return value
7277** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7278*/
7279static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7280 unixFile *pFile = (unixFile*)id;
7281 int rc = proxyTakeConch(pFile);
7282 if( rc==SQLITE_OK ){
7283 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007284 if( pCtx->conchHeld>0 ){
7285 unixFile *proxy = pCtx->lockProxy;
7286 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7287 }else{ /* conchHeld < 0 is lockless */
7288 pResOut=0;
7289 }
drh715ff302008-12-03 22:32:44 +00007290 }
7291 return rc;
7292}
7293
7294/*
drh308c2a52010-05-14 11:30:18 +00007295** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007296** of the following:
7297**
7298** (1) SHARED_LOCK
7299** (2) RESERVED_LOCK
7300** (3) PENDING_LOCK
7301** (4) EXCLUSIVE_LOCK
7302**
7303** Sometimes when requesting one lock state, additional lock states
7304** are inserted in between. The locking might fail on one of the later
7305** transitions leaving the lock state different from what it started but
7306** still short of its goal. The following chart shows the allowed
7307** transitions and the inserted intermediate states:
7308**
7309** UNLOCKED -> SHARED
7310** SHARED -> RESERVED
7311** SHARED -> (PENDING) -> EXCLUSIVE
7312** RESERVED -> (PENDING) -> EXCLUSIVE
7313** PENDING -> EXCLUSIVE
7314**
7315** This routine will only increase a lock. Use the sqlite3OsUnlock()
7316** routine to lower a locking level.
7317*/
drh308c2a52010-05-14 11:30:18 +00007318static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007319 unixFile *pFile = (unixFile*)id;
7320 int rc = proxyTakeConch(pFile);
7321 if( rc==SQLITE_OK ){
7322 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007323 if( pCtx->conchHeld>0 ){
7324 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007325 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7326 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007327 }else{
7328 /* conchHeld < 0 is lockless */
7329 }
drh715ff302008-12-03 22:32:44 +00007330 }
7331 return rc;
7332}
7333
7334
7335/*
drh308c2a52010-05-14 11:30:18 +00007336** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007337** must be either NO_LOCK or SHARED_LOCK.
7338**
7339** If the locking level of the file descriptor is already at or below
7340** the requested locking level, this routine is a no-op.
7341*/
drh308c2a52010-05-14 11:30:18 +00007342static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007343 unixFile *pFile = (unixFile*)id;
7344 int rc = proxyTakeConch(pFile);
7345 if( rc==SQLITE_OK ){
7346 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007347 if( pCtx->conchHeld>0 ){
7348 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007349 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7350 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007351 }else{
7352 /* conchHeld < 0 is lockless */
7353 }
drh715ff302008-12-03 22:32:44 +00007354 }
7355 return rc;
7356}
7357
7358/*
7359** Close a file that uses proxy locks.
7360*/
7361static int proxyClose(sqlite3_file *id) {
7362 if( id ){
7363 unixFile *pFile = (unixFile*)id;
7364 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7365 unixFile *lockProxy = pCtx->lockProxy;
7366 unixFile *conchFile = pCtx->conchFile;
7367 int rc = SQLITE_OK;
7368
7369 if( lockProxy ){
7370 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7371 if( rc ) return rc;
7372 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7373 if( rc ) return rc;
7374 sqlite3_free(lockProxy);
7375 pCtx->lockProxy = 0;
7376 }
7377 if( conchFile ){
7378 if( pCtx->conchHeld ){
7379 rc = proxyReleaseConch(pFile);
7380 if( rc ) return rc;
7381 }
7382 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7383 if( rc ) return rc;
7384 sqlite3_free(conchFile);
7385 }
drhd56b1212010-08-11 06:14:15 +00007386 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007387 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007388 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007389 /* restore the original locking context and pMethod then close it */
7390 pFile->lockingContext = pCtx->oldLockingContext;
7391 pFile->pMethod = pCtx->pOldMethod;
7392 sqlite3_free(pCtx);
7393 return pFile->pMethod->xClose(id);
7394 }
7395 return SQLITE_OK;
7396}
7397
7398
7399
drhd2cb50b2009-01-09 21:41:17 +00007400#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007401/*
7402** The proxy locking style is intended for use with AFP filesystems.
7403** And since AFP is only supported on MacOSX, the proxy locking is also
7404** restricted to MacOSX.
7405**
7406**
7407******************* End of the proxy lock implementation **********************
7408******************************************************************************/
7409
drh734c9862008-11-28 15:37:20 +00007410/*
danielk1977e339d652008-06-28 11:23:00 +00007411** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007412**
7413** This routine registers all VFS implementations for unix-like operating
7414** systems. This routine, and the sqlite3_os_end() routine that follows,
7415** should be the only routines in this file that are visible from other
7416** files.
drh6b9d6dd2008-12-03 19:34:47 +00007417**
7418** This routine is called once during SQLite initialization and by a
7419** single thread. The memory allocation and mutex subsystems have not
7420** necessarily been initialized when this routine is called, and so they
7421** should not be used.
drh153c62c2007-08-24 03:51:33 +00007422*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007423int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007424 /*
7425 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007426 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7427 ** to the "finder" function. (pAppData is a pointer to a pointer because
7428 ** silly C90 rules prohibit a void* from being cast to a function pointer
7429 ** and so we have to go through the intermediate pointer to avoid problems
7430 ** when compiling with -pedantic-errors on GCC.)
7431 **
7432 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007433 ** finder-function. The finder-function returns a pointer to the
7434 ** sqlite_io_methods object that implements the desired locking
7435 ** behaviors. See the division above that contains the IOMETHODS
7436 ** macro for addition information on finder-functions.
7437 **
7438 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7439 ** object. But the "autolockIoFinder" available on MacOSX does a little
7440 ** more than that; it looks at the filesystem type that hosts the
7441 ** database file and tries to choose an locking method appropriate for
7442 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007443 */
drh7708e972008-11-29 00:56:52 +00007444 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007445 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007446 sizeof(unixFile), /* szOsFile */ \
7447 MAX_PATHNAME, /* mxPathname */ \
7448 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007449 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007450 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007451 unixOpen, /* xOpen */ \
7452 unixDelete, /* xDelete */ \
7453 unixAccess, /* xAccess */ \
7454 unixFullPathname, /* xFullPathname */ \
7455 unixDlOpen, /* xDlOpen */ \
7456 unixDlError, /* xDlError */ \
7457 unixDlSym, /* xDlSym */ \
7458 unixDlClose, /* xDlClose */ \
7459 unixRandomness, /* xRandomness */ \
7460 unixSleep, /* xSleep */ \
7461 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007462 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007463 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007464 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007465 unixGetSystemCall, /* xGetSystemCall */ \
7466 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007467 }
7468
drh6b9d6dd2008-12-03 19:34:47 +00007469 /*
7470 ** All default VFSes for unix are contained in the following array.
7471 **
7472 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7473 ** by the SQLite core when the VFS is registered. So the following
7474 ** array cannot be const.
7475 */
danielk1977e339d652008-06-28 11:23:00 +00007476 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007477#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007478 UNIXVFS("unix", autolockIoFinder ),
7479#else
7480 UNIXVFS("unix", posixIoFinder ),
7481#endif
7482 UNIXVFS("unix-none", nolockIoFinder ),
7483 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007484 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007485#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007486 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007487#endif
7488#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007489 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007490#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007491 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007492#endif
chw78a13182009-04-07 05:35:03 +00007493#endif
drhd2cb50b2009-01-09 21:41:17 +00007494#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007495 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007496 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007497 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007498#endif
drh153c62c2007-08-24 03:51:33 +00007499 };
drh6b9d6dd2008-12-03 19:34:47 +00007500 unsigned int i; /* Loop counter */
7501
drh2aa5a002011-04-13 13:42:25 +00007502 /* Double-check that the aSyscall[] array has been constructed
7503 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007504 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007505
drh6b9d6dd2008-12-03 19:34:47 +00007506 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007507 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007508 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007509 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007510 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007511}
danielk1977e339d652008-06-28 11:23:00 +00007512
7513/*
drh6b9d6dd2008-12-03 19:34:47 +00007514** Shutdown the operating system interface.
7515**
7516** Some operating systems might need to do some cleanup in this routine,
7517** to release dynamically allocated objects. But not on unix.
7518** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007519*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007520int sqlite3_os_end(void){
7521 return SQLITE_OK;
7522}
drhdce8bdb2007-08-16 13:01:44 +00007523
danielk197729bafea2008-06-26 10:41:19 +00007524#endif /* SQLITE_OS_UNIX */