blob: fc320a4926f26c8565c51e4acd5c8b4d7239cb74 [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
drhf2424c52010-04-26 00:04:55 +000097#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +000098#endif
drh1da88f02011-12-17 16:09:16 +000099
danielk1977e339d652008-06-28 11:23:00 +0000100
drh40bbb0a2008-09-23 10:23:26 +0000101#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000102# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000103# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000104# include <semaphore.h>
105# include <limits.h>
106# else
drh9b35ea62008-11-29 02:20:26 +0000107# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000108# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000109# endif
drhbfe66312006-10-03 17:40:40 +0000110#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000111
drhf8b4d8c2010-03-05 13:53:22 +0000112#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000113# include <sys/mount.h>
114#endif
115
drhdbe4b882011-06-20 18:00:17 +0000116#ifdef HAVE_UTIME
117# include <utime.h>
118#endif
119
drh9cbe6352005-11-29 03:13:21 +0000120/*
drh7ed97b92010-01-20 13:07:21 +0000121** Allowed values of unixFile.fsFlags
122*/
123#define SQLITE_FSFLAGS_IS_MSDOS 0x1
124
125/*
drhf1a221e2006-01-15 17:27:17 +0000126** If we are to be thread-safe, include the pthreads header and define
127** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000128*/
drhd677b3d2007-08-20 22:48:41 +0000129#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000130# include <pthread.h>
131# define SQLITE_UNIX_THREADS 1
132#endif
133
134/*
135** Default permissions when creating a new file
136*/
137#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
138# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
139#endif
140
danielk1977b4b47412007-08-17 15:53:36 +0000141/*
drh5adc60b2012-04-14 13:25:11 +0000142** Default permissions when creating auto proxy dir
143*/
aswiftaebf4132008-11-21 00:10:35 +0000144#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
145# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
146#endif
147
148/*
danielk1977b4b47412007-08-17 15:53:36 +0000149** Maximum supported path-length.
150*/
151#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000152
drh734c9862008-11-28 15:37:20 +0000153/*
drh734c9862008-11-28 15:37:20 +0000154** Only set the lastErrno if the error code is a real error and not
155** a normal expected return code of SQLITE_BUSY or SQLITE_OK
156*/
157#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
158
drhd91c68f2010-05-14 14:52:25 +0000159/* Forward references */
160typedef struct unixShm unixShm; /* Connection shared memory */
161typedef struct unixShmNode unixShmNode; /* Shared memory instance */
162typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
163typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000164
165/*
dane946c392009-08-22 11:39:46 +0000166** Sometimes, after a file handle is closed by SQLite, the file descriptor
167** cannot be closed immediately. In these cases, instances of the following
168** structure are used to store the file descriptor while waiting for an
169** opportunity to either close or reuse it.
170*/
dane946c392009-08-22 11:39:46 +0000171struct UnixUnusedFd {
172 int fd; /* File descriptor to close */
173 int flags; /* Flags this file descriptor was opened with */
174 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
175};
176
177/*
drh9b35ea62008-11-29 02:20:26 +0000178** The unixFile structure is subclass of sqlite3_file specific to the unix
179** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000180*/
drh054889e2005-11-30 03:20:31 +0000181typedef struct unixFile unixFile;
182struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000183 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000184 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000185 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000186 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000187 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000188 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000189 int lastErrno; /* The unix errno from last I/O error */
190 void *lockingContext; /* Locking style specific state */
191 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000192 const char *zPath; /* Name of the file */
193 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000194 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000195#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000196 int nFetchOut; /* Number of outstanding xFetch refs */
197 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000198 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
199 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000200 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000201#endif
drh537dddf2012-10-26 13:46:24 +0000202#ifdef __QNXNTO__
203 int sectorSize; /* Device sector size */
204 int deviceCharacteristics; /* Precomputed device characteristics */
205#endif
drh08c6d442009-02-09 17:34:07 +0000206#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000207 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000208#endif
drh7ed97b92010-01-20 13:07:21 +0000209#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000210 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000211#endif
212#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000213 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000214#endif
drhd3d8c042012-05-29 17:02:40 +0000215#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000216 /* The next group of variables are used to track whether or not the
217 ** transaction counter in bytes 24-27 of database files are updated
218 ** whenever any part of the database changes. An assertion fault will
219 ** occur if a file is updated without also updating the transaction
220 ** counter. This test is made to avoid new problems similar to the
221 ** one described by ticket #3584.
222 */
223 unsigned char transCntrChng; /* True if the transaction counter changed */
224 unsigned char dbUpdate; /* True if any part of database file changed */
225 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000226
drh8f941bc2009-01-14 23:03:40 +0000227#endif
danf23da962013-03-23 21:00:41 +0000228
danielk1977967a4a12007-08-20 14:23:44 +0000229#ifdef SQLITE_TEST
230 /* In test mode, increase the size of this structure a bit so that
231 ** it is larger than the struct CrashFile defined in test6.c.
232 */
233 char aPadding[32];
234#endif
drh9cbe6352005-11-29 03:13:21 +0000235};
236
drhb00d8622014-01-01 15:18:36 +0000237/* This variable holds the process id (pid) from when the xRandomness()
238** method was called. If xOpen() is called from a different process id,
239** indicating that a fork() has occurred, the PRNG will be reset.
240*/
241static int randomnessPid = 0;
242
drh0ccebe72005-06-07 22:22:50 +0000243/*
drha7e61d82011-03-12 17:02:57 +0000244** Allowed values for the unixFile.ctrlFlags bitmask:
245*/
drhf0b190d2011-07-26 16:03:07 +0000246#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
247#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
248#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000249#ifndef SQLITE_DISABLE_DIRSYNC
250# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
251#else
252# define UNIXFILE_DIRSYNC 0x00
253#endif
drhcb15f352011-12-23 01:04:17 +0000254#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000255#define UNIXFILE_DELETE 0x20 /* Delete on close */
256#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
257#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhfbc7e882013-04-11 01:16:15 +0000258#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
drha7e61d82011-03-12 17:02:57 +0000259
260/*
drh198bf392006-01-06 21:52:49 +0000261** Include code that is common to all os_*.c files
262*/
263#include "os_common.h"
264
265/*
drh0ccebe72005-06-07 22:22:50 +0000266** Define various macros that are missing from some systems.
267*/
drhbbd42a62004-05-22 17:41:58 +0000268#ifndef O_LARGEFILE
269# define O_LARGEFILE 0
270#endif
271#ifdef SQLITE_DISABLE_LFS
272# undef O_LARGEFILE
273# define O_LARGEFILE 0
274#endif
275#ifndef O_NOFOLLOW
276# define O_NOFOLLOW 0
277#endif
278#ifndef O_BINARY
279# define O_BINARY 0
280#endif
281
282/*
drh2b4b5962005-06-15 17:47:55 +0000283** The threadid macro resolves to the thread-id or to 0. Used for
284** testing and debugging only.
285*/
drhd677b3d2007-08-20 22:48:41 +0000286#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000287#define threadid pthread_self()
288#else
289#define threadid 0
290#endif
291
drh99ab3b12011-03-02 15:09:07 +0000292/*
dane6ecd662013-04-01 17:56:59 +0000293** HAVE_MREMAP defaults to true on Linux and false everywhere else.
294*/
295#if !defined(HAVE_MREMAP)
296# if defined(__linux__) && defined(_GNU_SOURCE)
297# define HAVE_MREMAP 1
298# else
299# define HAVE_MREMAP 0
300# endif
301#endif
302
303/*
drh9a3baf12011-04-25 18:01:27 +0000304** Different Unix systems declare open() in different ways. Same use
305** open(const char*,int,mode_t). Others use open(const char*,int,...).
306** The difference is important when using a pointer to the function.
307**
308** The safest way to deal with the problem is to always use this wrapper
309** which always has the same well-defined interface.
310*/
311static int posixOpen(const char *zFile, int flags, int mode){
312 return open(zFile, flags, mode);
313}
314
drhed466822012-05-31 13:10:49 +0000315/*
316** On some systems, calls to fchown() will trigger a message in a security
317** log if they come from non-root processes. So avoid calling fchown() if
318** we are not running as root.
319*/
320static int posixFchown(int fd, uid_t uid, gid_t gid){
321 return geteuid() ? 0 : fchown(fd,uid,gid);
322}
323
drh90315a22011-08-10 01:52:12 +0000324/* Forward reference */
325static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000326static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000327
drh9a3baf12011-04-25 18:01:27 +0000328/*
drh99ab3b12011-03-02 15:09:07 +0000329** Many system calls are accessed through pointer-to-functions so that
330** they may be overridden at runtime to facilitate fault injection during
331** testing and sandboxing. The following array holds the names and pointers
332** to all overrideable system calls.
333*/
334static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000335 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000336 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
337 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000338} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000339 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
340#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000341
drh58ad5802011-03-23 22:02:23 +0000342 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000343#define osClose ((int(*)(int))aSyscall[1].pCurrent)
344
drh58ad5802011-03-23 22:02:23 +0000345 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000346#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
347
drh58ad5802011-03-23 22:02:23 +0000348 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000349#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
350
drh58ad5802011-03-23 22:02:23 +0000351 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000352#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
353
354/*
355** The DJGPP compiler environment looks mostly like Unix, but it
356** lacks the fcntl() system call. So redefine fcntl() to be something
357** that always succeeds. This means that locking does not occur under
358** DJGPP. But it is DOS - what did you expect?
359*/
360#ifdef __DJGPP__
361 { "fstat", 0, 0 },
362#define osFstat(a,b,c) 0
363#else
drh58ad5802011-03-23 22:02:23 +0000364 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000365#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
366#endif
367
drh58ad5802011-03-23 22:02:23 +0000368 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000369#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
370
drh58ad5802011-03-23 22:02:23 +0000371 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000372#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000373
drh58ad5802011-03-23 22:02:23 +0000374 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000375#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
376
drhd4a80312011-04-15 14:33:20 +0000377#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000378 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000379#else
drh58ad5802011-03-23 22:02:23 +0000380 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000381#endif
382#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
383
384#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000385 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000386#else
drh58ad5802011-03-23 22:02:23 +0000387 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000388#endif
389#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
390
drh58ad5802011-03-23 22:02:23 +0000391 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000392#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
393
drhd4a80312011-04-15 14:33:20 +0000394#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000395 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000396#else
drh58ad5802011-03-23 22:02:23 +0000397 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000398#endif
399#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
400 aSyscall[12].pCurrent)
401
402#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000403 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000404#else
drh58ad5802011-03-23 22:02:23 +0000405 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000406#endif
407#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
408 aSyscall[13].pCurrent)
409
drh58ad5802011-03-23 22:02:23 +0000410 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000411#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000412
413#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000414 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000415#else
drh58ad5802011-03-23 22:02:23 +0000416 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000417#endif
dan0fd7d862011-03-29 10:04:23 +0000418#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000419
drh036ac7f2011-08-08 23:18:05 +0000420 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
421#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
422
drh90315a22011-08-10 01:52:12 +0000423 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
424#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
425
drh9ef6bc42011-11-04 02:24:02 +0000426 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
427#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
428
429 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
430#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
431
drhed466822012-05-31 13:10:49 +0000432 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000433#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000434
dan4dd51442013-08-26 14:30:25 +0000435#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000436 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
437#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
438
drhd1ab8062013-03-25 20:50:25 +0000439 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
440#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
441
dane6ecd662013-04-01 17:56:59 +0000442#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000443 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
444#else
445 { "mremap", (sqlite3_syscall_ptr)0, 0 },
446#endif
447#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
dan4dd51442013-08-26 14:30:25 +0000448#endif
drhd1ab8062013-03-25 20:50:25 +0000449
danbc760632014-03-20 09:42:09 +0000450 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
451#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
452
drhe562be52011-03-02 18:01:10 +0000453}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000454
455/*
456** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000457** "unix" VFSes. Return SQLITE_OK opon successfully updating the
458** system call pointer, or SQLITE_NOTFOUND if there is no configurable
459** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000460*/
461static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000462 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
463 const char *zName, /* Name of system call to override */
464 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000465){
drh58ad5802011-03-23 22:02:23 +0000466 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000467 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000468
469 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000470 if( zName==0 ){
471 /* If no zName is given, restore all system calls to their default
472 ** settings and return NULL
473 */
dan51438a72011-04-02 17:00:47 +0000474 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000475 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
476 if( aSyscall[i].pDefault ){
477 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000478 }
479 }
480 }else{
481 /* If zName is specified, operate on only the one system call
482 ** specified.
483 */
484 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
485 if( strcmp(zName, aSyscall[i].zName)==0 ){
486 if( aSyscall[i].pDefault==0 ){
487 aSyscall[i].pDefault = aSyscall[i].pCurrent;
488 }
drh1df30962011-03-02 19:06:42 +0000489 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000490 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
491 aSyscall[i].pCurrent = pNewFunc;
492 break;
493 }
494 }
495 }
496 return rc;
497}
498
drh1df30962011-03-02 19:06:42 +0000499/*
500** Return the value of a system call. Return NULL if zName is not a
501** recognized system call name. NULL is also returned if the system call
502** is currently undefined.
503*/
drh58ad5802011-03-23 22:02:23 +0000504static sqlite3_syscall_ptr unixGetSystemCall(
505 sqlite3_vfs *pNotUsed,
506 const char *zName
507){
508 unsigned int i;
509
510 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000511 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
512 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
513 }
514 return 0;
515}
516
517/*
518** Return the name of the first system call after zName. If zName==NULL
519** then return the name of the first system call. Return NULL if zName
520** is the last system call or if zName is not the name of a valid
521** system call.
522*/
523static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000524 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000525
526 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000527 if( zName ){
528 for(i=0; i<ArraySize(aSyscall)-1; i++){
529 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000530 }
531 }
dan0fd7d862011-03-29 10:04:23 +0000532 for(i++; i<ArraySize(aSyscall); i++){
533 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000534 }
535 return 0;
536}
537
drhad4f1e52011-03-04 15:43:57 +0000538/*
drh77a3fdc2013-08-30 14:24:12 +0000539** Do not accept any file descriptor less than this value, in order to avoid
540** opening database file using file descriptors that are commonly used for
541** standard input, output, and error.
542*/
543#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
544# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
545#endif
546
547/*
drh8c815d12012-02-13 20:16:37 +0000548** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000549** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000550**
551** If the file creation mode "m" is 0 then set it to the default for
552** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
553** 0644) as modified by the system umask. If m is not 0, then
554** make the file creation mode be exactly m ignoring the umask.
555**
556** The m parameter will be non-zero only when creating -wal, -journal,
557** and -shm files. We want those files to have *exactly* the same
558** permissions as their original database, unadulterated by the umask.
559** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
560** transaction crashes and leaves behind hot journals, then any
561** process that is able to write to the database will also be able to
562** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000563*/
drh8c815d12012-02-13 20:16:37 +0000564static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000565 int fd;
drhe1186ab2013-01-04 20:45:13 +0000566 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000567 while(1){
drh5adc60b2012-04-14 13:25:11 +0000568#if defined(O_CLOEXEC)
569 fd = osOpen(z,f|O_CLOEXEC,m2);
570#else
571 fd = osOpen(z,f,m2);
572#endif
drh5128d002013-08-30 06:20:23 +0000573 if( fd<0 ){
574 if( errno==EINTR ) continue;
575 break;
576 }
drh77a3fdc2013-08-30 14:24:12 +0000577 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000578 osClose(fd);
579 sqlite3_log(SQLITE_WARNING,
580 "attempt to open \"%s\" as file descriptor %d", z, fd);
581 fd = -1;
582 if( osOpen("/dev/null", f, m)<0 ) break;
583 }
drhe1186ab2013-01-04 20:45:13 +0000584 if( fd>=0 ){
585 if( m!=0 ){
586 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000587 if( osFstat(fd, &statbuf)==0
588 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000589 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000590 ){
drhe1186ab2013-01-04 20:45:13 +0000591 osFchmod(fd, m);
592 }
593 }
drh5adc60b2012-04-14 13:25:11 +0000594#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000595 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000596#endif
drhe1186ab2013-01-04 20:45:13 +0000597 }
drh5adc60b2012-04-14 13:25:11 +0000598 return fd;
drhad4f1e52011-03-04 15:43:57 +0000599}
danielk197713adf8a2004-06-03 16:08:41 +0000600
drh107886a2008-11-21 22:21:50 +0000601/*
dan9359c7b2009-08-21 08:29:10 +0000602** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000603** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000604** vxworksFileId objects used by this file, all of which may be
605** shared by multiple threads.
606**
607** Function unixMutexHeld() is used to assert() that the global mutex
608** is held when required. This function is only used as part of assert()
609** statements. e.g.
610**
611** unixEnterMutex()
612** assert( unixMutexHeld() );
613** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000614*/
615static void unixEnterMutex(void){
616 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
617}
618static void unixLeaveMutex(void){
619 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
620}
dan9359c7b2009-08-21 08:29:10 +0000621#ifdef SQLITE_DEBUG
622static int unixMutexHeld(void) {
623 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
624}
625#endif
drh107886a2008-11-21 22:21:50 +0000626
drh734c9862008-11-28 15:37:20 +0000627
drh30ddce62011-10-15 00:16:30 +0000628#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000629/*
630** Helper function for printing out trace information from debugging
631** binaries. This returns the string represetation of the supplied
632** integer lock-type.
633*/
drh308c2a52010-05-14 11:30:18 +0000634static const char *azFileLock(int eFileLock){
635 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000636 case NO_LOCK: return "NONE";
637 case SHARED_LOCK: return "SHARED";
638 case RESERVED_LOCK: return "RESERVED";
639 case PENDING_LOCK: return "PENDING";
640 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000641 }
642 return "ERROR";
643}
644#endif
645
646#ifdef SQLITE_LOCK_TRACE
647/*
648** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000649**
drh734c9862008-11-28 15:37:20 +0000650** This routine is used for troubleshooting locks on multithreaded
651** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
652** command-line option on the compiler. This code is normally
653** turned off.
654*/
655static int lockTrace(int fd, int op, struct flock *p){
656 char *zOpName, *zType;
657 int s;
658 int savedErrno;
659 if( op==F_GETLK ){
660 zOpName = "GETLK";
661 }else if( op==F_SETLK ){
662 zOpName = "SETLK";
663 }else{
drh99ab3b12011-03-02 15:09:07 +0000664 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000665 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
666 return s;
667 }
668 if( p->l_type==F_RDLCK ){
669 zType = "RDLCK";
670 }else if( p->l_type==F_WRLCK ){
671 zType = "WRLCK";
672 }else if( p->l_type==F_UNLCK ){
673 zType = "UNLCK";
674 }else{
675 assert( 0 );
676 }
677 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000678 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000679 savedErrno = errno;
680 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
681 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
682 (int)p->l_pid, s);
683 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
684 struct flock l2;
685 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000686 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000687 if( l2.l_type==F_RDLCK ){
688 zType = "RDLCK";
689 }else if( l2.l_type==F_WRLCK ){
690 zType = "WRLCK";
691 }else if( l2.l_type==F_UNLCK ){
692 zType = "UNLCK";
693 }else{
694 assert( 0 );
695 }
696 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
697 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
698 }
699 errno = savedErrno;
700 return s;
701}
drh99ab3b12011-03-02 15:09:07 +0000702#undef osFcntl
703#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000704#endif /* SQLITE_LOCK_TRACE */
705
drhff812312011-02-23 13:33:46 +0000706/*
707** Retry ftruncate() calls that fail due to EINTR
708*/
drhff812312011-02-23 13:33:46 +0000709static int robust_ftruncate(int h, sqlite3_int64 sz){
710 int rc;
drh99ab3b12011-03-02 15:09:07 +0000711 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000712 return rc;
713}
drh734c9862008-11-28 15:37:20 +0000714
715/*
716** This routine translates a standard POSIX errno code into something
717** useful to the clients of the sqlite3 functions. Specifically, it is
718** intended to translate a variety of "try again" errors into SQLITE_BUSY
719** and a variety of "please close the file descriptor NOW" errors into
720** SQLITE_IOERR
721**
722** Errors during initialization of locks, or file system support for locks,
723** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
724*/
725static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
726 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000727#if 0
728 /* At one point this code was not commented out. In theory, this branch
729 ** should never be hit, as this function should only be called after
730 ** a locking-related function (i.e. fcntl()) has returned non-zero with
731 ** the value of errno as the first argument. Since a system call has failed,
732 ** errno should be non-zero.
733 **
734 ** Despite this, if errno really is zero, we still don't want to return
735 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
736 ** propagated back to the caller. Commenting this branch out means errno==0
737 ** will be handled by the "default:" case below.
738 */
drh734c9862008-11-28 15:37:20 +0000739 case 0:
740 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000741#endif
742
drh734c9862008-11-28 15:37:20 +0000743 case EAGAIN:
744 case ETIMEDOUT:
745 case EBUSY:
746 case EINTR:
747 case ENOLCK:
748 /* random NFS retry error, unless during file system support
749 * introspection, in which it actually means what it says */
750 return SQLITE_BUSY;
751
752 case EACCES:
753 /* EACCES is like EAGAIN during locking operations, but not any other time*/
754 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000755 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
756 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
757 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000758 return SQLITE_BUSY;
759 }
760 /* else fall through */
761 case EPERM:
762 return SQLITE_PERM;
763
danea83bc62011-04-01 11:56:32 +0000764 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
765 ** this module never makes such a call. And the code in SQLite itself
766 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
767 ** this case is also commented out. If the system does set errno to EDEADLK,
768 ** the default SQLITE_IOERR_XXX code will be returned. */
769#if 0
drh734c9862008-11-28 15:37:20 +0000770 case EDEADLK:
771 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000772#endif
drh734c9862008-11-28 15:37:20 +0000773
774#if EOPNOTSUPP!=ENOTSUP
775 case EOPNOTSUPP:
776 /* something went terribly awry, unless during file system support
777 * introspection, in which it actually means what it says */
778#endif
779#ifdef ENOTSUP
780 case ENOTSUP:
781 /* invalid fd, unless during file system support introspection, in which
782 * it actually means what it says */
783#endif
784 case EIO:
785 case EBADF:
786 case EINVAL:
787 case ENOTCONN:
788 case ENODEV:
789 case ENXIO:
790 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000791#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000792 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000793#endif
drh734c9862008-11-28 15:37:20 +0000794 case ENOSYS:
795 /* these should force the client to close the file and reconnect */
796
797 default:
798 return sqliteIOErr;
799 }
800}
801
802
drh734c9862008-11-28 15:37:20 +0000803/******************************************************************************
804****************** Begin Unique File ID Utility Used By VxWorks ***************
805**
806** On most versions of unix, we can get a unique ID for a file by concatenating
807** the device number and the inode number. But this does not work on VxWorks.
808** On VxWorks, a unique file id must be based on the canonical filename.
809**
810** A pointer to an instance of the following structure can be used as a
811** unique file ID in VxWorks. Each instance of this structure contains
812** a copy of the canonical filename. There is also a reference count.
813** The structure is reclaimed when the number of pointers to it drops to
814** zero.
815**
816** There are never very many files open at one time and lookups are not
817** a performance-critical path, so it is sufficient to put these
818** structures on a linked list.
819*/
820struct vxworksFileId {
821 struct vxworksFileId *pNext; /* Next in a list of them all */
822 int nRef; /* Number of references to this one */
823 int nName; /* Length of the zCanonicalName[] string */
824 char *zCanonicalName; /* Canonical filename */
825};
826
827#if OS_VXWORKS
828/*
drh9b35ea62008-11-29 02:20:26 +0000829** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000830** variable:
831*/
832static struct vxworksFileId *vxworksFileList = 0;
833
834/*
835** Simplify a filename into its canonical form
836** by making the following changes:
837**
838** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000839** * convert /./ into just /
840** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000841**
842** Changes are made in-place. Return the new name length.
843**
844** The original filename is in z[0..n-1]. Return the number of
845** characters in the simplified name.
846*/
847static int vxworksSimplifyName(char *z, int n){
848 int i, j;
849 while( n>1 && z[n-1]=='/' ){ n--; }
850 for(i=j=0; i<n; i++){
851 if( z[i]=='/' ){
852 if( z[i+1]=='/' ) continue;
853 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
854 i += 1;
855 continue;
856 }
857 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
858 while( j>0 && z[j-1]!='/' ){ j--; }
859 if( j>0 ){ j--; }
860 i += 2;
861 continue;
862 }
863 }
864 z[j++] = z[i];
865 }
866 z[j] = 0;
867 return j;
868}
869
870/*
871** Find a unique file ID for the given absolute pathname. Return
872** a pointer to the vxworksFileId object. This pointer is the unique
873** file ID.
874**
875** The nRef field of the vxworksFileId object is incremented before
876** the object is returned. A new vxworksFileId object is created
877** and added to the global list if necessary.
878**
879** If a memory allocation error occurs, return NULL.
880*/
881static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
882 struct vxworksFileId *pNew; /* search key and new file ID */
883 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
884 int n; /* Length of zAbsoluteName string */
885
886 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000887 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000888 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
889 if( pNew==0 ) return 0;
890 pNew->zCanonicalName = (char*)&pNew[1];
891 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
892 n = vxworksSimplifyName(pNew->zCanonicalName, n);
893
894 /* Search for an existing entry that matching the canonical name.
895 ** If found, increment the reference count and return a pointer to
896 ** the existing file ID.
897 */
898 unixEnterMutex();
899 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
900 if( pCandidate->nName==n
901 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
902 ){
903 sqlite3_free(pNew);
904 pCandidate->nRef++;
905 unixLeaveMutex();
906 return pCandidate;
907 }
908 }
909
910 /* No match was found. We will make a new file ID */
911 pNew->nRef = 1;
912 pNew->nName = n;
913 pNew->pNext = vxworksFileList;
914 vxworksFileList = pNew;
915 unixLeaveMutex();
916 return pNew;
917}
918
919/*
920** Decrement the reference count on a vxworksFileId object. Free
921** the object when the reference count reaches zero.
922*/
923static void vxworksReleaseFileId(struct vxworksFileId *pId){
924 unixEnterMutex();
925 assert( pId->nRef>0 );
926 pId->nRef--;
927 if( pId->nRef==0 ){
928 struct vxworksFileId **pp;
929 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
930 assert( *pp==pId );
931 *pp = pId->pNext;
932 sqlite3_free(pId);
933 }
934 unixLeaveMutex();
935}
936#endif /* OS_VXWORKS */
937/*************** End of Unique File ID Utility Used By VxWorks ****************
938******************************************************************************/
939
940
941/******************************************************************************
942*************************** Posix Advisory Locking ****************************
943**
drh9b35ea62008-11-29 02:20:26 +0000944** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000945** section 6.5.2.2 lines 483 through 490 specify that when a process
946** sets or clears a lock, that operation overrides any prior locks set
947** by the same process. It does not explicitly say so, but this implies
948** that it overrides locks set by the same process using a different
949** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000950**
951** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000952** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
953**
954** Suppose ./file1 and ./file2 are really the same file (because
955** one is a hard or symbolic link to the other) then if you set
956** an exclusive lock on fd1, then try to get an exclusive lock
957** on fd2, it works. I would have expected the second lock to
958** fail since there was already a lock on the file due to fd1.
959** But not so. Since both locks came from the same process, the
960** second overrides the first, even though they were on different
961** file descriptors opened on different file names.
962**
drh734c9862008-11-28 15:37:20 +0000963** This means that we cannot use POSIX locks to synchronize file access
964** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000965** to synchronize access for threads in separate processes, but not
966** threads within the same process.
967**
968** To work around the problem, SQLite has to manage file locks internally
969** on its own. Whenever a new database is opened, we have to find the
970** specific inode of the database file (the inode is determined by the
971** st_dev and st_ino fields of the stat structure that fstat() fills in)
972** and check for locks already existing on that inode. When locks are
973** created or removed, we have to look at our own internal record of the
974** locks to see if another thread has previously set a lock on that same
975** inode.
976**
drh9b35ea62008-11-29 02:20:26 +0000977** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
978** For VxWorks, we have to use the alternative unique ID system based on
979** canonical filename and implemented in the previous division.)
980**
danielk1977ad94b582007-08-20 06:44:22 +0000981** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000982** descriptor. It is now a structure that holds the integer file
983** descriptor and a pointer to a structure that describes the internal
984** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000985** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000986** point to the same locking structure. The locking structure keeps
987** a reference count (so we will know when to delete it) and a "cnt"
988** field that tells us its internal lock status. cnt==0 means the
989** file is unlocked. cnt==-1 means the file has an exclusive lock.
990** cnt>0 means there are cnt shared locks on the file.
991**
992** Any attempt to lock or unlock a file first checks the locking
993** structure. The fcntl() system call is only invoked to set a
994** POSIX lock if the internal lock structure transitions between
995** a locked and an unlocked state.
996**
drh734c9862008-11-28 15:37:20 +0000997** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000998**
999** If you close a file descriptor that points to a file that has locks,
1000** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001001** released. To work around this problem, each unixInodeInfo object
1002** maintains a count of the number of pending locks on tha inode.
1003** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001004** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001005** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001006** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001007** be closed and that list is walked (and cleared) when the last lock
1008** clears.
1009**
drh9b35ea62008-11-29 02:20:26 +00001010** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001011**
drh9b35ea62008-11-29 02:20:26 +00001012** Many older versions of linux use the LinuxThreads library which is
1013** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001014** A cannot be modified or overridden by a different thread B.
1015** Only thread A can modify the lock. Locking behavior is correct
1016** if the appliation uses the newer Native Posix Thread Library (NPTL)
1017** on linux - with NPTL a lock created by thread A can override locks
1018** in thread B. But there is no way to know at compile-time which
1019** threading library is being used. So there is no way to know at
1020** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001021** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001022** current process.
drh5fdae772004-06-29 03:29:00 +00001023**
drh8af6c222010-05-14 12:43:01 +00001024** SQLite used to support LinuxThreads. But support for LinuxThreads
1025** was dropped beginning with version 3.7.0. SQLite will still work with
1026** LinuxThreads provided that (1) there is no more than one connection
1027** per database file in the same process and (2) database connections
1028** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001029*/
1030
1031/*
1032** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001033** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001034*/
1035struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001036 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001037#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001038 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001039#else
drh107886a2008-11-21 22:21:50 +00001040 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001041#endif
1042};
1043
1044/*
drhbbd42a62004-05-22 17:41:58 +00001045** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001046** inode. Or, on LinuxThreads, there is one of these structures for
1047** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001048**
danielk1977ad94b582007-08-20 06:44:22 +00001049** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001050** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001051** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001052*/
drh8af6c222010-05-14 12:43:01 +00001053struct unixInodeInfo {
1054 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001055 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001056 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1057 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001058 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001059 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1060 int nLock; /* Number of outstanding file locks */
1061 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1062 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1063 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001064#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001065 unsigned long long sharedByte; /* for AFP simulated shared lock */
1066#endif
drh6c7d5c52008-11-21 20:32:33 +00001067#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001068 sem_t *pSem; /* Named POSIX semaphore */
1069 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001070#endif
drhbbd42a62004-05-22 17:41:58 +00001071};
1072
drhda0e7682008-07-30 15:27:54 +00001073/*
drh8af6c222010-05-14 12:43:01 +00001074** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001075*/
drhd91c68f2010-05-14 14:52:25 +00001076static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001077
drh5fdae772004-06-29 03:29:00 +00001078/*
dane18d4952011-02-21 11:46:24 +00001079**
1080** This function - unixLogError_x(), is only ever called via the macro
1081** unixLogError().
1082**
1083** It is invoked after an error occurs in an OS function and errno has been
1084** set. It logs a message using sqlite3_log() containing the current value of
1085** errno and, if possible, the human-readable equivalent from strerror() or
1086** strerror_r().
1087**
1088** The first argument passed to the macro should be the error code that
1089** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1090** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001091** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001092** if any.
1093*/
drh0e9365c2011-03-02 02:08:13 +00001094#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1095static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001096 int errcode, /* SQLite error code */
1097 const char *zFunc, /* Name of OS function that failed */
1098 const char *zPath, /* File path associated with error */
1099 int iLine /* Source line number where error occurred */
1100){
1101 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001102 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001103
1104 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1105 ** the strerror() function to obtain the human-readable error message
1106 ** equivalent to errno. Otherwise, use strerror_r().
1107 */
1108#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1109 char aErr[80];
1110 memset(aErr, 0, sizeof(aErr));
1111 zErr = aErr;
1112
1113 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001114 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001115 ** returns a pointer to a buffer containing the error message. That pointer
1116 ** may point to aErr[], or it may point to some static storage somewhere.
1117 ** Otherwise, assume that the system provides the POSIX version of
1118 ** strerror_r(), which always writes an error message into aErr[].
1119 **
1120 ** If the code incorrectly assumes that it is the POSIX version that is
1121 ** available, the error message will often be an empty string. Not a
1122 ** huge problem. Incorrectly concluding that the GNU version is available
1123 ** could lead to a segfault though.
1124 */
1125#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1126 zErr =
1127# endif
drh0e9365c2011-03-02 02:08:13 +00001128 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001129
1130#elif SQLITE_THREADSAFE
1131 /* This is a threadsafe build, but strerror_r() is not available. */
1132 zErr = "";
1133#else
1134 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001135 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001136#endif
1137
drh0e9365c2011-03-02 02:08:13 +00001138 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001139 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001140 "os_unix.c:%d: (%d) %s(%s) - %s",
1141 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001142 );
1143
1144 return errcode;
1145}
1146
drh0e9365c2011-03-02 02:08:13 +00001147/*
1148** Close a file descriptor.
1149**
1150** We assume that close() almost always works, since it is only in a
1151** very sick application or on a very sick platform that it might fail.
1152** If it does fail, simply leak the file descriptor, but do log the
1153** error.
1154**
1155** Note that it is not safe to retry close() after EINTR since the
1156** file descriptor might have already been reused by another thread.
1157** So we don't even try to recover from an EINTR. Just log the error
1158** and move on.
1159*/
1160static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001161 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001162 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1163 pFile ? pFile->zPath : 0, lineno);
1164 }
1165}
dane18d4952011-02-21 11:46:24 +00001166
1167/*
danb0ac3e32010-06-16 10:55:42 +00001168** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001169*/
drh0e9365c2011-03-02 02:08:13 +00001170static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001171 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001172 UnixUnusedFd *p;
1173 UnixUnusedFd *pNext;
1174 for(p=pInode->pUnused; p; p=pNext){
1175 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001176 robust_close(pFile, p->fd, __LINE__);
1177 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001178 }
drh0e9365c2011-03-02 02:08:13 +00001179 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001180}
1181
1182/*
drh8af6c222010-05-14 12:43:01 +00001183** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001184**
1185** The mutex entered using the unixEnterMutex() function must be held
1186** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001187*/
danb0ac3e32010-06-16 10:55:42 +00001188static void releaseInodeInfo(unixFile *pFile){
1189 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001190 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001191 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001192 pInode->nRef--;
1193 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001194 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001195 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001196 if( pInode->pPrev ){
1197 assert( pInode->pPrev->pNext==pInode );
1198 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001199 }else{
drh8af6c222010-05-14 12:43:01 +00001200 assert( inodeList==pInode );
1201 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001202 }
drh8af6c222010-05-14 12:43:01 +00001203 if( pInode->pNext ){
1204 assert( pInode->pNext->pPrev==pInode );
1205 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001206 }
drh8af6c222010-05-14 12:43:01 +00001207 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001208 }
drhbbd42a62004-05-22 17:41:58 +00001209 }
1210}
1211
1212/*
drh8af6c222010-05-14 12:43:01 +00001213** Given a file descriptor, locate the unixInodeInfo object that
1214** describes that file descriptor. Create a new one if necessary. The
1215** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001216**
dan9359c7b2009-08-21 08:29:10 +00001217** The mutex entered using the unixEnterMutex() function must be held
1218** when this function is called.
1219**
drh6c7d5c52008-11-21 20:32:33 +00001220** Return an appropriate error code.
1221*/
drh8af6c222010-05-14 12:43:01 +00001222static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001223 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001224 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001225){
1226 int rc; /* System call return code */
1227 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001228 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1229 struct stat statbuf; /* Low-level file information */
1230 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001231
dan9359c7b2009-08-21 08:29:10 +00001232 assert( unixMutexHeld() );
1233
drh6c7d5c52008-11-21 20:32:33 +00001234 /* Get low-level information about the file that we can used to
1235 ** create a unique name for the file.
1236 */
1237 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001238 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001239 if( rc!=0 ){
1240 pFile->lastErrno = errno;
1241#ifdef EOVERFLOW
1242 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1243#endif
1244 return SQLITE_IOERR;
1245 }
1246
drheb0d74f2009-02-03 15:27:02 +00001247#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001248 /* On OS X on an msdos filesystem, the inode number is reported
1249 ** incorrectly for zero-size files. See ticket #3260. To work
1250 ** around this problem (we consider it a bug in OS X, not SQLite)
1251 ** we always increase the file size to 1 by writing a single byte
1252 ** prior to accessing the inode number. The one byte written is
1253 ** an ASCII 'S' character which also happens to be the first byte
1254 ** in the header of every SQLite database. In this way, if there
1255 ** is a race condition such that another thread has already populated
1256 ** the first page of the database, no damage is done.
1257 */
drh7ed97b92010-01-20 13:07:21 +00001258 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001259 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001260 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001261 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001262 return SQLITE_IOERR;
1263 }
drh99ab3b12011-03-02 15:09:07 +00001264 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001265 if( rc!=0 ){
1266 pFile->lastErrno = errno;
1267 return SQLITE_IOERR;
1268 }
1269 }
drheb0d74f2009-02-03 15:27:02 +00001270#endif
drh6c7d5c52008-11-21 20:32:33 +00001271
drh8af6c222010-05-14 12:43:01 +00001272 memset(&fileId, 0, sizeof(fileId));
1273 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001274#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001275 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001276#else
drh8af6c222010-05-14 12:43:01 +00001277 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001278#endif
drh8af6c222010-05-14 12:43:01 +00001279 pInode = inodeList;
1280 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1281 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001282 }
drh8af6c222010-05-14 12:43:01 +00001283 if( pInode==0 ){
1284 pInode = sqlite3_malloc( sizeof(*pInode) );
1285 if( pInode==0 ){
1286 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001287 }
drh8af6c222010-05-14 12:43:01 +00001288 memset(pInode, 0, sizeof(*pInode));
1289 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1290 pInode->nRef = 1;
1291 pInode->pNext = inodeList;
1292 pInode->pPrev = 0;
1293 if( inodeList ) inodeList->pPrev = pInode;
1294 inodeList = pInode;
1295 }else{
1296 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001297 }
drh8af6c222010-05-14 12:43:01 +00001298 *ppInode = pInode;
1299 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001300}
drh6c7d5c52008-11-21 20:32:33 +00001301
drhb959a012013-12-07 12:29:22 +00001302/*
1303** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1304*/
1305static int fileHasMoved(unixFile *pFile){
1306 struct stat buf;
1307 return pFile->pInode!=0 &&
1308 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
1309}
1310
aswift5b1a2562008-08-22 00:22:35 +00001311
1312/*
drhfbc7e882013-04-11 01:16:15 +00001313** Check a unixFile that is a database. Verify the following:
1314**
1315** (1) There is exactly one hard link on the file
1316** (2) The file is not a symbolic link
1317** (3) The file has not been renamed or unlinked
1318**
1319** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1320*/
1321static void verifyDbFile(unixFile *pFile){
1322 struct stat buf;
1323 int rc;
drh3044b512014-06-16 16:41:52 +00001324 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1325 /* One or more of the following warnings have already been issued. Do not
1326 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001327 return;
1328 }
1329 rc = osFstat(pFile->h, &buf);
1330 if( rc!=0 ){
1331 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1332 pFile->ctrlFlags |= UNIXFILE_WARNED;
1333 return;
1334 }
drh3044b512014-06-16 16:41:52 +00001335 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001336 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1337 pFile->ctrlFlags |= UNIXFILE_WARNED;
1338 return;
1339 }
1340 if( buf.st_nlink>1 ){
1341 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1342 pFile->ctrlFlags |= UNIXFILE_WARNED;
1343 return;
1344 }
drhb959a012013-12-07 12:29:22 +00001345 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001346 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1347 pFile->ctrlFlags |= UNIXFILE_WARNED;
1348 return;
1349 }
1350}
1351
1352
1353/*
danielk197713adf8a2004-06-03 16:08:41 +00001354** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001355** file by this or any other process. If such a lock is held, set *pResOut
1356** to a non-zero value otherwise *pResOut is set to zero. The return value
1357** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001358*/
danielk1977861f7452008-06-05 11:39:11 +00001359static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001360 int rc = SQLITE_OK;
1361 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001362 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001363
danielk1977861f7452008-06-05 11:39:11 +00001364 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1365
drh054889e2005-11-30 03:20:31 +00001366 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001367 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001368
1369 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001370 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001371 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001372 }
1373
drh2ac3ee92004-06-07 16:27:46 +00001374 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001375 */
danielk197709480a92009-02-09 05:32:32 +00001376#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001377 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001378 struct flock lock;
1379 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001380 lock.l_start = RESERVED_BYTE;
1381 lock.l_len = 1;
1382 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001383 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1384 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1385 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001386 } else if( lock.l_type!=F_UNLCK ){
1387 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001388 }
1389 }
danielk197709480a92009-02-09 05:32:32 +00001390#endif
danielk197713adf8a2004-06-03 16:08:41 +00001391
drh6c7d5c52008-11-21 20:32:33 +00001392 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001393 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001394
aswift5b1a2562008-08-22 00:22:35 +00001395 *pResOut = reserved;
1396 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001397}
1398
1399/*
drha7e61d82011-03-12 17:02:57 +00001400** Attempt to set a system-lock on the file pFile. The lock is
1401** described by pLock.
1402**
drh77197112011-03-15 19:08:48 +00001403** If the pFile was opened read/write from unix-excl, then the only lock
1404** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001405** the first time any lock is attempted. All subsequent system locking
1406** operations become no-ops. Locking operations still happen internally,
1407** in order to coordinate access between separate database connections
1408** within this process, but all of that is handled in memory and the
1409** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001410**
1411** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1412** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1413** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001414**
1415** Zero is returned if the call completes successfully, or -1 if a call
1416** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001417*/
1418static int unixFileLock(unixFile *pFile, struct flock *pLock){
1419 int rc;
drh3cb93392011-03-12 18:10:44 +00001420 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001421 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001422 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001423 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1424 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1425 ){
drh3cb93392011-03-12 18:10:44 +00001426 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001427 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001428 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001429 lock.l_whence = SEEK_SET;
1430 lock.l_start = SHARED_FIRST;
1431 lock.l_len = SHARED_SIZE;
1432 lock.l_type = F_WRLCK;
1433 rc = osFcntl(pFile->h, F_SETLK, &lock);
1434 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001435 pInode->bProcessLock = 1;
1436 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001437 }else{
1438 rc = 0;
1439 }
1440 }else{
1441 rc = osFcntl(pFile->h, F_SETLK, pLock);
1442 }
1443 return rc;
1444}
1445
1446/*
drh308c2a52010-05-14 11:30:18 +00001447** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001448** of the following:
1449**
drh2ac3ee92004-06-07 16:27:46 +00001450** (1) SHARED_LOCK
1451** (2) RESERVED_LOCK
1452** (3) PENDING_LOCK
1453** (4) EXCLUSIVE_LOCK
1454**
drhb3e04342004-06-08 00:47:47 +00001455** Sometimes when requesting one lock state, additional lock states
1456** are inserted in between. The locking might fail on one of the later
1457** transitions leaving the lock state different from what it started but
1458** still short of its goal. The following chart shows the allowed
1459** transitions and the inserted intermediate states:
1460**
1461** UNLOCKED -> SHARED
1462** SHARED -> RESERVED
1463** SHARED -> (PENDING) -> EXCLUSIVE
1464** RESERVED -> (PENDING) -> EXCLUSIVE
1465** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001466**
drha6abd042004-06-09 17:37:22 +00001467** This routine will only increase a lock. Use the sqlite3OsUnlock()
1468** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001469*/
drh308c2a52010-05-14 11:30:18 +00001470static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001471 /* The following describes the implementation of the various locks and
1472 ** lock transitions in terms of the POSIX advisory shared and exclusive
1473 ** lock primitives (called read-locks and write-locks below, to avoid
1474 ** confusion with SQLite lock names). The algorithms are complicated
1475 ** slightly in order to be compatible with windows systems simultaneously
1476 ** accessing the same database file, in case that is ever required.
1477 **
1478 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1479 ** byte', each single bytes at well known offsets, and the 'shared byte
1480 ** range', a range of 510 bytes at a well known offset.
1481 **
1482 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1483 ** byte'. If this is successful, a random byte from the 'shared byte
1484 ** range' is read-locked and the lock on the 'pending byte' released.
1485 **
danielk197790ba3bd2004-06-25 08:32:25 +00001486 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1487 ** A RESERVED lock is implemented by grabbing a write-lock on the
1488 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001489 **
1490 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001491 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1492 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1493 ** obtained, but existing SHARED locks are allowed to persist. A process
1494 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1495 ** This property is used by the algorithm for rolling back a journal file
1496 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001497 **
danielk197790ba3bd2004-06-25 08:32:25 +00001498 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1499 ** implemented by obtaining a write-lock on the entire 'shared byte
1500 ** range'. Since all other locks require a read-lock on one of the bytes
1501 ** within this range, this ensures that no other locks are held on the
1502 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001503 **
1504 ** The reason a single byte cannot be used instead of the 'shared byte
1505 ** range' is that some versions of windows do not support read-locks. By
1506 ** locking a random byte from a range, concurrent SHARED locks may exist
1507 ** even if the locking primitive used is always a write-lock.
1508 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001509 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001510 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001511 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001512 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001513 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001514
drh054889e2005-11-30 03:20:31 +00001515 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001516 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1517 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001518 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001519
1520 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001521 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001522 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001523 */
drh308c2a52010-05-14 11:30:18 +00001524 if( pFile->eFileLock>=eFileLock ){
1525 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1526 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001527 return SQLITE_OK;
1528 }
1529
drh0c2694b2009-09-03 16:23:44 +00001530 /* Make sure the locking sequence is correct.
1531 ** (1) We never move from unlocked to anything higher than shared lock.
1532 ** (2) SQLite never explicitly requests a pendig lock.
1533 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001534 */
drh308c2a52010-05-14 11:30:18 +00001535 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1536 assert( eFileLock!=PENDING_LOCK );
1537 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001538
drh8af6c222010-05-14 12:43:01 +00001539 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001540 */
drh6c7d5c52008-11-21 20:32:33 +00001541 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001542 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001543
danielk1977ad94b582007-08-20 06:44:22 +00001544 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001545 ** handle that precludes the requested lock, return BUSY.
1546 */
drh8af6c222010-05-14 12:43:01 +00001547 if( (pFile->eFileLock!=pInode->eFileLock &&
1548 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001549 ){
1550 rc = SQLITE_BUSY;
1551 goto end_lock;
1552 }
1553
1554 /* If a SHARED lock is requested, and some thread using this PID already
1555 ** has a SHARED or RESERVED lock, then increment reference counts and
1556 ** return SQLITE_OK.
1557 */
drh308c2a52010-05-14 11:30:18 +00001558 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001559 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001560 assert( eFileLock==SHARED_LOCK );
1561 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001562 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001563 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001564 pInode->nShared++;
1565 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001566 goto end_lock;
1567 }
1568
danielk19779a1d0ab2004-06-01 14:09:28 +00001569
drh3cde3bb2004-06-12 02:17:14 +00001570 /* A PENDING lock is needed before acquiring a SHARED lock and before
1571 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1572 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001573 */
drh0c2694b2009-09-03 16:23:44 +00001574 lock.l_len = 1L;
1575 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001576 if( eFileLock==SHARED_LOCK
1577 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001578 ){
drh308c2a52010-05-14 11:30:18 +00001579 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001580 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001581 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001582 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001583 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001584 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001585 pFile->lastErrno = tErrno;
1586 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001587 goto end_lock;
1588 }
drh3cde3bb2004-06-12 02:17:14 +00001589 }
1590
1591
1592 /* If control gets to this point, then actually go ahead and make
1593 ** operating system calls for the specified lock.
1594 */
drh308c2a52010-05-14 11:30:18 +00001595 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001596 assert( pInode->nShared==0 );
1597 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001598 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001599
drh2ac3ee92004-06-07 16:27:46 +00001600 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001601 lock.l_start = SHARED_FIRST;
1602 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001603 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001604 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001605 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001606 }
dan661d71a2011-03-30 19:08:03 +00001607
drh2ac3ee92004-06-07 16:27:46 +00001608 /* Drop the temporary PENDING lock */
1609 lock.l_start = PENDING_BYTE;
1610 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001611 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001612 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1613 /* This could happen with a network mount */
1614 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001615 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001616 }
dan661d71a2011-03-30 19:08:03 +00001617
1618 if( rc ){
1619 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001620 pFile->lastErrno = tErrno;
1621 }
dan661d71a2011-03-30 19:08:03 +00001622 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001623 }else{
drh308c2a52010-05-14 11:30:18 +00001624 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001625 pInode->nLock++;
1626 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001627 }
drh8af6c222010-05-14 12:43:01 +00001628 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001629 /* We are trying for an exclusive lock but another thread in this
1630 ** same process is still holding a shared lock. */
1631 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001632 }else{
drh3cde3bb2004-06-12 02:17:14 +00001633 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001634 ** assumed that there is a SHARED or greater lock on the file
1635 ** already.
1636 */
drh308c2a52010-05-14 11:30:18 +00001637 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001638 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001639
1640 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1641 if( eFileLock==RESERVED_LOCK ){
1642 lock.l_start = RESERVED_BYTE;
1643 lock.l_len = 1L;
1644 }else{
1645 lock.l_start = SHARED_FIRST;
1646 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001647 }
dan661d71a2011-03-30 19:08:03 +00001648
1649 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001650 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001651 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001652 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001653 pFile->lastErrno = tErrno;
1654 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001655 }
drhbbd42a62004-05-22 17:41:58 +00001656 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001657
drh8f941bc2009-01-14 23:03:40 +00001658
drhd3d8c042012-05-29 17:02:40 +00001659#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001660 /* Set up the transaction-counter change checking flags when
1661 ** transitioning from a SHARED to a RESERVED lock. The change
1662 ** from SHARED to RESERVED marks the beginning of a normal
1663 ** write operation (not a hot journal rollback).
1664 */
1665 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001666 && pFile->eFileLock<=SHARED_LOCK
1667 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001668 ){
1669 pFile->transCntrChng = 0;
1670 pFile->dbUpdate = 0;
1671 pFile->inNormalWrite = 1;
1672 }
1673#endif
1674
1675
danielk1977ecb2a962004-06-02 06:30:16 +00001676 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001677 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001678 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001679 }else if( eFileLock==EXCLUSIVE_LOCK ){
1680 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001681 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001682 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001683
1684end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001685 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001686 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1687 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001688 return rc;
1689}
1690
1691/*
dan08da86a2009-08-21 17:18:03 +00001692** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001693** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001694*/
1695static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001696 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001697 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001698 p->pNext = pInode->pUnused;
1699 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001700 pFile->h = -1;
1701 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001702}
1703
1704/*
drh308c2a52010-05-14 11:30:18 +00001705** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001706** must be either NO_LOCK or SHARED_LOCK.
1707**
1708** If the locking level of the file descriptor is already at or below
1709** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001710**
1711** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1712** the byte range is divided into 2 parts and the first part is unlocked then
1713** set to a read lock, then the other part is simply unlocked. This works
1714** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1715** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001716*/
drha7e61d82011-03-12 17:02:57 +00001717static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001718 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001719 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001720 struct flock lock;
1721 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001722
drh054889e2005-11-30 03:20:31 +00001723 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001724 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001725 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001726 getpid()));
drha6abd042004-06-09 17:37:22 +00001727
drh308c2a52010-05-14 11:30:18 +00001728 assert( eFileLock<=SHARED_LOCK );
1729 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001730 return SQLITE_OK;
1731 }
drh6c7d5c52008-11-21 20:32:33 +00001732 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001733 pInode = pFile->pInode;
1734 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001735 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001736 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001737
drhd3d8c042012-05-29 17:02:40 +00001738#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001739 /* When reducing a lock such that other processes can start
1740 ** reading the database file again, make sure that the
1741 ** transaction counter was updated if any part of the database
1742 ** file changed. If the transaction counter is not updated,
1743 ** other connections to the same file might not realize that
1744 ** the file has changed and hence might not know to flush their
1745 ** cache. The use of a stale cache can lead to database corruption.
1746 */
drh8f941bc2009-01-14 23:03:40 +00001747 pFile->inNormalWrite = 0;
1748#endif
1749
drh7ed97b92010-01-20 13:07:21 +00001750 /* downgrading to a shared lock on NFS involves clearing the write lock
1751 ** before establishing the readlock - to avoid a race condition we downgrade
1752 ** the lock in 2 blocks, so that part of the range will be covered by a
1753 ** write lock until the rest is covered by a read lock:
1754 ** 1: [WWWWW]
1755 ** 2: [....W]
1756 ** 3: [RRRRW]
1757 ** 4: [RRRR.]
1758 */
drh308c2a52010-05-14 11:30:18 +00001759 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001760
1761#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001762 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001763 assert( handleNFSUnlock==0 );
1764#endif
1765#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001766 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001767 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001768 off_t divSize = SHARED_SIZE - 1;
1769
1770 lock.l_type = F_UNLCK;
1771 lock.l_whence = SEEK_SET;
1772 lock.l_start = SHARED_FIRST;
1773 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001774 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001775 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001776 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001777 if( IS_LOCK_ERROR(rc) ){
1778 pFile->lastErrno = tErrno;
1779 }
1780 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001781 }
drh7ed97b92010-01-20 13:07:21 +00001782 lock.l_type = F_RDLCK;
1783 lock.l_whence = SEEK_SET;
1784 lock.l_start = SHARED_FIRST;
1785 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001786 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001787 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001788 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1789 if( IS_LOCK_ERROR(rc) ){
1790 pFile->lastErrno = tErrno;
1791 }
1792 goto end_unlock;
1793 }
1794 lock.l_type = F_UNLCK;
1795 lock.l_whence = SEEK_SET;
1796 lock.l_start = SHARED_FIRST+divSize;
1797 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001798 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001799 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001800 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001801 if( IS_LOCK_ERROR(rc) ){
1802 pFile->lastErrno = tErrno;
1803 }
1804 goto end_unlock;
1805 }
drh30f776f2011-02-25 03:25:07 +00001806 }else
1807#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1808 {
drh7ed97b92010-01-20 13:07:21 +00001809 lock.l_type = F_RDLCK;
1810 lock.l_whence = SEEK_SET;
1811 lock.l_start = SHARED_FIRST;
1812 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001813 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001814 /* In theory, the call to unixFileLock() cannot fail because another
1815 ** process is holding an incompatible lock. If it does, this
1816 ** indicates that the other process is not following the locking
1817 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1818 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1819 ** an assert to fail). */
1820 rc = SQLITE_IOERR_RDLOCK;
1821 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001822 goto end_unlock;
1823 }
drh9c105bb2004-10-02 20:38:28 +00001824 }
1825 }
drhbbd42a62004-05-22 17:41:58 +00001826 lock.l_type = F_UNLCK;
1827 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001828 lock.l_start = PENDING_BYTE;
1829 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001830 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001831 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001832 }else{
danea83bc62011-04-01 11:56:32 +00001833 rc = SQLITE_IOERR_UNLOCK;
1834 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001835 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001836 }
drhbbd42a62004-05-22 17:41:58 +00001837 }
drh308c2a52010-05-14 11:30:18 +00001838 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001839 /* Decrement the shared lock counter. Release the lock using an
1840 ** OS call only when all threads in this same process have released
1841 ** the lock.
1842 */
drh8af6c222010-05-14 12:43:01 +00001843 pInode->nShared--;
1844 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001845 lock.l_type = F_UNLCK;
1846 lock.l_whence = SEEK_SET;
1847 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001848 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001849 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001850 }else{
danea83bc62011-04-01 11:56:32 +00001851 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001852 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001853 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001854 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001855 }
drha6abd042004-06-09 17:37:22 +00001856 }
1857
drhbbd42a62004-05-22 17:41:58 +00001858 /* Decrement the count of locks against this same file. When the
1859 ** count reaches zero, close any other file descriptors whose close
1860 ** was deferred because of outstanding locks.
1861 */
drh8af6c222010-05-14 12:43:01 +00001862 pInode->nLock--;
1863 assert( pInode->nLock>=0 );
1864 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001865 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001866 }
1867 }
drhf2f105d2012-08-20 15:53:54 +00001868
aswift5b1a2562008-08-22 00:22:35 +00001869end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001870 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001871 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001872 return rc;
drhbbd42a62004-05-22 17:41:58 +00001873}
1874
1875/*
drh308c2a52010-05-14 11:30:18 +00001876** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001877** must be either NO_LOCK or SHARED_LOCK.
1878**
1879** If the locking level of the file descriptor is already at or below
1880** the requested locking level, this routine is a no-op.
1881*/
drh308c2a52010-05-14 11:30:18 +00001882static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001883#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001884 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001885#endif
drha7e61d82011-03-12 17:02:57 +00001886 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001887}
1888
mistachkine98844f2013-08-24 00:59:24 +00001889#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001890static int unixMapfile(unixFile *pFd, i64 nByte);
1891static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001892#endif
danf23da962013-03-23 21:00:41 +00001893
drh7ed97b92010-01-20 13:07:21 +00001894/*
danielk1977e339d652008-06-28 11:23:00 +00001895** This function performs the parts of the "close file" operation
1896** common to all locking schemes. It closes the directory and file
1897** handles, if they are valid, and sets all fields of the unixFile
1898** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001899**
1900** It is *not* necessary to hold the mutex when this routine is called,
1901** even on VxWorks. A mutex will be acquired on VxWorks by the
1902** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001903*/
1904static int closeUnixFile(sqlite3_file *id){
1905 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001906#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001907 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001908#endif
dan661d71a2011-03-30 19:08:03 +00001909 if( pFile->h>=0 ){
1910 robust_close(pFile, pFile->h, __LINE__);
1911 pFile->h = -1;
1912 }
1913#if OS_VXWORKS
1914 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001915 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001916 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001917 }
1918 vxworksReleaseFileId(pFile->pId);
1919 pFile->pId = 0;
1920 }
1921#endif
1922 OSTRACE(("CLOSE %-3d\n", pFile->h));
1923 OpenCounter(-1);
1924 sqlite3_free(pFile->pUnused);
1925 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001926 return SQLITE_OK;
1927}
1928
1929/*
danielk1977e3026632004-06-22 11:29:02 +00001930** Close a file.
1931*/
danielk197762079062007-08-15 17:08:46 +00001932static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001933 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001934 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001935 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001936 unixUnlock(id, NO_LOCK);
1937 unixEnterMutex();
1938
1939 /* unixFile.pInode is always valid here. Otherwise, a different close
1940 ** routine (e.g. nolockClose()) would be called instead.
1941 */
1942 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1943 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1944 /* If there are outstanding locks, do not actually close the file just
1945 ** yet because that would clear those locks. Instead, add the file
1946 ** descriptor to pInode->pUnused list. It will be automatically closed
1947 ** when the last lock is cleared.
1948 */
1949 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001950 }
dan661d71a2011-03-30 19:08:03 +00001951 releaseInodeInfo(pFile);
1952 rc = closeUnixFile(id);
1953 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001954 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001955}
1956
drh734c9862008-11-28 15:37:20 +00001957/************** End of the posix advisory lock implementation *****************
1958******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001959
drh734c9862008-11-28 15:37:20 +00001960/******************************************************************************
1961****************************** No-op Locking **********************************
1962**
1963** Of the various locking implementations available, this is by far the
1964** simplest: locking is ignored. No attempt is made to lock the database
1965** file for reading or writing.
1966**
1967** This locking mode is appropriate for use on read-only databases
1968** (ex: databases that are burned into CD-ROM, for example.) It can
1969** also be used if the application employs some external mechanism to
1970** prevent simultaneous access of the same database by two or more
1971** database connections. But there is a serious risk of database
1972** corruption if this locking mode is used in situations where multiple
1973** database connections are accessing the same database file at the same
1974** time and one or more of those connections are writing.
1975*/
drhbfe66312006-10-03 17:40:40 +00001976
drh734c9862008-11-28 15:37:20 +00001977static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1978 UNUSED_PARAMETER(NotUsed);
1979 *pResOut = 0;
1980 return SQLITE_OK;
1981}
drh734c9862008-11-28 15:37:20 +00001982static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1983 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1984 return SQLITE_OK;
1985}
drh734c9862008-11-28 15:37:20 +00001986static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1987 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1988 return SQLITE_OK;
1989}
1990
1991/*
drh9b35ea62008-11-29 02:20:26 +00001992** Close the file.
drh734c9862008-11-28 15:37:20 +00001993*/
1994static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001995 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001996}
1997
1998/******************* End of the no-op lock implementation *********************
1999******************************************************************************/
2000
2001/******************************************************************************
2002************************* Begin dot-file Locking ******************************
2003**
mistachkin48864df2013-03-21 21:20:32 +00002004** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002005** files (really a directory) to control access to the database. This works
2006** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002007**
2008** (1) There is zero concurrency. A single reader blocks all other
2009** connections from reading or writing the database.
2010**
2011** (2) An application crash or power loss can leave stale lock files
2012** sitting around that need to be cleared manually.
2013**
2014** Nevertheless, a dotlock is an appropriate locking mode for use if no
2015** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002016**
drh9ef6bc42011-11-04 02:24:02 +00002017** Dotfile locking works by creating a subdirectory in the same directory as
2018** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002019** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002020** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002021*/
2022
2023/*
2024** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002025** lock directory.
drh734c9862008-11-28 15:37:20 +00002026*/
2027#define DOTLOCK_SUFFIX ".lock"
2028
drh7708e972008-11-29 00:56:52 +00002029/*
2030** This routine checks if there is a RESERVED lock held on the specified
2031** file by this or any other process. If such a lock is held, set *pResOut
2032** to a non-zero value otherwise *pResOut is set to zero. The return value
2033** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2034**
2035** In dotfile locking, either a lock exists or it does not. So in this
2036** variation of CheckReservedLock(), *pResOut is set to true if any lock
2037** is held on the file and false if the file is unlocked.
2038*/
drh734c9862008-11-28 15:37:20 +00002039static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2040 int rc = SQLITE_OK;
2041 int reserved = 0;
2042 unixFile *pFile = (unixFile*)id;
2043
2044 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2045
2046 assert( pFile );
2047
2048 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002049 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002050 /* Either this connection or some other connection in the same process
2051 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002052 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002053 }else{
2054 /* The lock is held if and only if the lockfile exists */
2055 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002056 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002057 }
drh308c2a52010-05-14 11:30:18 +00002058 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002059 *pResOut = reserved;
2060 return rc;
2061}
2062
drh7708e972008-11-29 00:56:52 +00002063/*
drh308c2a52010-05-14 11:30:18 +00002064** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002065** of the following:
2066**
2067** (1) SHARED_LOCK
2068** (2) RESERVED_LOCK
2069** (3) PENDING_LOCK
2070** (4) EXCLUSIVE_LOCK
2071**
2072** Sometimes when requesting one lock state, additional lock states
2073** are inserted in between. The locking might fail on one of the later
2074** transitions leaving the lock state different from what it started but
2075** still short of its goal. The following chart shows the allowed
2076** transitions and the inserted intermediate states:
2077**
2078** UNLOCKED -> SHARED
2079** SHARED -> RESERVED
2080** SHARED -> (PENDING) -> EXCLUSIVE
2081** RESERVED -> (PENDING) -> EXCLUSIVE
2082** PENDING -> EXCLUSIVE
2083**
2084** This routine will only increase a lock. Use the sqlite3OsUnlock()
2085** routine to lower a locking level.
2086**
2087** With dotfile locking, we really only support state (4): EXCLUSIVE.
2088** But we track the other locking levels internally.
2089*/
drh308c2a52010-05-14 11:30:18 +00002090static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002091 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002092 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002093 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002094
drh7708e972008-11-29 00:56:52 +00002095
2096 /* If we have any lock, then the lock file already exists. All we have
2097 ** to do is adjust our internal record of the lock level.
2098 */
drh308c2a52010-05-14 11:30:18 +00002099 if( pFile->eFileLock > NO_LOCK ){
2100 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002101 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002102#ifdef HAVE_UTIME
2103 utime(zLockFile, NULL);
2104#else
drh734c9862008-11-28 15:37:20 +00002105 utimes(zLockFile, NULL);
2106#endif
drh7708e972008-11-29 00:56:52 +00002107 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002108 }
2109
2110 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002111 rc = osMkdir(zLockFile, 0777);
2112 if( rc<0 ){
2113 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002114 int tErrno = errno;
2115 if( EEXIST == tErrno ){
2116 rc = SQLITE_BUSY;
2117 } else {
2118 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2119 if( IS_LOCK_ERROR(rc) ){
2120 pFile->lastErrno = tErrno;
2121 }
2122 }
drh7708e972008-11-29 00:56:52 +00002123 return rc;
drh734c9862008-11-28 15:37:20 +00002124 }
drh734c9862008-11-28 15:37:20 +00002125
2126 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002127 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002128 return rc;
2129}
2130
drh7708e972008-11-29 00:56:52 +00002131/*
drh308c2a52010-05-14 11:30:18 +00002132** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002133** must be either NO_LOCK or SHARED_LOCK.
2134**
2135** If the locking level of the file descriptor is already at or below
2136** the requested locking level, this routine is a no-op.
2137**
2138** When the locking level reaches NO_LOCK, delete the lock file.
2139*/
drh308c2a52010-05-14 11:30:18 +00002140static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002141 unixFile *pFile = (unixFile*)id;
2142 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002143 int rc;
drh734c9862008-11-28 15:37:20 +00002144
2145 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002146 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002147 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002148 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002149
2150 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002151 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002152 return SQLITE_OK;
2153 }
drh7708e972008-11-29 00:56:52 +00002154
2155 /* To downgrade to shared, simply update our internal notion of the
2156 ** lock state. No need to mess with the file on disk.
2157 */
drh308c2a52010-05-14 11:30:18 +00002158 if( eFileLock==SHARED_LOCK ){
2159 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002160 return SQLITE_OK;
2161 }
2162
drh7708e972008-11-29 00:56:52 +00002163 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002164 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002165 rc = osRmdir(zLockFile);
2166 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2167 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002168 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002169 rc = 0;
drh734c9862008-11-28 15:37:20 +00002170 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002171 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002172 }
2173 if( IS_LOCK_ERROR(rc) ){
2174 pFile->lastErrno = tErrno;
2175 }
2176 return rc;
2177 }
drh308c2a52010-05-14 11:30:18 +00002178 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002179 return SQLITE_OK;
2180}
2181
2182/*
drh9b35ea62008-11-29 02:20:26 +00002183** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002184*/
2185static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002186 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002187 if( id ){
2188 unixFile *pFile = (unixFile*)id;
2189 dotlockUnlock(id, NO_LOCK);
2190 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002191 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002192 }
drh734c9862008-11-28 15:37:20 +00002193 return rc;
2194}
2195/****************** End of the dot-file lock implementation *******************
2196******************************************************************************/
2197
2198/******************************************************************************
2199************************** Begin flock Locking ********************************
2200**
2201** Use the flock() system call to do file locking.
2202**
drh6b9d6dd2008-12-03 19:34:47 +00002203** flock() locking is like dot-file locking in that the various
2204** fine-grain locking levels supported by SQLite are collapsed into
2205** a single exclusive lock. In other words, SHARED, RESERVED, and
2206** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2207** still works when you do this, but concurrency is reduced since
2208** only a single process can be reading the database at a time.
2209**
drh734c9862008-11-28 15:37:20 +00002210** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2211** compiling for VXWORKS.
2212*/
2213#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002214
drh6b9d6dd2008-12-03 19:34:47 +00002215/*
drhff812312011-02-23 13:33:46 +00002216** Retry flock() calls that fail with EINTR
2217*/
2218#ifdef EINTR
2219static int robust_flock(int fd, int op){
2220 int rc;
2221 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2222 return rc;
2223}
2224#else
drh5c819272011-02-23 14:00:12 +00002225# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002226#endif
2227
2228
2229/*
drh6b9d6dd2008-12-03 19:34:47 +00002230** This routine checks if there is a RESERVED lock held on the specified
2231** file by this or any other process. If such a lock is held, set *pResOut
2232** to a non-zero value otherwise *pResOut is set to zero. The return value
2233** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2234*/
drh734c9862008-11-28 15:37:20 +00002235static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2236 int rc = SQLITE_OK;
2237 int reserved = 0;
2238 unixFile *pFile = (unixFile*)id;
2239
2240 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2241
2242 assert( pFile );
2243
2244 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002245 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002246 reserved = 1;
2247 }
2248
2249 /* Otherwise see if some other process holds it. */
2250 if( !reserved ){
2251 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002252 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002253 if( !lrc ){
2254 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002255 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002256 if ( lrc ) {
2257 int tErrno = errno;
2258 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002259 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002260 if( IS_LOCK_ERROR(lrc) ){
2261 pFile->lastErrno = tErrno;
2262 rc = lrc;
2263 }
2264 }
2265 } else {
2266 int tErrno = errno;
2267 reserved = 1;
2268 /* someone else might have it reserved */
2269 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2270 if( IS_LOCK_ERROR(lrc) ){
2271 pFile->lastErrno = tErrno;
2272 rc = lrc;
2273 }
2274 }
2275 }
drh308c2a52010-05-14 11:30:18 +00002276 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002277
2278#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2279 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2280 rc = SQLITE_OK;
2281 reserved=1;
2282 }
2283#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2284 *pResOut = reserved;
2285 return rc;
2286}
2287
drh6b9d6dd2008-12-03 19:34:47 +00002288/*
drh308c2a52010-05-14 11:30:18 +00002289** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002290** of the following:
2291**
2292** (1) SHARED_LOCK
2293** (2) RESERVED_LOCK
2294** (3) PENDING_LOCK
2295** (4) EXCLUSIVE_LOCK
2296**
2297** Sometimes when requesting one lock state, additional lock states
2298** are inserted in between. The locking might fail on one of the later
2299** transitions leaving the lock state different from what it started but
2300** still short of its goal. The following chart shows the allowed
2301** transitions and the inserted intermediate states:
2302**
2303** UNLOCKED -> SHARED
2304** SHARED -> RESERVED
2305** SHARED -> (PENDING) -> EXCLUSIVE
2306** RESERVED -> (PENDING) -> EXCLUSIVE
2307** PENDING -> EXCLUSIVE
2308**
2309** flock() only really support EXCLUSIVE locks. We track intermediate
2310** lock states in the sqlite3_file structure, but all locks SHARED or
2311** above are really EXCLUSIVE locks and exclude all other processes from
2312** access the file.
2313**
2314** This routine will only increase a lock. Use the sqlite3OsUnlock()
2315** routine to lower a locking level.
2316*/
drh308c2a52010-05-14 11:30:18 +00002317static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002318 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002319 unixFile *pFile = (unixFile*)id;
2320
2321 assert( pFile );
2322
2323 /* if we already have a lock, it is exclusive.
2324 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002325 if (pFile->eFileLock > NO_LOCK) {
2326 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002327 return SQLITE_OK;
2328 }
2329
2330 /* grab an exclusive lock */
2331
drhff812312011-02-23 13:33:46 +00002332 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002333 int tErrno = errno;
2334 /* didn't get, must be busy */
2335 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2336 if( IS_LOCK_ERROR(rc) ){
2337 pFile->lastErrno = tErrno;
2338 }
2339 } else {
2340 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002341 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002342 }
drh308c2a52010-05-14 11:30:18 +00002343 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2344 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002345#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2346 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2347 rc = SQLITE_BUSY;
2348 }
2349#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2350 return rc;
2351}
2352
drh6b9d6dd2008-12-03 19:34:47 +00002353
2354/*
drh308c2a52010-05-14 11:30:18 +00002355** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002356** must be either NO_LOCK or SHARED_LOCK.
2357**
2358** If the locking level of the file descriptor is already at or below
2359** the requested locking level, this routine is a no-op.
2360*/
drh308c2a52010-05-14 11:30:18 +00002361static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002362 unixFile *pFile = (unixFile*)id;
2363
2364 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002365 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2366 pFile->eFileLock, getpid()));
2367 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002368
2369 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002370 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002371 return SQLITE_OK;
2372 }
2373
2374 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002375 if (eFileLock==SHARED_LOCK) {
2376 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002377 return SQLITE_OK;
2378 }
2379
2380 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002381 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002382#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002383 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002384#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002385 return SQLITE_IOERR_UNLOCK;
2386 }else{
drh308c2a52010-05-14 11:30:18 +00002387 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002388 return SQLITE_OK;
2389 }
2390}
2391
2392/*
2393** Close a file.
2394*/
2395static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002396 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002397 if( id ){
2398 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002399 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002400 }
drh5a05be12012-10-09 18:51:44 +00002401 return rc;
drh734c9862008-11-28 15:37:20 +00002402}
2403
2404#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2405
2406/******************* End of the flock lock implementation *********************
2407******************************************************************************/
2408
2409/******************************************************************************
2410************************ Begin Named Semaphore Locking ************************
2411**
2412** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002413**
2414** Semaphore locking is like dot-lock and flock in that it really only
2415** supports EXCLUSIVE locking. Only a single process can read or write
2416** the database file at a time. This reduces potential concurrency, but
2417** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002418*/
2419#if OS_VXWORKS
2420
drh6b9d6dd2008-12-03 19:34:47 +00002421/*
2422** This routine checks if there is a RESERVED lock held on the specified
2423** file by this or any other process. If such a lock is held, set *pResOut
2424** to a non-zero value otherwise *pResOut is set to zero. The return value
2425** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2426*/
drh734c9862008-11-28 15:37:20 +00002427static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2428 int rc = SQLITE_OK;
2429 int reserved = 0;
2430 unixFile *pFile = (unixFile*)id;
2431
2432 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2433
2434 assert( pFile );
2435
2436 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002437 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002438 reserved = 1;
2439 }
2440
2441 /* Otherwise see if some other process holds it. */
2442 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002443 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002444 struct stat statBuf;
2445
2446 if( sem_trywait(pSem)==-1 ){
2447 int tErrno = errno;
2448 if( EAGAIN != tErrno ){
2449 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2450 pFile->lastErrno = tErrno;
2451 } else {
2452 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002453 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002454 }
2455 }else{
2456 /* we could have it if we want it */
2457 sem_post(pSem);
2458 }
2459 }
drh308c2a52010-05-14 11:30:18 +00002460 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002461
2462 *pResOut = reserved;
2463 return rc;
2464}
2465
drh6b9d6dd2008-12-03 19:34:47 +00002466/*
drh308c2a52010-05-14 11:30:18 +00002467** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002468** of the following:
2469**
2470** (1) SHARED_LOCK
2471** (2) RESERVED_LOCK
2472** (3) PENDING_LOCK
2473** (4) EXCLUSIVE_LOCK
2474**
2475** Sometimes when requesting one lock state, additional lock states
2476** are inserted in between. The locking might fail on one of the later
2477** transitions leaving the lock state different from what it started but
2478** still short of its goal. The following chart shows the allowed
2479** transitions and the inserted intermediate states:
2480**
2481** UNLOCKED -> SHARED
2482** SHARED -> RESERVED
2483** SHARED -> (PENDING) -> EXCLUSIVE
2484** RESERVED -> (PENDING) -> EXCLUSIVE
2485** PENDING -> EXCLUSIVE
2486**
2487** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2488** lock states in the sqlite3_file structure, but all locks SHARED or
2489** above are really EXCLUSIVE locks and exclude all other processes from
2490** access the file.
2491**
2492** This routine will only increase a lock. Use the sqlite3OsUnlock()
2493** routine to lower a locking level.
2494*/
drh308c2a52010-05-14 11:30:18 +00002495static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002496 unixFile *pFile = (unixFile*)id;
2497 int fd;
drh8af6c222010-05-14 12:43:01 +00002498 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002499 int rc = SQLITE_OK;
2500
2501 /* if we already have a lock, it is exclusive.
2502 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002503 if (pFile->eFileLock > NO_LOCK) {
2504 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002505 rc = SQLITE_OK;
2506 goto sem_end_lock;
2507 }
2508
2509 /* lock semaphore now but bail out when already locked. */
2510 if( sem_trywait(pSem)==-1 ){
2511 rc = SQLITE_BUSY;
2512 goto sem_end_lock;
2513 }
2514
2515 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002516 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002517
2518 sem_end_lock:
2519 return rc;
2520}
2521
drh6b9d6dd2008-12-03 19:34:47 +00002522/*
drh308c2a52010-05-14 11:30:18 +00002523** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002524** must be either NO_LOCK or SHARED_LOCK.
2525**
2526** If the locking level of the file descriptor is already at or below
2527** the requested locking level, this routine is a no-op.
2528*/
drh308c2a52010-05-14 11:30:18 +00002529static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002530 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002531 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002532
2533 assert( pFile );
2534 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002535 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002536 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002537 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002538
2539 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002540 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002541 return SQLITE_OK;
2542 }
2543
2544 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002545 if (eFileLock==SHARED_LOCK) {
2546 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002547 return SQLITE_OK;
2548 }
2549
2550 /* no, really unlock. */
2551 if ( sem_post(pSem)==-1 ) {
2552 int rc, tErrno = errno;
2553 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2554 if( IS_LOCK_ERROR(rc) ){
2555 pFile->lastErrno = tErrno;
2556 }
2557 return rc;
2558 }
drh308c2a52010-05-14 11:30:18 +00002559 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002560 return SQLITE_OK;
2561}
2562
2563/*
2564 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002565 */
drh734c9862008-11-28 15:37:20 +00002566static int semClose(sqlite3_file *id) {
2567 if( id ){
2568 unixFile *pFile = (unixFile*)id;
2569 semUnlock(id, NO_LOCK);
2570 assert( pFile );
2571 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002572 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002573 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002574 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002575 }
2576 return SQLITE_OK;
2577}
2578
2579#endif /* OS_VXWORKS */
2580/*
2581** Named semaphore locking is only available on VxWorks.
2582**
2583*************** End of the named semaphore lock implementation ****************
2584******************************************************************************/
2585
2586
2587/******************************************************************************
2588*************************** Begin AFP Locking *********************************
2589**
2590** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2591** on Apple Macintosh computers - both OS9 and OSX.
2592**
2593** Third-party implementations of AFP are available. But this code here
2594** only works on OSX.
2595*/
2596
drhd2cb50b2009-01-09 21:41:17 +00002597#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002598/*
2599** The afpLockingContext structure contains all afp lock specific state
2600*/
drhbfe66312006-10-03 17:40:40 +00002601typedef struct afpLockingContext afpLockingContext;
2602struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002603 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002604 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002605};
2606
2607struct ByteRangeLockPB2
2608{
2609 unsigned long long offset; /* offset to first byte to lock */
2610 unsigned long long length; /* nbr of bytes to lock */
2611 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2612 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2613 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2614 int fd; /* file desc to assoc this lock with */
2615};
2616
drhfd131da2007-08-07 17:13:03 +00002617#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002618
drh6b9d6dd2008-12-03 19:34:47 +00002619/*
2620** This is a utility for setting or clearing a bit-range lock on an
2621** AFP filesystem.
2622**
2623** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2624*/
2625static int afpSetLock(
2626 const char *path, /* Name of the file to be locked or unlocked */
2627 unixFile *pFile, /* Open file descriptor on path */
2628 unsigned long long offset, /* First byte to be locked */
2629 unsigned long long length, /* Number of bytes to lock */
2630 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002631){
drh6b9d6dd2008-12-03 19:34:47 +00002632 struct ByteRangeLockPB2 pb;
2633 int err;
drhbfe66312006-10-03 17:40:40 +00002634
2635 pb.unLockFlag = setLockFlag ? 0 : 1;
2636 pb.startEndFlag = 0;
2637 pb.offset = offset;
2638 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002639 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002640
drh308c2a52010-05-14 11:30:18 +00002641 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002642 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002643 offset, length));
drhbfe66312006-10-03 17:40:40 +00002644 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2645 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002646 int rc;
2647 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002648 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2649 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002650#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2651 rc = SQLITE_BUSY;
2652#else
drh734c9862008-11-28 15:37:20 +00002653 rc = sqliteErrorFromPosixError(tErrno,
2654 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002655#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002656 if( IS_LOCK_ERROR(rc) ){
2657 pFile->lastErrno = tErrno;
2658 }
2659 return rc;
drhbfe66312006-10-03 17:40:40 +00002660 } else {
aswift5b1a2562008-08-22 00:22:35 +00002661 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002662 }
2663}
2664
drh6b9d6dd2008-12-03 19:34:47 +00002665/*
2666** This routine checks if there is a RESERVED lock held on the specified
2667** file by this or any other process. If such a lock is held, set *pResOut
2668** to a non-zero value otherwise *pResOut is set to zero. The return value
2669** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2670*/
danielk1977e339d652008-06-28 11:23:00 +00002671static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002672 int rc = SQLITE_OK;
2673 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002674 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002675 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002676
aswift5b1a2562008-08-22 00:22:35 +00002677 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2678
2679 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002680 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002681 if( context->reserved ){
2682 *pResOut = 1;
2683 return SQLITE_OK;
2684 }
drh8af6c222010-05-14 12:43:01 +00002685 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002686
2687 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002688 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002689 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002690 }
2691
2692 /* Otherwise see if some other process holds it.
2693 */
aswift5b1a2562008-08-22 00:22:35 +00002694 if( !reserved ){
2695 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002696 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002697 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002698 /* if we succeeded in taking the reserved lock, unlock it to restore
2699 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002700 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002701 } else {
2702 /* if we failed to get the lock then someone else must have it */
2703 reserved = 1;
2704 }
2705 if( IS_LOCK_ERROR(lrc) ){
2706 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002707 }
2708 }
drhbfe66312006-10-03 17:40:40 +00002709
drh7ed97b92010-01-20 13:07:21 +00002710 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002711 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002712
2713 *pResOut = reserved;
2714 return rc;
drhbfe66312006-10-03 17:40:40 +00002715}
2716
drh6b9d6dd2008-12-03 19:34:47 +00002717/*
drh308c2a52010-05-14 11:30:18 +00002718** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002719** of the following:
2720**
2721** (1) SHARED_LOCK
2722** (2) RESERVED_LOCK
2723** (3) PENDING_LOCK
2724** (4) EXCLUSIVE_LOCK
2725**
2726** Sometimes when requesting one lock state, additional lock states
2727** are inserted in between. The locking might fail on one of the later
2728** transitions leaving the lock state different from what it started but
2729** still short of its goal. The following chart shows the allowed
2730** transitions and the inserted intermediate states:
2731**
2732** UNLOCKED -> SHARED
2733** SHARED -> RESERVED
2734** SHARED -> (PENDING) -> EXCLUSIVE
2735** RESERVED -> (PENDING) -> EXCLUSIVE
2736** PENDING -> EXCLUSIVE
2737**
2738** This routine will only increase a lock. Use the sqlite3OsUnlock()
2739** routine to lower a locking level.
2740*/
drh308c2a52010-05-14 11:30:18 +00002741static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002742 int rc = SQLITE_OK;
2743 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002744 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002745 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002746
2747 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002748 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2749 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002750 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002751
drhbfe66312006-10-03 17:40:40 +00002752 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002753 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002754 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002755 */
drh308c2a52010-05-14 11:30:18 +00002756 if( pFile->eFileLock>=eFileLock ){
2757 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2758 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002759 return SQLITE_OK;
2760 }
2761
2762 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002763 ** (1) We never move from unlocked to anything higher than shared lock.
2764 ** (2) SQLite never explicitly requests a pendig lock.
2765 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002766 */
drh308c2a52010-05-14 11:30:18 +00002767 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2768 assert( eFileLock!=PENDING_LOCK );
2769 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002770
drh8af6c222010-05-14 12:43:01 +00002771 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002772 */
drh6c7d5c52008-11-21 20:32:33 +00002773 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002774 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002775
2776 /* If some thread using this PID has a lock via a different unixFile*
2777 ** handle that precludes the requested lock, return BUSY.
2778 */
drh8af6c222010-05-14 12:43:01 +00002779 if( (pFile->eFileLock!=pInode->eFileLock &&
2780 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002781 ){
2782 rc = SQLITE_BUSY;
2783 goto afp_end_lock;
2784 }
2785
2786 /* If a SHARED lock is requested, and some thread using this PID already
2787 ** has a SHARED or RESERVED lock, then increment reference counts and
2788 ** return SQLITE_OK.
2789 */
drh308c2a52010-05-14 11:30:18 +00002790 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002791 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002792 assert( eFileLock==SHARED_LOCK );
2793 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002794 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002795 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002796 pInode->nShared++;
2797 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002798 goto afp_end_lock;
2799 }
drhbfe66312006-10-03 17:40:40 +00002800
2801 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002802 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2803 ** be released.
2804 */
drh308c2a52010-05-14 11:30:18 +00002805 if( eFileLock==SHARED_LOCK
2806 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002807 ){
2808 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002809 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002810 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002811 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002812 goto afp_end_lock;
2813 }
2814 }
2815
2816 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002817 ** operating system calls for the specified lock.
2818 */
drh308c2a52010-05-14 11:30:18 +00002819 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002820 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002821 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002822
drh8af6c222010-05-14 12:43:01 +00002823 assert( pInode->nShared==0 );
2824 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002825
2826 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002827 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002828 /* note that the quality of the randomness doesn't matter that much */
2829 lk = random();
drh8af6c222010-05-14 12:43:01 +00002830 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002831 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002832 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002833 if( IS_LOCK_ERROR(lrc1) ){
2834 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002835 }
aswift5b1a2562008-08-22 00:22:35 +00002836 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002837 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002838
aswift5b1a2562008-08-22 00:22:35 +00002839 if( IS_LOCK_ERROR(lrc1) ) {
2840 pFile->lastErrno = lrc1Errno;
2841 rc = lrc1;
2842 goto afp_end_lock;
2843 } else if( IS_LOCK_ERROR(lrc2) ){
2844 rc = lrc2;
2845 goto afp_end_lock;
2846 } else if( lrc1 != SQLITE_OK ) {
2847 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002848 } else {
drh308c2a52010-05-14 11:30:18 +00002849 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002850 pInode->nLock++;
2851 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002852 }
drh8af6c222010-05-14 12:43:01 +00002853 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002854 /* We are trying for an exclusive lock but another thread in this
2855 ** same process is still holding a shared lock. */
2856 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002857 }else{
2858 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2859 ** assumed that there is a SHARED or greater lock on the file
2860 ** already.
2861 */
2862 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002863 assert( 0!=pFile->eFileLock );
2864 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002865 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002866 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002867 if( !failed ){
2868 context->reserved = 1;
2869 }
drhbfe66312006-10-03 17:40:40 +00002870 }
drh308c2a52010-05-14 11:30:18 +00002871 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002872 /* Acquire an EXCLUSIVE lock */
2873
2874 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002875 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002876 */
drh6b9d6dd2008-12-03 19:34:47 +00002877 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002878 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002879 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002880 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002881 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002882 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002883 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002884 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002885 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2886 ** a critical I/O error
2887 */
2888 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2889 SQLITE_IOERR_LOCK;
2890 goto afp_end_lock;
2891 }
2892 }else{
aswift5b1a2562008-08-22 00:22:35 +00002893 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002894 }
2895 }
aswift5b1a2562008-08-22 00:22:35 +00002896 if( failed ){
2897 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002898 }
2899 }
2900
2901 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002902 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002903 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002904 }else if( eFileLock==EXCLUSIVE_LOCK ){
2905 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002906 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002907 }
2908
2909afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002910 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002911 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2912 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002913 return rc;
2914}
2915
2916/*
drh308c2a52010-05-14 11:30:18 +00002917** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002918** must be either NO_LOCK or SHARED_LOCK.
2919**
2920** If the locking level of the file descriptor is already at or below
2921** the requested locking level, this routine is a no-op.
2922*/
drh308c2a52010-05-14 11:30:18 +00002923static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002924 int rc = SQLITE_OK;
2925 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002926 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002927 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2928 int skipShared = 0;
2929#ifdef SQLITE_TEST
2930 int h = pFile->h;
2931#endif
drhbfe66312006-10-03 17:40:40 +00002932
2933 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002934 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002935 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002936 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002937
drh308c2a52010-05-14 11:30:18 +00002938 assert( eFileLock<=SHARED_LOCK );
2939 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002940 return SQLITE_OK;
2941 }
drh6c7d5c52008-11-21 20:32:33 +00002942 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002943 pInode = pFile->pInode;
2944 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002945 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002946 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002947 SimulateIOErrorBenign(1);
2948 SimulateIOError( h=(-1) )
2949 SimulateIOErrorBenign(0);
2950
drhd3d8c042012-05-29 17:02:40 +00002951#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002952 /* When reducing a lock such that other processes can start
2953 ** reading the database file again, make sure that the
2954 ** transaction counter was updated if any part of the database
2955 ** file changed. If the transaction counter is not updated,
2956 ** other connections to the same file might not realize that
2957 ** the file has changed and hence might not know to flush their
2958 ** cache. The use of a stale cache can lead to database corruption.
2959 */
2960 assert( pFile->inNormalWrite==0
2961 || pFile->dbUpdate==0
2962 || pFile->transCntrChng==1 );
2963 pFile->inNormalWrite = 0;
2964#endif
aswiftaebf4132008-11-21 00:10:35 +00002965
drh308c2a52010-05-14 11:30:18 +00002966 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002967 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002968 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002969 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002970 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002971 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2972 } else {
2973 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002974 }
2975 }
drh308c2a52010-05-14 11:30:18 +00002976 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002977 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002978 }
drh308c2a52010-05-14 11:30:18 +00002979 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002980 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2981 if( !rc ){
2982 context->reserved = 0;
2983 }
aswiftaebf4132008-11-21 00:10:35 +00002984 }
drh8af6c222010-05-14 12:43:01 +00002985 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2986 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002987 }
aswiftaebf4132008-11-21 00:10:35 +00002988 }
drh308c2a52010-05-14 11:30:18 +00002989 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002990
drh7ed97b92010-01-20 13:07:21 +00002991 /* Decrement the shared lock counter. Release the lock using an
2992 ** OS call only when all threads in this same process have released
2993 ** the lock.
2994 */
drh8af6c222010-05-14 12:43:01 +00002995 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2996 pInode->nShared--;
2997 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002998 SimulateIOErrorBenign(1);
2999 SimulateIOError( h=(-1) )
3000 SimulateIOErrorBenign(0);
3001 if( !skipShared ){
3002 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3003 }
3004 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003005 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003006 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003007 }
3008 }
3009 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003010 pInode->nLock--;
3011 assert( pInode->nLock>=0 );
3012 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003013 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003014 }
3015 }
drhbfe66312006-10-03 17:40:40 +00003016 }
drh7ed97b92010-01-20 13:07:21 +00003017
drh6c7d5c52008-11-21 20:32:33 +00003018 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003019 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003020 return rc;
3021}
3022
3023/*
drh339eb0b2008-03-07 15:34:11 +00003024** Close a file & cleanup AFP specific locking context
3025*/
danielk1977e339d652008-06-28 11:23:00 +00003026static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003027 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003028 if( id ){
3029 unixFile *pFile = (unixFile*)id;
3030 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003031 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003032 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003033 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003034 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003035 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003036 ** the last lock is cleared.
3037 */
dan08da86a2009-08-21 17:18:03 +00003038 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003039 }
danb0ac3e32010-06-16 10:55:42 +00003040 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003041 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003042 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003043 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003044 }
drh7ed97b92010-01-20 13:07:21 +00003045 return rc;
drhbfe66312006-10-03 17:40:40 +00003046}
3047
drhd2cb50b2009-01-09 21:41:17 +00003048#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003049/*
3050** The code above is the AFP lock implementation. The code is specific
3051** to MacOSX and does not work on other unix platforms. No alternative
3052** is available. If you don't compile for a mac, then the "unix-afp"
3053** VFS is not available.
3054**
3055********************* End of the AFP lock implementation **********************
3056******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003057
drh7ed97b92010-01-20 13:07:21 +00003058/******************************************************************************
3059*************************** Begin NFS Locking ********************************/
3060
3061#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3062/*
drh308c2a52010-05-14 11:30:18 +00003063 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003064 ** must be either NO_LOCK or SHARED_LOCK.
3065 **
3066 ** If the locking level of the file descriptor is already at or below
3067 ** the requested locking level, this routine is a no-op.
3068 */
drh308c2a52010-05-14 11:30:18 +00003069static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003070 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003071}
3072
3073#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3074/*
3075** The code above is the NFS lock implementation. The code is specific
3076** to MacOSX and does not work on other unix platforms. No alternative
3077** is available.
3078**
3079********************* End of the NFS lock implementation **********************
3080******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003081
3082/******************************************************************************
3083**************** Non-locking sqlite3_file methods *****************************
3084**
3085** The next division contains implementations for all methods of the
3086** sqlite3_file object other than the locking methods. The locking
3087** methods were defined in divisions above (one locking method per
3088** division). Those methods that are common to all locking modes
3089** are gather together into this division.
3090*/
drhbfe66312006-10-03 17:40:40 +00003091
3092/*
drh734c9862008-11-28 15:37:20 +00003093** Seek to the offset passed as the second argument, then read cnt
3094** bytes into pBuf. Return the number of bytes actually read.
3095**
3096** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3097** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3098** one system to another. Since SQLite does not define USE_PREAD
3099** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3100** See tickets #2741 and #2681.
3101**
3102** To avoid stomping the errno value on a failed read the lastErrno value
3103** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003104*/
drh734c9862008-11-28 15:37:20 +00003105static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3106 int got;
drh58024642011-11-07 18:16:00 +00003107 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003108#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003109 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003110#endif
drh734c9862008-11-28 15:37:20 +00003111 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003112 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003113 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003114 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003115 do{
drh734c9862008-11-28 15:37:20 +00003116#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003117 got = osPread(id->h, pBuf, cnt, offset);
3118 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003119#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003120 got = osPread64(id->h, pBuf, cnt, offset);
3121 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003122#else
drh58024642011-11-07 18:16:00 +00003123 newOffset = lseek(id->h, offset, SEEK_SET);
3124 SimulateIOError( newOffset-- );
3125 if( newOffset!=offset ){
3126 if( newOffset == -1 ){
3127 ((unixFile*)id)->lastErrno = errno;
3128 }else{
drhf2f105d2012-08-20 15:53:54 +00003129 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003130 }
3131 return -1;
drh734c9862008-11-28 15:37:20 +00003132 }
drh58024642011-11-07 18:16:00 +00003133 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003134#endif
drh58024642011-11-07 18:16:00 +00003135 if( got==cnt ) break;
3136 if( got<0 ){
3137 if( errno==EINTR ){ got = 1; continue; }
3138 prior = 0;
3139 ((unixFile*)id)->lastErrno = errno;
3140 break;
3141 }else if( got>0 ){
3142 cnt -= got;
3143 offset += got;
3144 prior += got;
3145 pBuf = (void*)(got + (char*)pBuf);
3146 }
3147 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003148 TIMER_END;
drh58024642011-11-07 18:16:00 +00003149 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3150 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3151 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003152}
3153
3154/*
drh734c9862008-11-28 15:37:20 +00003155** Read data from a file into a buffer. Return SQLITE_OK if all
3156** bytes were read successfully and SQLITE_IOERR if anything goes
3157** wrong.
drh339eb0b2008-03-07 15:34:11 +00003158*/
drh734c9862008-11-28 15:37:20 +00003159static int unixRead(
3160 sqlite3_file *id,
3161 void *pBuf,
3162 int amt,
3163 sqlite3_int64 offset
3164){
dan08da86a2009-08-21 17:18:03 +00003165 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003166 int got;
3167 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003168 assert( offset>=0 );
3169 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003170
dan08da86a2009-08-21 17:18:03 +00003171 /* If this is a database file (not a journal, master-journal or temp
3172 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003173#if 0
dane946c392009-08-22 11:39:46 +00003174 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003175 || offset>=PENDING_BYTE+512
3176 || offset+amt<=PENDING_BYTE
3177 );
dan7c246102010-04-12 19:00:29 +00003178#endif
drh08c6d442009-02-09 17:34:07 +00003179
drh9b4c59f2013-04-15 17:03:42 +00003180#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003181 /* Deal with as much of this read request as possible by transfering
3182 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003183 if( offset<pFile->mmapSize ){
3184 if( offset+amt <= pFile->mmapSize ){
3185 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3186 return SQLITE_OK;
3187 }else{
3188 int nCopy = pFile->mmapSize - offset;
3189 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3190 pBuf = &((u8 *)pBuf)[nCopy];
3191 amt -= nCopy;
3192 offset += nCopy;
3193 }
3194 }
drh6e0b6d52013-04-09 16:19:20 +00003195#endif
danf23da962013-03-23 21:00:41 +00003196
dan08da86a2009-08-21 17:18:03 +00003197 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003198 if( got==amt ){
3199 return SQLITE_OK;
3200 }else if( got<0 ){
3201 /* lastErrno set by seekAndRead */
3202 return SQLITE_IOERR_READ;
3203 }else{
dan08da86a2009-08-21 17:18:03 +00003204 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003205 /* Unread parts of the buffer must be zero-filled */
3206 memset(&((char*)pBuf)[got], 0, amt-got);
3207 return SQLITE_IOERR_SHORT_READ;
3208 }
3209}
3210
3211/*
dan47a2b4a2013-04-26 16:09:29 +00003212** Attempt to seek the file-descriptor passed as the first argument to
3213** absolute offset iOff, then attempt to write nBuf bytes of data from
3214** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3215** return the actual number of bytes written (which may be less than
3216** nBuf).
3217*/
3218static int seekAndWriteFd(
3219 int fd, /* File descriptor to write to */
3220 i64 iOff, /* File offset to begin writing at */
3221 const void *pBuf, /* Copy data from this buffer to the file */
3222 int nBuf, /* Size of buffer pBuf in bytes */
3223 int *piErrno /* OUT: Error number if error occurs */
3224){
3225 int rc = 0; /* Value returned by system call */
3226
3227 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003228 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003229 nBuf &= 0x1ffff;
3230 TIMER_START;
3231
3232#if defined(USE_PREAD)
3233 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3234#elif defined(USE_PREAD64)
3235 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3236#else
3237 do{
3238 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3239 SimulateIOError( iSeek-- );
3240
3241 if( iSeek!=iOff ){
3242 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3243 return -1;
3244 }
3245 rc = osWrite(fd, pBuf, nBuf);
3246 }while( rc<0 && errno==EINTR );
3247#endif
3248
3249 TIMER_END;
3250 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3251
3252 if( rc<0 && piErrno ) *piErrno = errno;
3253 return rc;
3254}
3255
3256
3257/*
drh734c9862008-11-28 15:37:20 +00003258** Seek to the offset in id->offset then read cnt bytes into pBuf.
3259** Return the number of bytes actually read. Update the offset.
3260**
3261** To avoid stomping the errno value on a failed write the lastErrno value
3262** is set before returning.
3263*/
3264static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003265 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003266}
3267
3268
3269/*
3270** Write data from a buffer into a file. Return SQLITE_OK on success
3271** or some other error code on failure.
3272*/
3273static int unixWrite(
3274 sqlite3_file *id,
3275 const void *pBuf,
3276 int amt,
3277 sqlite3_int64 offset
3278){
dan08da86a2009-08-21 17:18:03 +00003279 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003280 int wrote = 0;
3281 assert( id );
3282 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003283
dan08da86a2009-08-21 17:18:03 +00003284 /* If this is a database file (not a journal, master-journal or temp
3285 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003286#if 0
dane946c392009-08-22 11:39:46 +00003287 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003288 || offset>=PENDING_BYTE+512
3289 || offset+amt<=PENDING_BYTE
3290 );
dan7c246102010-04-12 19:00:29 +00003291#endif
drh08c6d442009-02-09 17:34:07 +00003292
drhd3d8c042012-05-29 17:02:40 +00003293#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003294 /* If we are doing a normal write to a database file (as opposed to
3295 ** doing a hot-journal rollback or a write to some file other than a
3296 ** normal database file) then record the fact that the database
3297 ** has changed. If the transaction counter is modified, record that
3298 ** fact too.
3299 */
dan08da86a2009-08-21 17:18:03 +00003300 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003301 pFile->dbUpdate = 1; /* The database has been modified */
3302 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003303 int rc;
drh8f941bc2009-01-14 23:03:40 +00003304 char oldCntr[4];
3305 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003306 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003307 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003308 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003309 pFile->transCntrChng = 1; /* The transaction counter has changed */
3310 }
3311 }
3312 }
3313#endif
3314
drh9b4c59f2013-04-15 17:03:42 +00003315#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003316 /* Deal with as much of this write request as possible by transfering
3317 ** data from the memory mapping using memcpy(). */
3318 if( offset<pFile->mmapSize ){
3319 if( offset+amt <= pFile->mmapSize ){
3320 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3321 return SQLITE_OK;
3322 }else{
3323 int nCopy = pFile->mmapSize - offset;
3324 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3325 pBuf = &((u8 *)pBuf)[nCopy];
3326 amt -= nCopy;
3327 offset += nCopy;
3328 }
3329 }
drh6e0b6d52013-04-09 16:19:20 +00003330#endif
danf23da962013-03-23 21:00:41 +00003331
dan08da86a2009-08-21 17:18:03 +00003332 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003333 amt -= wrote;
3334 offset += wrote;
3335 pBuf = &((char*)pBuf)[wrote];
3336 }
3337 SimulateIOError(( wrote=(-1), amt=1 ));
3338 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003339
drh734c9862008-11-28 15:37:20 +00003340 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003341 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003342 /* lastErrno set by seekAndWrite */
3343 return SQLITE_IOERR_WRITE;
3344 }else{
dan08da86a2009-08-21 17:18:03 +00003345 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003346 return SQLITE_FULL;
3347 }
3348 }
dan6e09d692010-07-27 18:34:15 +00003349
drh734c9862008-11-28 15:37:20 +00003350 return SQLITE_OK;
3351}
3352
3353#ifdef SQLITE_TEST
3354/*
3355** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003356** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003357*/
3358int sqlite3_sync_count = 0;
3359int sqlite3_fullsync_count = 0;
3360#endif
3361
3362/*
drh89240432009-03-25 01:06:01 +00003363** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003364** Others do no. To be safe, we will stick with the (slightly slower)
3365** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003366** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003367*/
drh20f8e132011-08-31 21:01:55 +00003368#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003369# define fdatasync fsync
3370#endif
3371
3372/*
3373** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3374** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3375** only available on Mac OS X. But that could change.
3376*/
3377#ifdef F_FULLFSYNC
3378# define HAVE_FULLFSYNC 1
3379#else
3380# define HAVE_FULLFSYNC 0
3381#endif
3382
3383
3384/*
3385** The fsync() system call does not work as advertised on many
3386** unix systems. The following procedure is an attempt to make
3387** it work better.
3388**
3389** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3390** for testing when we want to run through the test suite quickly.
3391** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3392** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3393** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003394**
3395** SQLite sets the dataOnly flag if the size of the file is unchanged.
3396** The idea behind dataOnly is that it should only write the file content
3397** to disk, not the inode. We only set dataOnly if the file size is
3398** unchanged since the file size is part of the inode. However,
3399** Ted Ts'o tells us that fdatasync() will also write the inode if the
3400** file size has changed. The only real difference between fdatasync()
3401** and fsync(), Ted tells us, is that fdatasync() will not flush the
3402** inode if the mtime or owner or other inode attributes have changed.
3403** We only care about the file size, not the other file attributes, so
3404** as far as SQLite is concerned, an fdatasync() is always adequate.
3405** So, we always use fdatasync() if it is available, regardless of
3406** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003407*/
3408static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003409 int rc;
drh734c9862008-11-28 15:37:20 +00003410
3411 /* The following "ifdef/elif/else/" block has the same structure as
3412 ** the one below. It is replicated here solely to avoid cluttering
3413 ** up the real code with the UNUSED_PARAMETER() macros.
3414 */
3415#ifdef SQLITE_NO_SYNC
3416 UNUSED_PARAMETER(fd);
3417 UNUSED_PARAMETER(fullSync);
3418 UNUSED_PARAMETER(dataOnly);
3419#elif HAVE_FULLFSYNC
3420 UNUSED_PARAMETER(dataOnly);
3421#else
3422 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003423 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003424#endif
3425
3426 /* Record the number of times that we do a normal fsync() and
3427 ** FULLSYNC. This is used during testing to verify that this procedure
3428 ** gets called with the correct arguments.
3429 */
3430#ifdef SQLITE_TEST
3431 if( fullSync ) sqlite3_fullsync_count++;
3432 sqlite3_sync_count++;
3433#endif
3434
3435 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3436 ** no-op
3437 */
3438#ifdef SQLITE_NO_SYNC
3439 rc = SQLITE_OK;
3440#elif HAVE_FULLFSYNC
3441 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003442 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003443 }else{
3444 rc = 1;
3445 }
3446 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003447 ** It shouldn't be possible for fullfsync to fail on the local
3448 ** file system (on OSX), so failure indicates that FULLFSYNC
3449 ** isn't supported for this file system. So, attempt an fsync
3450 ** and (for now) ignore the overhead of a superfluous fcntl call.
3451 ** It'd be better to detect fullfsync support once and avoid
3452 ** the fcntl call every time sync is called.
3453 */
drh734c9862008-11-28 15:37:20 +00003454 if( rc ) rc = fsync(fd);
3455
drh7ed97b92010-01-20 13:07:21 +00003456#elif defined(__APPLE__)
3457 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3458 ** so currently we default to the macro that redefines fdatasync to fsync
3459 */
3460 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003461#else
drh0b647ff2009-03-21 14:41:04 +00003462 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003463#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003464 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003465 rc = fsync(fd);
3466 }
drh0b647ff2009-03-21 14:41:04 +00003467#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003468#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3469
3470 if( OS_VXWORKS && rc!= -1 ){
3471 rc = 0;
3472 }
chw97185482008-11-17 08:05:31 +00003473 return rc;
drhbfe66312006-10-03 17:40:40 +00003474}
3475
drh734c9862008-11-28 15:37:20 +00003476/*
drh0059eae2011-08-08 23:48:40 +00003477** Open a file descriptor to the directory containing file zFilename.
3478** If successful, *pFd is set to the opened file descriptor and
3479** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3480** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3481** value.
3482**
drh90315a22011-08-10 01:52:12 +00003483** The directory file descriptor is used for only one thing - to
3484** fsync() a directory to make sure file creation and deletion events
3485** are flushed to disk. Such fsyncs are not needed on newer
3486** journaling filesystems, but are required on older filesystems.
3487**
3488** This routine can be overridden using the xSetSysCall interface.
3489** The ability to override this routine was added in support of the
3490** chromium sandbox. Opening a directory is a security risk (we are
3491** told) so making it overrideable allows the chromium sandbox to
3492** replace this routine with a harmless no-op. To make this routine
3493** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3494** *pFd set to a negative number.
3495**
drh0059eae2011-08-08 23:48:40 +00003496** If SQLITE_OK is returned, the caller is responsible for closing
3497** the file descriptor *pFd using close().
3498*/
3499static int openDirectory(const char *zFilename, int *pFd){
3500 int ii;
3501 int fd = -1;
3502 char zDirname[MAX_PATHNAME+1];
3503
3504 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3505 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3506 if( ii>0 ){
3507 zDirname[ii] = '\0';
3508 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3509 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003510 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3511 }
3512 }
3513 *pFd = fd;
3514 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3515}
3516
3517/*
drh734c9862008-11-28 15:37:20 +00003518** Make sure all writes to a particular file are committed to disk.
3519**
3520** If dataOnly==0 then both the file itself and its metadata (file
3521** size, access time, etc) are synced. If dataOnly!=0 then only the
3522** file data is synced.
3523**
3524** Under Unix, also make sure that the directory entry for the file
3525** has been created by fsync-ing the directory that contains the file.
3526** If we do not do this and we encounter a power failure, the directory
3527** entry for the journal might not exist after we reboot. The next
3528** SQLite to access the file will not know that the journal exists (because
3529** the directory entry for the journal was never created) and the transaction
3530** will not roll back - possibly leading to database corruption.
3531*/
3532static int unixSync(sqlite3_file *id, int flags){
3533 int rc;
3534 unixFile *pFile = (unixFile*)id;
3535
3536 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3537 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3538
3539 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3540 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3541 || (flags&0x0F)==SQLITE_SYNC_FULL
3542 );
3543
3544 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3545 ** line is to test that doing so does not cause any problems.
3546 */
3547 SimulateDiskfullError( return SQLITE_FULL );
3548
3549 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003550 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003551 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3552 SimulateIOError( rc=1 );
3553 if( rc ){
3554 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003555 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003556 }
drh0059eae2011-08-08 23:48:40 +00003557
3558 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003559 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003560 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003561 */
3562 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3563 int dirfd;
3564 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003565 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003566 rc = osOpenDirectory(pFile->zPath, &dirfd);
3567 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003568 full_fsync(dirfd, 0, 0);
3569 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003570 }else if( rc==SQLITE_CANTOPEN ){
3571 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003572 }
drh0059eae2011-08-08 23:48:40 +00003573 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003574 }
3575 return rc;
3576}
3577
3578/*
3579** Truncate an open file to a specified size
3580*/
3581static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003582 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003583 int rc;
dan6e09d692010-07-27 18:34:15 +00003584 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003585 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003586
3587 /* If the user has configured a chunk-size for this file, truncate the
3588 ** file so that it consists of an integer number of chunks (i.e. the
3589 ** actual file size after the operation may be larger than the requested
3590 ** size).
3591 */
drhb8af4b72012-04-05 20:04:39 +00003592 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003593 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3594 }
3595
drhff812312011-02-23 13:33:46 +00003596 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003597 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003598 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003599 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003600 }else{
drhd3d8c042012-05-29 17:02:40 +00003601#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003602 /* If we are doing a normal write to a database file (as opposed to
3603 ** doing a hot-journal rollback or a write to some file other than a
3604 ** normal database file) and we truncate the file to zero length,
3605 ** that effectively updates the change counter. This might happen
3606 ** when restoring a database using the backup API from a zero-length
3607 ** source.
3608 */
dan6e09d692010-07-27 18:34:15 +00003609 if( pFile->inNormalWrite && nByte==0 ){
3610 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003611 }
danf23da962013-03-23 21:00:41 +00003612#endif
danc0003312013-03-22 17:46:11 +00003613
mistachkine98844f2013-08-24 00:59:24 +00003614#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003615 /* If the file was just truncated to a size smaller than the currently
3616 ** mapped region, reduce the effective mapping size as well. SQLite will
3617 ** use read() and write() to access data beyond this point from now on.
3618 */
3619 if( nByte<pFile->mmapSize ){
3620 pFile->mmapSize = nByte;
3621 }
mistachkine98844f2013-08-24 00:59:24 +00003622#endif
drh3313b142009-11-06 04:13:18 +00003623
drh734c9862008-11-28 15:37:20 +00003624 return SQLITE_OK;
3625 }
3626}
3627
3628/*
3629** Determine the current size of a file in bytes
3630*/
3631static int unixFileSize(sqlite3_file *id, i64 *pSize){
3632 int rc;
3633 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003634 assert( id );
3635 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003636 SimulateIOError( rc=1 );
3637 if( rc!=0 ){
drh3044b512014-06-16 16:41:52 +00003638 ((unixFile*)id)->lastErrno = errno;
drh734c9862008-11-28 15:37:20 +00003639 return SQLITE_IOERR_FSTAT;
3640 }
3641 *pSize = buf.st_size;
3642
drh8af6c222010-05-14 12:43:01 +00003643 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003644 ** writes a single byte into that file in order to work around a bug
3645 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3646 ** layers, we need to report this file size as zero even though it is
3647 ** really 1. Ticket #3260.
3648 */
3649 if( *pSize==1 ) *pSize = 0;
3650
3651
3652 return SQLITE_OK;
3653}
3654
drhd2cb50b2009-01-09 21:41:17 +00003655#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003656/*
3657** Handler for proxy-locking file-control verbs. Defined below in the
3658** proxying locking division.
3659*/
3660static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003661#endif
drh715ff302008-12-03 22:32:44 +00003662
dan502019c2010-07-28 14:26:17 +00003663/*
3664** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003665** file-control operation. Enlarge the database to nBytes in size
3666** (rounded up to the next chunk-size). If the database is already
3667** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003668*/
3669static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003670 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003671 i64 nSize; /* Required file size */
3672 struct stat buf; /* Used to hold return values of fstat() */
3673
drh99ab3b12011-03-02 15:09:07 +00003674 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003675
3676 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3677 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003678
dan502019c2010-07-28 14:26:17 +00003679#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003680 /* The code below is handling the return value of osFallocate()
3681 ** correctly. posix_fallocate() is defined to "returns zero on success,
3682 ** or an error number on failure". See the manpage for details. */
3683 int err;
drhff812312011-02-23 13:33:46 +00003684 do{
dan661d71a2011-03-30 19:08:03 +00003685 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3686 }while( err==EINTR );
3687 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003688#else
3689 /* If the OS does not have posix_fallocate(), fake it. First use
3690 ** ftruncate() to set the file size, then write a single byte to
3691 ** the last byte in each block within the extended region. This
3692 ** is the same technique used by glibc to implement posix_fallocate()
3693 ** on systems that do not have a real fallocate() system call.
3694 */
3695 int nBlk = buf.st_blksize; /* File-system block size */
3696 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003697
drhff812312011-02-23 13:33:46 +00003698 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003699 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003700 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003701 }
3702 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003703 while( iWrite<nSize ){
3704 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3705 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003706 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003707 }
dan502019c2010-07-28 14:26:17 +00003708#endif
3709 }
3710 }
3711
mistachkine98844f2013-08-24 00:59:24 +00003712#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003713 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003714 int rc;
3715 if( pFile->szChunk<=0 ){
3716 if( robust_ftruncate(pFile->h, nByte) ){
3717 pFile->lastErrno = errno;
3718 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3719 }
3720 }
3721
3722 rc = unixMapfile(pFile, nByte);
3723 return rc;
3724 }
mistachkine98844f2013-08-24 00:59:24 +00003725#endif
danf23da962013-03-23 21:00:41 +00003726
dan502019c2010-07-28 14:26:17 +00003727 return SQLITE_OK;
3728}
danielk1977ad94b582007-08-20 06:44:22 +00003729
danielk1977e3026632004-06-22 11:29:02 +00003730/*
drhf12b3f62011-12-21 14:42:29 +00003731** If *pArg is inititially negative then this is a query. Set *pArg to
3732** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3733**
3734** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3735*/
3736static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3737 if( *pArg<0 ){
3738 *pArg = (pFile->ctrlFlags & mask)!=0;
3739 }else if( (*pArg)==0 ){
3740 pFile->ctrlFlags &= ~mask;
3741 }else{
3742 pFile->ctrlFlags |= mask;
3743 }
3744}
3745
drh696b33e2012-12-06 19:01:42 +00003746/* Forward declaration */
3747static int unixGetTempname(int nBuf, char *zBuf);
3748
drhf12b3f62011-12-21 14:42:29 +00003749/*
drh9e33c2c2007-08-31 18:34:59 +00003750** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003751*/
drhcc6bb3e2007-08-31 16:11:35 +00003752static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003753 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003754 switch( op ){
3755 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003756 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003757 return SQLITE_OK;
3758 }
drh7708e972008-11-29 00:56:52 +00003759 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003760 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003761 return SQLITE_OK;
3762 }
dan6e09d692010-07-27 18:34:15 +00003763 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003764 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003765 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003766 }
drh9ff27ec2010-05-19 19:26:05 +00003767 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003768 int rc;
3769 SimulateIOErrorBenign(1);
3770 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3771 SimulateIOErrorBenign(0);
3772 return rc;
drhf0b190d2011-07-26 16:03:07 +00003773 }
3774 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003775 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3776 return SQLITE_OK;
3777 }
drhcb15f352011-12-23 01:04:17 +00003778 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3779 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003780 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003781 }
drhde60fc22011-12-14 17:53:36 +00003782 case SQLITE_FCNTL_VFSNAME: {
3783 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3784 return SQLITE_OK;
3785 }
drh696b33e2012-12-06 19:01:42 +00003786 case SQLITE_FCNTL_TEMPFILENAME: {
3787 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3788 if( zTFile ){
3789 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3790 *(char**)pArg = zTFile;
3791 }
3792 return SQLITE_OK;
3793 }
drhb959a012013-12-07 12:29:22 +00003794 case SQLITE_FCNTL_HAS_MOVED: {
3795 *(int*)pArg = fileHasMoved(pFile);
3796 return SQLITE_OK;
3797 }
mistachkine98844f2013-08-24 00:59:24 +00003798#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003799 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003800 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003801 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003802 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3803 newLimit = sqlite3GlobalConfig.mxMmap;
3804 }
3805 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003806 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003807 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003808 if( pFile->mmapSize>0 ){
3809 unixUnmapfile(pFile);
3810 rc = unixMapfile(pFile, -1);
3811 }
danbcb8a862013-04-08 15:30:41 +00003812 }
drh34e258c2013-05-23 01:40:53 +00003813 return rc;
danb2d3de32013-03-14 18:34:37 +00003814 }
mistachkine98844f2013-08-24 00:59:24 +00003815#endif
drhd3d8c042012-05-29 17:02:40 +00003816#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003817 /* The pager calls this method to signal that it has done
3818 ** a rollback and that the database is therefore unchanged and
3819 ** it hence it is OK for the transaction change counter to be
3820 ** unchanged.
3821 */
3822 case SQLITE_FCNTL_DB_UNCHANGED: {
3823 ((unixFile*)id)->dbUpdate = 0;
3824 return SQLITE_OK;
3825 }
3826#endif
drhd2cb50b2009-01-09 21:41:17 +00003827#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003828 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003829 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003830 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003831 }
drhd2cb50b2009-01-09 21:41:17 +00003832#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003833 }
drh0b52b7d2011-01-26 19:46:22 +00003834 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003835}
3836
3837/*
danielk1977a3d4c882007-03-23 10:08:38 +00003838** Return the sector size in bytes of the underlying block device for
3839** the specified file. This is almost always 512 bytes, but may be
3840** larger for some devices.
3841**
3842** SQLite code assumes this function cannot fail. It also assumes that
3843** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003844** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003845** same for both.
3846*/
drh537dddf2012-10-26 13:46:24 +00003847#ifndef __QNXNTO__
3848static int unixSectorSize(sqlite3_file *NotUsed){
3849 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003850 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003851}
drh537dddf2012-10-26 13:46:24 +00003852#endif
3853
3854/*
3855** The following version of unixSectorSize() is optimized for QNX.
3856*/
3857#ifdef __QNXNTO__
3858#include <sys/dcmd_blk.h>
3859#include <sys/statvfs.h>
3860static int unixSectorSize(sqlite3_file *id){
3861 unixFile *pFile = (unixFile*)id;
3862 if( pFile->sectorSize == 0 ){
3863 struct statvfs fsInfo;
3864
3865 /* Set defaults for non-supported filesystems */
3866 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3867 pFile->deviceCharacteristics = 0;
3868 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3869 return pFile->sectorSize;
3870 }
3871
3872 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3873 pFile->sectorSize = fsInfo.f_bsize;
3874 pFile->deviceCharacteristics =
3875 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3876 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3877 ** the write succeeds */
3878 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3879 ** so it is ordered */
3880 0;
3881 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3882 pFile->sectorSize = fsInfo.f_bsize;
3883 pFile->deviceCharacteristics =
3884 /* etfs cluster size writes are atomic */
3885 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3886 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3887 ** the write succeeds */
3888 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3889 ** so it is ordered */
3890 0;
3891 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3892 pFile->sectorSize = fsInfo.f_bsize;
3893 pFile->deviceCharacteristics =
3894 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3895 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3896 ** the write succeeds */
3897 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3898 ** so it is ordered */
3899 0;
3900 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3901 pFile->sectorSize = fsInfo.f_bsize;
3902 pFile->deviceCharacteristics =
3903 /* full bitset of atomics from max sector size and smaller */
3904 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3905 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3906 ** so it is ordered */
3907 0;
3908 }else if( strstr(fsInfo.f_basetype, "dos") ){
3909 pFile->sectorSize = fsInfo.f_bsize;
3910 pFile->deviceCharacteristics =
3911 /* full bitset of atomics from max sector size and smaller */
3912 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3913 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3914 ** so it is ordered */
3915 0;
3916 }else{
3917 pFile->deviceCharacteristics =
3918 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3919 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3920 ** the write succeeds */
3921 0;
3922 }
3923 }
3924 /* Last chance verification. If the sector size isn't a multiple of 512
3925 ** then it isn't valid.*/
3926 if( pFile->sectorSize % 512 != 0 ){
3927 pFile->deviceCharacteristics = 0;
3928 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3929 }
3930 return pFile->sectorSize;
3931}
3932#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003933
danielk197790949c22007-08-17 16:50:38 +00003934/*
drhf12b3f62011-12-21 14:42:29 +00003935** Return the device characteristics for the file.
3936**
drhcb15f352011-12-23 01:04:17 +00003937** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3938** However, that choice is contraversial since technically the underlying
3939** file system does not always provide powersafe overwrites. (In other
3940** words, after a power-loss event, parts of the file that were never
3941** written might end up being altered.) However, non-PSOW behavior is very,
3942** very rare. And asserting PSOW makes a large reduction in the amount
3943** of required I/O for journaling, since a lot of padding is eliminated.
3944** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3945** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003946*/
drhf12b3f62011-12-21 14:42:29 +00003947static int unixDeviceCharacteristics(sqlite3_file *id){
3948 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003949 int rc = 0;
3950#ifdef __QNXNTO__
3951 if( p->sectorSize==0 ) unixSectorSize(id);
3952 rc = p->deviceCharacteristics;
3953#endif
drhcb15f352011-12-23 01:04:17 +00003954 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003955 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003956 }
drh537dddf2012-10-26 13:46:24 +00003957 return rc;
danielk197762079062007-08-15 17:08:46 +00003958}
3959
drhd9e5c4f2010-05-12 18:01:39 +00003960#ifndef SQLITE_OMIT_WAL
3961
3962
3963/*
drhd91c68f2010-05-14 14:52:25 +00003964** Object used to represent an shared memory buffer.
3965**
3966** When multiple threads all reference the same wal-index, each thread
3967** has its own unixShm object, but they all point to a single instance
3968** of this unixShmNode object. In other words, each wal-index is opened
3969** only once per process.
3970**
3971** Each unixShmNode object is connected to a single unixInodeInfo object.
3972** We could coalesce this object into unixInodeInfo, but that would mean
3973** every open file that does not use shared memory (in other words, most
3974** open files) would have to carry around this extra information. So
3975** the unixInodeInfo object contains a pointer to this unixShmNode object
3976** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003977**
3978** unixMutexHeld() must be true when creating or destroying
3979** this object or while reading or writing the following fields:
3980**
3981** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003982**
3983** The following fields are read-only after the object is created:
3984**
3985** fid
3986** zFilename
3987**
drhd91c68f2010-05-14 14:52:25 +00003988** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003989** unixMutexHeld() is true when reading or writing any other field
3990** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003991*/
drhd91c68f2010-05-14 14:52:25 +00003992struct unixShmNode {
3993 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003994 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003995 char *zFilename; /* Name of the mmapped file */
3996 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003997 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003998 u16 nRegion; /* Size of array apRegion */
3999 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004000 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004001 int nRef; /* Number of unixShm objects pointing to this */
4002 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004003#ifdef SQLITE_DEBUG
4004 u8 exclMask; /* Mask of exclusive locks held */
4005 u8 sharedMask; /* Mask of shared locks held */
4006 u8 nextShmId; /* Next available unixShm.id value */
4007#endif
4008};
4009
4010/*
drhd9e5c4f2010-05-12 18:01:39 +00004011** Structure used internally by this VFS to record the state of an
4012** open shared memory connection.
4013**
drhd91c68f2010-05-14 14:52:25 +00004014** The following fields are initialized when this object is created and
4015** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004016**
drhd91c68f2010-05-14 14:52:25 +00004017** unixShm.pFile
4018** unixShm.id
4019**
4020** All other fields are read/write. The unixShm.pFile->mutex must be held
4021** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004022*/
4023struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004024 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4025 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004026 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004027 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004028 u16 sharedMask; /* Mask of shared locks held */
4029 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004030};
4031
4032/*
drhd9e5c4f2010-05-12 18:01:39 +00004033** Constants used for locking
4034*/
drhbd9676c2010-06-23 17:58:38 +00004035#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004036#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004037
drhd9e5c4f2010-05-12 18:01:39 +00004038/*
drh73b64e42010-05-30 19:55:15 +00004039** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004040**
4041** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4042** otherwise.
4043*/
4044static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004045 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4046 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004047 int ofst, /* First byte of the locking range */
4048 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004049){
4050 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004051 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004052
drhd91c68f2010-05-14 14:52:25 +00004053 /* Access to the unixShmNode object is serialized by the caller */
4054 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004055
drh73b64e42010-05-30 19:55:15 +00004056 /* Shared locks never span more than one byte */
4057 assert( n==1 || lockType!=F_RDLCK );
4058
4059 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004060 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004061
drh3cb93392011-03-12 18:10:44 +00004062 if( pShmNode->h>=0 ){
4063 /* Initialize the locking parameters */
4064 memset(&f, 0, sizeof(f));
4065 f.l_type = lockType;
4066 f.l_whence = SEEK_SET;
4067 f.l_start = ofst;
4068 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004069
drh3cb93392011-03-12 18:10:44 +00004070 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4071 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4072 }
drhd9e5c4f2010-05-12 18:01:39 +00004073
4074 /* Update the global lock state and do debug tracing */
4075#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004076 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004077 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004078 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004079 if( rc==SQLITE_OK ){
4080 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004081 OSTRACE(("unlock %d ok", ofst));
4082 pShmNode->exclMask &= ~mask;
4083 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004084 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004085 OSTRACE(("read-lock %d ok", ofst));
4086 pShmNode->exclMask &= ~mask;
4087 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004088 }else{
4089 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004090 OSTRACE(("write-lock %d ok", ofst));
4091 pShmNode->exclMask |= mask;
4092 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004093 }
4094 }else{
4095 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004096 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004097 }else if( lockType==F_RDLCK ){
4098 OSTRACE(("read-lock failed"));
4099 }else{
4100 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004101 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004102 }
4103 }
drh20e1f082010-05-31 16:10:12 +00004104 OSTRACE((" - afterwards %03x,%03x\n",
4105 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004106 }
drhd9e5c4f2010-05-12 18:01:39 +00004107#endif
4108
4109 return rc;
4110}
4111
dan781e34c2014-03-20 08:59:47 +00004112/*
4113** Return the system page size.
danbc760632014-03-20 09:42:09 +00004114**
4115** This function should not be called directly by other code in this file.
4116** Instead, it should be called via macro osGetpagesize().
dan781e34c2014-03-20 08:59:47 +00004117*/
danbc760632014-03-20 09:42:09 +00004118static int unixGetpagesize(void){
dan781e34c2014-03-20 08:59:47 +00004119#if defined(_BSD_SOURCE)
4120 return getpagesize();
4121#else
4122 return (int)sysconf(_SC_PAGESIZE);
4123#endif
4124}
4125
4126/*
4127** Return the minimum number of 32KB shm regions that should be mapped at
4128** a time, assuming that each mapping must be an integer multiple of the
4129** current system page-size.
4130**
4131** Usually, this is 1. The exception seems to be systems that are configured
4132** to use 64KB pages - in this case each mapping must cover at least two
4133** shm regions.
4134*/
4135static int unixShmRegionPerMap(void){
4136 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004137 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004138 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4139 if( pgsz<shmsz ) return 1;
4140 return pgsz/shmsz;
4141}
drhd9e5c4f2010-05-12 18:01:39 +00004142
4143/*
drhd91c68f2010-05-14 14:52:25 +00004144** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004145**
4146** This is not a VFS shared-memory method; it is a utility function called
4147** by VFS shared-memory methods.
4148*/
drhd91c68f2010-05-14 14:52:25 +00004149static void unixShmPurge(unixFile *pFd){
4150 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004151 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004152 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004153 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004154 int i;
drhd91c68f2010-05-14 14:52:25 +00004155 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004156 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004157 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004158 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004159 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004160 }else{
4161 sqlite3_free(p->apRegion[i]);
4162 }
dan13a3cb82010-06-11 19:04:21 +00004163 }
dan18801912010-06-14 14:07:50 +00004164 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004165 if( p->h>=0 ){
4166 robust_close(pFd, p->h, __LINE__);
4167 p->h = -1;
4168 }
drhd91c68f2010-05-14 14:52:25 +00004169 p->pInode->pShmNode = 0;
4170 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004171 }
4172}
4173
4174/*
danda9fe0c2010-07-13 18:44:03 +00004175** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004176** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004177**
drh7234c6d2010-06-19 15:10:09 +00004178** The file used to implement shared-memory is in the same directory
4179** as the open database file and has the same name as the open database
4180** file with the "-shm" suffix added. For example, if the database file
4181** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004182** for shared memory will be called "/home/user1/config.db-shm".
4183**
4184** Another approach to is to use files in /dev/shm or /dev/tmp or an
4185** some other tmpfs mount. But if a file in a different directory
4186** from the database file is used, then differing access permissions
4187** or a chroot() might cause two different processes on the same
4188** database to end up using different files for shared memory -
4189** meaning that their memory would not really be shared - resulting
4190** in database corruption. Nevertheless, this tmpfs file usage
4191** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4192** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4193** option results in an incompatible build of SQLite; builds of SQLite
4194** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4195** same database file at the same time, database corruption will likely
4196** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4197** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004198**
4199** When opening a new shared-memory file, if no other instances of that
4200** file are currently open, in this process or in other processes, then
4201** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004202**
4203** If the original database file (pDbFd) is using the "unix-excl" VFS
4204** that means that an exclusive lock is held on the database file and
4205** that no other processes are able to read or write the database. In
4206** that case, we do not really need shared memory. No shared memory
4207** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004208*/
danda9fe0c2010-07-13 18:44:03 +00004209static int unixOpenSharedMemory(unixFile *pDbFd){
4210 struct unixShm *p = 0; /* The connection to be opened */
4211 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4212 int rc; /* Result code */
4213 unixInodeInfo *pInode; /* The inode of fd */
4214 char *zShmFilename; /* Name of the file used for SHM */
4215 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004216
danda9fe0c2010-07-13 18:44:03 +00004217 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004218 p = sqlite3_malloc( sizeof(*p) );
4219 if( p==0 ) return SQLITE_NOMEM;
4220 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004221 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004222
danda9fe0c2010-07-13 18:44:03 +00004223 /* Check to see if a unixShmNode object already exists. Reuse an existing
4224 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004225 */
4226 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004227 pInode = pDbFd->pInode;
4228 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004229 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004230 struct stat sStat; /* fstat() info for database file */
4231
4232 /* Call fstat() to figure out the permissions on the database file. If
4233 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004234 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004235 */
drh3cb93392011-03-12 18:10:44 +00004236 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004237 rc = SQLITE_IOERR_FSTAT;
4238 goto shm_open_err;
4239 }
4240
drha4ced192010-07-15 18:32:40 +00004241#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004242 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004243#else
drh52bcde02012-01-03 14:50:45 +00004244 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004245#endif
drh7234c6d2010-06-19 15:10:09 +00004246 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004247 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004248 rc = SQLITE_NOMEM;
4249 goto shm_open_err;
4250 }
drh9cb5a0d2012-01-05 21:19:54 +00004251 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004252 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004253#ifdef SQLITE_SHM_DIRECTORY
4254 sqlite3_snprintf(nShmFilename, zShmFilename,
4255 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4256 (u32)sStat.st_ino, (u32)sStat.st_dev);
4257#else
drh7234c6d2010-06-19 15:10:09 +00004258 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004259 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004260#endif
drhd91c68f2010-05-14 14:52:25 +00004261 pShmNode->h = -1;
4262 pDbFd->pInode->pShmNode = pShmNode;
4263 pShmNode->pInode = pDbFd->pInode;
4264 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4265 if( pShmNode->mutex==0 ){
4266 rc = SQLITE_NOMEM;
4267 goto shm_open_err;
4268 }
drhd9e5c4f2010-05-12 18:01:39 +00004269
drh3cb93392011-03-12 18:10:44 +00004270 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004271 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004272 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004273 openFlags = O_RDONLY;
4274 pShmNode->isReadonly = 1;
4275 }
4276 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004277 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004278 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4279 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004280 }
drhac7c3ac2012-02-11 19:23:48 +00004281
4282 /* If this process is running as root, make sure that the SHM file
4283 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004284 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004285 */
drhed466822012-05-31 13:10:49 +00004286 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004287
4288 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004289 ** If not, truncate the file to zero length.
4290 */
4291 rc = SQLITE_OK;
4292 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4293 if( robust_ftruncate(pShmNode->h, 0) ){
4294 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004295 }
4296 }
drh66dfec8b2011-06-01 20:01:49 +00004297 if( rc==SQLITE_OK ){
4298 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4299 }
4300 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004301 }
drhd9e5c4f2010-05-12 18:01:39 +00004302 }
4303
drhd91c68f2010-05-14 14:52:25 +00004304 /* Make the new connection a child of the unixShmNode */
4305 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004306#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004307 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004308#endif
drhd91c68f2010-05-14 14:52:25 +00004309 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004310 pDbFd->pShm = p;
4311 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004312
4313 /* The reference count on pShmNode has already been incremented under
4314 ** the cover of the unixEnterMutex() mutex and the pointer from the
4315 ** new (struct unixShm) object to the pShmNode has been set. All that is
4316 ** left to do is to link the new object into the linked list starting
4317 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4318 ** mutex.
4319 */
4320 sqlite3_mutex_enter(pShmNode->mutex);
4321 p->pNext = pShmNode->pFirst;
4322 pShmNode->pFirst = p;
4323 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004324 return SQLITE_OK;
4325
4326 /* Jump here on any error */
4327shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004328 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004329 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004330 unixLeaveMutex();
4331 return rc;
4332}
4333
4334/*
danda9fe0c2010-07-13 18:44:03 +00004335** This function is called to obtain a pointer to region iRegion of the
4336** shared-memory associated with the database file fd. Shared-memory regions
4337** are numbered starting from zero. Each shared-memory region is szRegion
4338** bytes in size.
4339**
4340** If an error occurs, an error code is returned and *pp is set to NULL.
4341**
4342** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4343** region has not been allocated (by any client, including one running in a
4344** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4345** bExtend is non-zero and the requested shared-memory region has not yet
4346** been allocated, it is allocated by this function.
4347**
4348** If the shared-memory region has already been allocated or is allocated by
4349** this call as described above, then it is mapped into this processes
4350** address space (if it is not already), *pp is set to point to the mapped
4351** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004352*/
danda9fe0c2010-07-13 18:44:03 +00004353static int unixShmMap(
4354 sqlite3_file *fd, /* Handle open on database file */
4355 int iRegion, /* Region to retrieve */
4356 int szRegion, /* Size of regions */
4357 int bExtend, /* True to extend file if necessary */
4358 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004359){
danda9fe0c2010-07-13 18:44:03 +00004360 unixFile *pDbFd = (unixFile*)fd;
4361 unixShm *p;
4362 unixShmNode *pShmNode;
4363 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004364 int nShmPerMap = unixShmRegionPerMap();
4365 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004366
danda9fe0c2010-07-13 18:44:03 +00004367 /* If the shared-memory file has not yet been opened, open it now. */
4368 if( pDbFd->pShm==0 ){
4369 rc = unixOpenSharedMemory(pDbFd);
4370 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004371 }
drhd9e5c4f2010-05-12 18:01:39 +00004372
danda9fe0c2010-07-13 18:44:03 +00004373 p = pDbFd->pShm;
4374 pShmNode = p->pShmNode;
4375 sqlite3_mutex_enter(pShmNode->mutex);
4376 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004377 assert( pShmNode->pInode==pDbFd->pInode );
4378 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4379 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004380
dan781e34c2014-03-20 08:59:47 +00004381 /* Minimum number of regions required to be mapped. */
4382 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4383
4384 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004385 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004386 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004387 struct stat sStat; /* Used by fstat() */
4388
4389 pShmNode->szRegion = szRegion;
4390
drh3cb93392011-03-12 18:10:44 +00004391 if( pShmNode->h>=0 ){
4392 /* The requested region is not mapped into this processes address space.
4393 ** Check to see if it has been allocated (i.e. if the wal-index file is
4394 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004395 */
drh3cb93392011-03-12 18:10:44 +00004396 if( osFstat(pShmNode->h, &sStat) ){
4397 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004398 goto shmpage_out;
4399 }
drh3cb93392011-03-12 18:10:44 +00004400
4401 if( sStat.st_size<nByte ){
4402 /* The requested memory region does not exist. If bExtend is set to
4403 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004404 */
dan47a2b4a2013-04-26 16:09:29 +00004405 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004406 goto shmpage_out;
4407 }
dan47a2b4a2013-04-26 16:09:29 +00004408
4409 /* Alternatively, if bExtend is true, extend the file. Do this by
4410 ** writing a single byte to the end of each (OS) page being
4411 ** allocated or extended. Technically, we need only write to the
4412 ** last page in order to extend the file. But writing to all new
4413 ** pages forces the OS to allocate them immediately, which reduces
4414 ** the chances of SIGBUS while accessing the mapped region later on.
4415 */
4416 else{
4417 static const int pgsz = 4096;
4418 int iPg;
4419
4420 /* Write to the last byte of each newly allocated or extended page */
4421 assert( (nByte % pgsz)==0 );
4422 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4423 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4424 const char *zFile = pShmNode->zFilename;
4425 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4426 goto shmpage_out;
4427 }
4428 }
drh3cb93392011-03-12 18:10:44 +00004429 }
4430 }
danda9fe0c2010-07-13 18:44:03 +00004431 }
4432
4433 /* Map the requested memory region into this processes address space. */
4434 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004435 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004436 );
4437 if( !apNew ){
4438 rc = SQLITE_IOERR_NOMEM;
4439 goto shmpage_out;
4440 }
4441 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004442 while( pShmNode->nRegion<nReqRegion ){
4443 int nMap = szRegion*nShmPerMap;
4444 int i;
drh3cb93392011-03-12 18:10:44 +00004445 void *pMem;
4446 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004447 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004448 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004449 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004450 );
4451 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004452 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004453 goto shmpage_out;
4454 }
4455 }else{
4456 pMem = sqlite3_malloc(szRegion);
4457 if( pMem==0 ){
4458 rc = SQLITE_NOMEM;
4459 goto shmpage_out;
4460 }
4461 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004462 }
dan781e34c2014-03-20 08:59:47 +00004463
4464 for(i=0; i<nShmPerMap; i++){
4465 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4466 }
4467 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004468 }
4469 }
4470
4471shmpage_out:
4472 if( pShmNode->nRegion>iRegion ){
4473 *pp = pShmNode->apRegion[iRegion];
4474 }else{
4475 *pp = 0;
4476 }
drh66dfec8b2011-06-01 20:01:49 +00004477 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004478 sqlite3_mutex_leave(pShmNode->mutex);
4479 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004480}
4481
4482/*
drhd9e5c4f2010-05-12 18:01:39 +00004483** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004484**
4485** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4486** different here than in posix. In xShmLock(), one can go from unlocked
4487** to shared and back or from unlocked to exclusive and back. But one may
4488** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004489*/
4490static int unixShmLock(
4491 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004492 int ofst, /* First lock to acquire or release */
4493 int n, /* Number of locks to acquire or release */
4494 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004495){
drh73b64e42010-05-30 19:55:15 +00004496 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4497 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4498 unixShm *pX; /* For looping over all siblings */
4499 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4500 int rc = SQLITE_OK; /* Result code */
4501 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004502
drhd91c68f2010-05-14 14:52:25 +00004503 assert( pShmNode==pDbFd->pInode->pShmNode );
4504 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004505 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004506 assert( n>=1 );
4507 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4508 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4509 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4510 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4511 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004512 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4513 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004514
drhc99597c2010-05-31 01:41:15 +00004515 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004516 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004517 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004518 if( flags & SQLITE_SHM_UNLOCK ){
4519 u16 allMask = 0; /* Mask of locks held by siblings */
4520
4521 /* See if any siblings hold this same lock */
4522 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4523 if( pX==p ) continue;
4524 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4525 allMask |= pX->sharedMask;
4526 }
4527
4528 /* Unlock the system-level locks */
4529 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004530 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004531 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004532 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004533 }
drh73b64e42010-05-30 19:55:15 +00004534
4535 /* Undo the local locks */
4536 if( rc==SQLITE_OK ){
4537 p->exclMask &= ~mask;
4538 p->sharedMask &= ~mask;
4539 }
4540 }else if( flags & SQLITE_SHM_SHARED ){
4541 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4542
4543 /* Find out which shared locks are already held by sibling connections.
4544 ** If any sibling already holds an exclusive lock, go ahead and return
4545 ** SQLITE_BUSY.
4546 */
4547 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004548 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004549 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004550 break;
4551 }
4552 allShared |= pX->sharedMask;
4553 }
4554
4555 /* Get shared locks at the system level, if necessary */
4556 if( rc==SQLITE_OK ){
4557 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004558 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004559 }else{
drh73b64e42010-05-30 19:55:15 +00004560 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004561 }
drhd9e5c4f2010-05-12 18:01:39 +00004562 }
drh73b64e42010-05-30 19:55:15 +00004563
4564 /* Get the local shared locks */
4565 if( rc==SQLITE_OK ){
4566 p->sharedMask |= mask;
4567 }
4568 }else{
4569 /* Make sure no sibling connections hold locks that will block this
4570 ** lock. If any do, return SQLITE_BUSY right away.
4571 */
4572 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004573 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4574 rc = SQLITE_BUSY;
4575 break;
4576 }
4577 }
4578
4579 /* Get the exclusive locks at the system level. Then if successful
4580 ** also mark the local connection as being locked.
4581 */
4582 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004583 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004584 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004585 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004586 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004587 }
drhd9e5c4f2010-05-12 18:01:39 +00004588 }
4589 }
drhd91c68f2010-05-14 14:52:25 +00004590 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004591 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4592 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004593 return rc;
4594}
4595
drh286a2882010-05-20 23:51:06 +00004596/*
4597** Implement a memory barrier or memory fence on shared memory.
4598**
4599** All loads and stores begun before the barrier must complete before
4600** any load or store begun after the barrier.
4601*/
4602static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004603 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004604){
drhff828942010-06-26 21:34:06 +00004605 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004606 unixEnterMutex();
4607 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004608}
4609
dan18801912010-06-14 14:07:50 +00004610/*
danda9fe0c2010-07-13 18:44:03 +00004611** Close a connection to shared-memory. Delete the underlying
4612** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004613**
4614** If there is no shared memory associated with the connection then this
4615** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004616*/
danda9fe0c2010-07-13 18:44:03 +00004617static int unixShmUnmap(
4618 sqlite3_file *fd, /* The underlying database file */
4619 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004620){
danda9fe0c2010-07-13 18:44:03 +00004621 unixShm *p; /* The connection to be closed */
4622 unixShmNode *pShmNode; /* The underlying shared-memory file */
4623 unixShm **pp; /* For looping over sibling connections */
4624 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004625
danda9fe0c2010-07-13 18:44:03 +00004626 pDbFd = (unixFile*)fd;
4627 p = pDbFd->pShm;
4628 if( p==0 ) return SQLITE_OK;
4629 pShmNode = p->pShmNode;
4630
4631 assert( pShmNode==pDbFd->pInode->pShmNode );
4632 assert( pShmNode->pInode==pDbFd->pInode );
4633
4634 /* Remove connection p from the set of connections associated
4635 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004636 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004637 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4638 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004639
danda9fe0c2010-07-13 18:44:03 +00004640 /* Free the connection p */
4641 sqlite3_free(p);
4642 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004643 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004644
4645 /* If pShmNode->nRef has reached 0, then close the underlying
4646 ** shared-memory file, too */
4647 unixEnterMutex();
4648 assert( pShmNode->nRef>0 );
4649 pShmNode->nRef--;
4650 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004651 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004652 unixShmPurge(pDbFd);
4653 }
4654 unixLeaveMutex();
4655
4656 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004657}
drh286a2882010-05-20 23:51:06 +00004658
danda9fe0c2010-07-13 18:44:03 +00004659
drhd9e5c4f2010-05-12 18:01:39 +00004660#else
drh6b017cc2010-06-14 18:01:46 +00004661# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004662# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004663# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004664# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004665#endif /* #ifndef SQLITE_OMIT_WAL */
4666
mistachkine98844f2013-08-24 00:59:24 +00004667#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004668/*
danaef49d72013-03-25 16:28:54 +00004669** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004670*/
danf23da962013-03-23 21:00:41 +00004671static void unixUnmapfile(unixFile *pFd){
4672 assert( pFd->nFetchOut==0 );
4673 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004674 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004675 pFd->pMapRegion = 0;
4676 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004677 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004678 }
4679}
dan5d8a1372013-03-19 19:28:06 +00004680
danaef49d72013-03-25 16:28:54 +00004681/*
dane6ecd662013-04-01 17:56:59 +00004682** Attempt to set the size of the memory mapping maintained by file
4683** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4684**
4685** If successful, this function sets the following variables:
4686**
4687** unixFile.pMapRegion
4688** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004689** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004690**
4691** If unsuccessful, an error message is logged via sqlite3_log() and
4692** the three variables above are zeroed. In this case SQLite should
4693** continue accessing the database using the xRead() and xWrite()
4694** methods.
4695*/
4696static void unixRemapfile(
4697 unixFile *pFd, /* File descriptor object */
4698 i64 nNew /* Required mapping size */
4699){
dan4ff7bc42013-04-02 12:04:09 +00004700 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004701 int h = pFd->h; /* File descriptor open on db file */
4702 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004703 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004704 u8 *pNew = 0; /* Location of new mapping */
4705 int flags = PROT_READ; /* Flags to pass to mmap() */
4706
4707 assert( pFd->nFetchOut==0 );
4708 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004709 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004710 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004711 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004712 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004713
4714 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4715
4716 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004717#if HAVE_MREMAP
4718 i64 nReuse = pFd->mmapSize;
4719#else
danbc760632014-03-20 09:42:09 +00004720 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004721 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004722#endif
dane6ecd662013-04-01 17:56:59 +00004723 u8 *pReq = &pOrig[nReuse];
4724
4725 /* Unmap any pages of the existing mapping that cannot be reused. */
4726 if( nReuse!=nOrig ){
4727 osMunmap(pReq, nOrig-nReuse);
4728 }
4729
4730#if HAVE_MREMAP
4731 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004732 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004733#else
4734 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4735 if( pNew!=MAP_FAILED ){
4736 if( pNew!=pReq ){
4737 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004738 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004739 }else{
4740 pNew = pOrig;
4741 }
4742 }
4743#endif
4744
dan48ccef82013-04-02 20:55:01 +00004745 /* The attempt to extend the existing mapping failed. Free it. */
4746 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004747 osMunmap(pOrig, nReuse);
4748 }
4749 }
4750
4751 /* If pNew is still NULL, try to create an entirely new mapping. */
4752 if( pNew==0 ){
4753 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004754 }
4755
dan4ff7bc42013-04-02 12:04:09 +00004756 if( pNew==MAP_FAILED ){
4757 pNew = 0;
4758 nNew = 0;
4759 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4760
4761 /* If the mmap() above failed, assume that all subsequent mmap() calls
4762 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4763 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004764 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004765 }
dane6ecd662013-04-01 17:56:59 +00004766 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004767 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004768}
4769
4770/*
danaef49d72013-03-25 16:28:54 +00004771** Memory map or remap the file opened by file-descriptor pFd (if the file
4772** is already mapped, the existing mapping is replaced by the new). Or, if
4773** there already exists a mapping for this file, and there are still
4774** outstanding xFetch() references to it, this function is a no-op.
4775**
4776** If parameter nByte is non-negative, then it is the requested size of
4777** the mapping to create. Otherwise, if nByte is less than zero, then the
4778** requested size is the size of the file on disk. The actual size of the
4779** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004780** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004781**
4782** SQLITE_OK is returned if no error occurs (even if the mapping is not
4783** recreated as a result of outstanding references) or an SQLite error
4784** code otherwise.
4785*/
danf23da962013-03-23 21:00:41 +00004786static int unixMapfile(unixFile *pFd, i64 nByte){
4787 i64 nMap = nByte;
4788 int rc;
daneb97b292013-03-20 14:26:59 +00004789
danf23da962013-03-23 21:00:41 +00004790 assert( nMap>=0 || pFd->nFetchOut==0 );
4791 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4792
4793 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004794 struct stat statbuf; /* Low-level file information */
4795 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004796 if( rc!=SQLITE_OK ){
4797 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004798 }
drh3044b512014-06-16 16:41:52 +00004799 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004800 }
drh9b4c59f2013-04-15 17:03:42 +00004801 if( nMap>pFd->mmapSizeMax ){
4802 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004803 }
4804
danf23da962013-03-23 21:00:41 +00004805 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004806 if( nMap>0 ){
4807 unixRemapfile(pFd, nMap);
4808 }else{
danb7e3a322013-03-25 20:30:13 +00004809 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004810 }
4811 }
4812
danf23da962013-03-23 21:00:41 +00004813 return SQLITE_OK;
4814}
mistachkine98844f2013-08-24 00:59:24 +00004815#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004816
danaef49d72013-03-25 16:28:54 +00004817/*
4818** If possible, return a pointer to a mapping of file fd starting at offset
4819** iOff. The mapping must be valid for at least nAmt bytes.
4820**
4821** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4822** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4823** Finally, if an error does occur, return an SQLite error code. The final
4824** value of *pp is undefined in this case.
4825**
4826** If this function does return a pointer, the caller must eventually
4827** release the reference by calling unixUnfetch().
4828*/
danf23da962013-03-23 21:00:41 +00004829static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004830#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004831 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004832#endif
danf23da962013-03-23 21:00:41 +00004833 *pp = 0;
4834
drh9b4c59f2013-04-15 17:03:42 +00004835#if SQLITE_MAX_MMAP_SIZE>0
4836 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004837 if( pFd->pMapRegion==0 ){
4838 int rc = unixMapfile(pFd, -1);
4839 if( rc!=SQLITE_OK ) return rc;
4840 }
4841 if( pFd->mmapSize >= iOff+nAmt ){
4842 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4843 pFd->nFetchOut++;
4844 }
4845 }
drh6e0b6d52013-04-09 16:19:20 +00004846#endif
danf23da962013-03-23 21:00:41 +00004847 return SQLITE_OK;
4848}
4849
danaef49d72013-03-25 16:28:54 +00004850/*
dandf737fe2013-03-25 17:00:24 +00004851** If the third argument is non-NULL, then this function releases a
4852** reference obtained by an earlier call to unixFetch(). The second
4853** argument passed to this function must be the same as the corresponding
4854** argument that was passed to the unixFetch() invocation.
4855**
4856** Or, if the third argument is NULL, then this function is being called
4857** to inform the VFS layer that, according to POSIX, any existing mapping
4858** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004859*/
dandf737fe2013-03-25 17:00:24 +00004860static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004861#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004862 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004863 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004864
danaef49d72013-03-25 16:28:54 +00004865 /* If p==0 (unmap the entire file) then there must be no outstanding
4866 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4867 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004868 assert( (p==0)==(pFd->nFetchOut==0) );
4869
dandf737fe2013-03-25 17:00:24 +00004870 /* If p!=0, it must match the iOff value. */
4871 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4872
danf23da962013-03-23 21:00:41 +00004873 if( p ){
4874 pFd->nFetchOut--;
4875 }else{
4876 unixUnmapfile(pFd);
4877 }
4878
4879 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004880#else
4881 UNUSED_PARAMETER(fd);
4882 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004883 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004884#endif
danf23da962013-03-23 21:00:41 +00004885 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004886}
4887
4888/*
drh734c9862008-11-28 15:37:20 +00004889** Here ends the implementation of all sqlite3_file methods.
4890**
4891********************** End sqlite3_file Methods *******************************
4892******************************************************************************/
4893
4894/*
drh6b9d6dd2008-12-03 19:34:47 +00004895** This division contains definitions of sqlite3_io_methods objects that
4896** implement various file locking strategies. It also contains definitions
4897** of "finder" functions. A finder-function is used to locate the appropriate
4898** sqlite3_io_methods object for a particular database file. The pAppData
4899** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4900** the correct finder-function for that VFS.
4901**
4902** Most finder functions return a pointer to a fixed sqlite3_io_methods
4903** object. The only interesting finder-function is autolockIoFinder, which
4904** looks at the filesystem type and tries to guess the best locking
4905** strategy from that.
4906**
drh1875f7a2008-12-08 18:19:17 +00004907** For finder-funtion F, two objects are created:
4908**
4909** (1) The real finder-function named "FImpt()".
4910**
dane946c392009-08-22 11:39:46 +00004911** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004912**
4913**
4914** A pointer to the F pointer is used as the pAppData value for VFS
4915** objects. We have to do this instead of letting pAppData point
4916** directly at the finder-function since C90 rules prevent a void*
4917** from be cast into a function pointer.
4918**
drh6b9d6dd2008-12-03 19:34:47 +00004919**
drh7708e972008-11-29 00:56:52 +00004920** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004921**
drh7708e972008-11-29 00:56:52 +00004922** * A constant sqlite3_io_methods object call METHOD that has locking
4923** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4924**
4925** * An I/O method finder function called FINDER that returns a pointer
4926** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004927*/
drhd9e5c4f2010-05-12 18:01:39 +00004928#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004929static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004930 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004931 CLOSE, /* xClose */ \
4932 unixRead, /* xRead */ \
4933 unixWrite, /* xWrite */ \
4934 unixTruncate, /* xTruncate */ \
4935 unixSync, /* xSync */ \
4936 unixFileSize, /* xFileSize */ \
4937 LOCK, /* xLock */ \
4938 UNLOCK, /* xUnlock */ \
4939 CKLOCK, /* xCheckReservedLock */ \
4940 unixFileControl, /* xFileControl */ \
4941 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004942 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004943 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004944 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004945 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004946 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004947 unixFetch, /* xFetch */ \
4948 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004949}; \
drh0c2694b2009-09-03 16:23:44 +00004950static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4951 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004952 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004953} \
drh0c2694b2009-09-03 16:23:44 +00004954static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004955 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004956
4957/*
4958** Here are all of the sqlite3_io_methods objects for each of the
4959** locking strategies. Functions that return pointers to these methods
4960** are also created.
4961*/
4962IOMETHODS(
4963 posixIoFinder, /* Finder function name */
4964 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004965 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004966 unixClose, /* xClose method */
4967 unixLock, /* xLock method */
4968 unixUnlock, /* xUnlock method */
4969 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004970)
drh7708e972008-11-29 00:56:52 +00004971IOMETHODS(
4972 nolockIoFinder, /* Finder function name */
4973 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004974 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004975 nolockClose, /* xClose method */
4976 nolockLock, /* xLock method */
4977 nolockUnlock, /* xUnlock method */
4978 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004979)
drh7708e972008-11-29 00:56:52 +00004980IOMETHODS(
4981 dotlockIoFinder, /* Finder function name */
4982 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004983 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004984 dotlockClose, /* xClose method */
4985 dotlockLock, /* xLock method */
4986 dotlockUnlock, /* xUnlock method */
4987 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004988)
drh7708e972008-11-29 00:56:52 +00004989
chw78a13182009-04-07 05:35:03 +00004990#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004991IOMETHODS(
4992 flockIoFinder, /* Finder function name */
4993 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004994 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004995 flockClose, /* xClose method */
4996 flockLock, /* xLock method */
4997 flockUnlock, /* xUnlock method */
4998 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004999)
drh7708e972008-11-29 00:56:52 +00005000#endif
5001
drh6c7d5c52008-11-21 20:32:33 +00005002#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005003IOMETHODS(
5004 semIoFinder, /* Finder function name */
5005 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005006 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005007 semClose, /* xClose method */
5008 semLock, /* xLock method */
5009 semUnlock, /* xUnlock method */
5010 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005011)
aswiftaebf4132008-11-21 00:10:35 +00005012#endif
drh7708e972008-11-29 00:56:52 +00005013
drhd2cb50b2009-01-09 21:41:17 +00005014#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005015IOMETHODS(
5016 afpIoFinder, /* Finder function name */
5017 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005018 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005019 afpClose, /* xClose method */
5020 afpLock, /* xLock method */
5021 afpUnlock, /* xUnlock method */
5022 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005023)
drh715ff302008-12-03 22:32:44 +00005024#endif
5025
5026/*
5027** The proxy locking method is a "super-method" in the sense that it
5028** opens secondary file descriptors for the conch and lock files and
5029** it uses proxy, dot-file, AFP, and flock() locking methods on those
5030** secondary files. For this reason, the division that implements
5031** proxy locking is located much further down in the file. But we need
5032** to go ahead and define the sqlite3_io_methods and finder function
5033** for proxy locking here. So we forward declare the I/O methods.
5034*/
drhd2cb50b2009-01-09 21:41:17 +00005035#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005036static int proxyClose(sqlite3_file*);
5037static int proxyLock(sqlite3_file*, int);
5038static int proxyUnlock(sqlite3_file*, int);
5039static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005040IOMETHODS(
5041 proxyIoFinder, /* Finder function name */
5042 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005043 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005044 proxyClose, /* xClose method */
5045 proxyLock, /* xLock method */
5046 proxyUnlock, /* xUnlock method */
5047 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005048)
aswiftaebf4132008-11-21 00:10:35 +00005049#endif
drh7708e972008-11-29 00:56:52 +00005050
drh7ed97b92010-01-20 13:07:21 +00005051/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5052#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5053IOMETHODS(
5054 nfsIoFinder, /* Finder function name */
5055 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005056 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005057 unixClose, /* xClose method */
5058 unixLock, /* xLock method */
5059 nfsUnlock, /* xUnlock method */
5060 unixCheckReservedLock /* xCheckReservedLock method */
5061)
5062#endif
drh7708e972008-11-29 00:56:52 +00005063
drhd2cb50b2009-01-09 21:41:17 +00005064#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005065/*
drh6b9d6dd2008-12-03 19:34:47 +00005066** This "finder" function attempts to determine the best locking strategy
5067** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005068** object that implements that strategy.
5069**
5070** This is for MacOSX only.
5071*/
drh1875f7a2008-12-08 18:19:17 +00005072static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005073 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005074 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005075){
5076 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005077 const char *zFilesystem; /* Filesystem type name */
5078 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005079 } aMap[] = {
5080 { "hfs", &posixIoMethods },
5081 { "ufs", &posixIoMethods },
5082 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005083 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005084 { "webdav", &nolockIoMethods },
5085 { 0, 0 }
5086 };
5087 int i;
5088 struct statfs fsInfo;
5089 struct flock lockInfo;
5090
5091 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005092 /* If filePath==NULL that means we are dealing with a transient file
5093 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005094 return &nolockIoMethods;
5095 }
5096 if( statfs(filePath, &fsInfo) != -1 ){
5097 if( fsInfo.f_flags & MNT_RDONLY ){
5098 return &nolockIoMethods;
5099 }
5100 for(i=0; aMap[i].zFilesystem; i++){
5101 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5102 return aMap[i].pMethods;
5103 }
5104 }
5105 }
5106
5107 /* Default case. Handles, amongst others, "nfs".
5108 ** Test byte-range lock using fcntl(). If the call succeeds,
5109 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005110 */
drh7708e972008-11-29 00:56:52 +00005111 lockInfo.l_len = 1;
5112 lockInfo.l_start = 0;
5113 lockInfo.l_whence = SEEK_SET;
5114 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005115 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005116 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5117 return &nfsIoMethods;
5118 } else {
5119 return &posixIoMethods;
5120 }
drh7708e972008-11-29 00:56:52 +00005121 }else{
5122 return &dotlockIoMethods;
5123 }
5124}
drh0c2694b2009-09-03 16:23:44 +00005125static const sqlite3_io_methods
5126 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005127
drhd2cb50b2009-01-09 21:41:17 +00005128#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005129
chw78a13182009-04-07 05:35:03 +00005130#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5131/*
5132** This "finder" function attempts to determine the best locking strategy
5133** for the database file "filePath". It then returns the sqlite3_io_methods
5134** object that implements that strategy.
5135**
5136** This is for VXWorks only.
5137*/
5138static const sqlite3_io_methods *autolockIoFinderImpl(
5139 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005140 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005141){
5142 struct flock lockInfo;
5143
5144 if( !filePath ){
5145 /* If filePath==NULL that means we are dealing with a transient file
5146 ** that does not need to be locked. */
5147 return &nolockIoMethods;
5148 }
5149
5150 /* Test if fcntl() is supported and use POSIX style locks.
5151 ** Otherwise fall back to the named semaphore method.
5152 */
5153 lockInfo.l_len = 1;
5154 lockInfo.l_start = 0;
5155 lockInfo.l_whence = SEEK_SET;
5156 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005157 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005158 return &posixIoMethods;
5159 }else{
5160 return &semIoMethods;
5161 }
5162}
drh0c2694b2009-09-03 16:23:44 +00005163static const sqlite3_io_methods
5164 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005165
5166#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5167
drh7708e972008-11-29 00:56:52 +00005168/*
5169** An abstract type for a pointer to a IO method finder function:
5170*/
drh0c2694b2009-09-03 16:23:44 +00005171typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005172
aswiftaebf4132008-11-21 00:10:35 +00005173
drh734c9862008-11-28 15:37:20 +00005174/****************************************************************************
5175**************************** sqlite3_vfs methods ****************************
5176**
5177** This division contains the implementation of methods on the
5178** sqlite3_vfs object.
5179*/
5180
danielk1977a3d4c882007-03-23 10:08:38 +00005181/*
danielk1977e339d652008-06-28 11:23:00 +00005182** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005183*/
5184static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005185 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005186 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005187 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005188 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005189 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005190){
drh7708e972008-11-29 00:56:52 +00005191 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005192 unixFile *pNew = (unixFile *)pId;
5193 int rc = SQLITE_OK;
5194
drh8af6c222010-05-14 12:43:01 +00005195 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005196
dan00157392010-10-05 11:33:15 +00005197 /* Usually the path zFilename should not be a relative pathname. The
5198 ** exception is when opening the proxy "conch" file in builds that
5199 ** include the special Apple locking styles.
5200 */
dan00157392010-10-05 11:33:15 +00005201#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005202 assert( zFilename==0 || zFilename[0]=='/'
5203 || pVfs->pAppData==(void*)&autolockIoFinder );
5204#else
5205 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005206#endif
dan00157392010-10-05 11:33:15 +00005207
drhb07028f2011-10-14 21:49:18 +00005208 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005209 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005210
drh308c2a52010-05-14 11:30:18 +00005211 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005212 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005213 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005214 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005215 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005216#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005217 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005218#endif
drhc02a43a2012-01-10 23:18:38 +00005219 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5220 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005221 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005222 }
drh503a6862013-03-01 01:07:17 +00005223 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005224 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005225 }
drh339eb0b2008-03-07 15:34:11 +00005226
drh6c7d5c52008-11-21 20:32:33 +00005227#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005228 pNew->pId = vxworksFindFileId(zFilename);
5229 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005230 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005231 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005232 }
5233#endif
5234
drhc02a43a2012-01-10 23:18:38 +00005235 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005236 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005237 }else{
drh0c2694b2009-09-03 16:23:44 +00005238 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005239#if SQLITE_ENABLE_LOCKING_STYLE
5240 /* Cache zFilename in the locking context (AFP and dotlock override) for
5241 ** proxyLock activation is possible (remote proxy is based on db name)
5242 ** zFilename remains valid until file is closed, to support */
5243 pNew->lockingContext = (void*)zFilename;
5244#endif
drhda0e7682008-07-30 15:27:54 +00005245 }
danielk1977e339d652008-06-28 11:23:00 +00005246
drh7ed97b92010-01-20 13:07:21 +00005247 if( pLockingStyle == &posixIoMethods
5248#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5249 || pLockingStyle == &nfsIoMethods
5250#endif
5251 ){
drh7708e972008-11-29 00:56:52 +00005252 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005253 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005254 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005255 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005256 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005257 ** in two scenarios:
5258 **
5259 ** (a) A call to fstat() failed.
5260 ** (b) A malloc failed.
5261 **
5262 ** Scenario (b) may only occur if the process is holding no other
5263 ** file descriptors open on the same file. If there were other file
5264 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005265 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005266 ** handle h - as it is guaranteed that no posix locks will be released
5267 ** by doing so.
5268 **
5269 ** If scenario (a) caused the error then things are not so safe. The
5270 ** implicit assumption here is that if fstat() fails, things are in
5271 ** such bad shape that dropping a lock or two doesn't matter much.
5272 */
drh0e9365c2011-03-02 02:08:13 +00005273 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005274 h = -1;
5275 }
drh7708e972008-11-29 00:56:52 +00005276 unixLeaveMutex();
5277 }
danielk1977e339d652008-06-28 11:23:00 +00005278
drhd2cb50b2009-01-09 21:41:17 +00005279#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005280 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005281 /* AFP locking uses the file path so it needs to be included in
5282 ** the afpLockingContext.
5283 */
5284 afpLockingContext *pCtx;
5285 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5286 if( pCtx==0 ){
5287 rc = SQLITE_NOMEM;
5288 }else{
5289 /* NB: zFilename exists and remains valid until the file is closed
5290 ** according to requirement F11141. So we do not need to make a
5291 ** copy of the filename. */
5292 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005293 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005294 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005295 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005296 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005297 if( rc!=SQLITE_OK ){
5298 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005299 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005300 h = -1;
5301 }
drh7708e972008-11-29 00:56:52 +00005302 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005303 }
drh7708e972008-11-29 00:56:52 +00005304 }
5305#endif
danielk1977e339d652008-06-28 11:23:00 +00005306
drh7708e972008-11-29 00:56:52 +00005307 else if( pLockingStyle == &dotlockIoMethods ){
5308 /* Dotfile locking uses the file path so it needs to be included in
5309 ** the dotlockLockingContext
5310 */
5311 char *zLockFile;
5312 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005313 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005314 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005315 zLockFile = (char *)sqlite3_malloc(nFilename);
5316 if( zLockFile==0 ){
5317 rc = SQLITE_NOMEM;
5318 }else{
5319 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005320 }
drh7708e972008-11-29 00:56:52 +00005321 pNew->lockingContext = zLockFile;
5322 }
danielk1977e339d652008-06-28 11:23:00 +00005323
drh6c7d5c52008-11-21 20:32:33 +00005324#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005325 else if( pLockingStyle == &semIoMethods ){
5326 /* Named semaphore locking uses the file path so it needs to be
5327 ** included in the semLockingContext
5328 */
5329 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005330 rc = findInodeInfo(pNew, &pNew->pInode);
5331 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5332 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005333 int n;
drh2238dcc2009-08-27 17:56:20 +00005334 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005335 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005336 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005337 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005338 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5339 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005340 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005341 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005342 }
chw97185482008-11-17 08:05:31 +00005343 }
drh7708e972008-11-29 00:56:52 +00005344 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005345 }
drh7708e972008-11-29 00:56:52 +00005346#endif
aswift5b1a2562008-08-22 00:22:35 +00005347
5348 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005349#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005350 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005351 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005352 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005353 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005354 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005355 }
chw97185482008-11-17 08:05:31 +00005356#endif
danielk1977e339d652008-06-28 11:23:00 +00005357 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005358 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005359 }else{
drh7708e972008-11-29 00:56:52 +00005360 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005361 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005362 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005363 }
danielk1977e339d652008-06-28 11:23:00 +00005364 return rc;
drh054889e2005-11-30 03:20:31 +00005365}
drh9c06c952005-11-26 00:25:00 +00005366
danielk1977ad94b582007-08-20 06:44:22 +00005367/*
drh8b3cf822010-06-01 21:02:51 +00005368** Return the name of a directory in which to put temporary files.
5369** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005370*/
drh7234c6d2010-06-19 15:10:09 +00005371static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005372 static const char *azDirs[] = {
5373 0,
aswiftaebf4132008-11-21 00:10:35 +00005374 0,
mistachkind95a3d32013-08-30 21:52:38 +00005375 0,
danielk197717b90b52008-06-06 11:11:25 +00005376 "/var/tmp",
5377 "/usr/tmp",
5378 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005379 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005380 };
drh8b3cf822010-06-01 21:02:51 +00005381 unsigned int i;
5382 struct stat buf;
5383 const char *zDir = 0;
5384
5385 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005386 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5387 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005388 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005389 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005390 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005391 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005392 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005393 break;
5394 }
5395 return zDir;
5396}
5397
5398/*
5399** Create a temporary file name in zBuf. zBuf must be allocated
5400** by the calling process and must be big enough to hold at least
5401** pVfs->mxPathname bytes.
5402*/
5403static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005404 static const unsigned char zChars[] =
5405 "abcdefghijklmnopqrstuvwxyz"
5406 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5407 "0123456789";
drh41022642008-11-21 00:24:42 +00005408 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005409 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005410
5411 /* It's odd to simulate an io-error here, but really this is just
5412 ** using the io-error infrastructure to test that SQLite handles this
5413 ** function failing.
5414 */
5415 SimulateIOError( return SQLITE_IOERR );
5416
drh7234c6d2010-06-19 15:10:09 +00005417 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005418 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005419
5420 /* Check that the output buffer is large enough for the temporary file
5421 ** name. If it is not, return SQLITE_ERROR.
5422 */
drhc02a43a2012-01-10 23:18:38 +00005423 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005424 return SQLITE_ERROR;
5425 }
5426
5427 do{
drhc02a43a2012-01-10 23:18:38 +00005428 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005429 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005430 sqlite3_randomness(15, &zBuf[j]);
5431 for(i=0; i<15; i++, j++){
5432 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5433 }
5434 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005435 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005436 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005437 return SQLITE_OK;
5438}
5439
drhd2cb50b2009-01-09 21:41:17 +00005440#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005441/*
5442** Routine to transform a unixFile into a proxy-locking unixFile.
5443** Implementation in the proxy-lock division, but used by unixOpen()
5444** if SQLITE_PREFER_PROXY_LOCKING is defined.
5445*/
5446static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005447#endif
drhc66d5b62008-12-03 22:48:32 +00005448
dan08da86a2009-08-21 17:18:03 +00005449/*
5450** Search for an unused file descriptor that was opened on the database
5451** file (not a journal or master-journal file) identified by pathname
5452** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5453** argument to this function.
5454**
5455** Such a file descriptor may exist if a database connection was closed
5456** but the associated file descriptor could not be closed because some
5457** other file descriptor open on the same file is holding a file-lock.
5458** Refer to comments in the unixClose() function and the lengthy comment
5459** describing "Posix Advisory Locking" at the start of this file for
5460** further details. Also, ticket #4018.
5461**
5462** If a suitable file descriptor is found, then it is returned. If no
5463** such file descriptor is located, -1 is returned.
5464*/
dane946c392009-08-22 11:39:46 +00005465static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5466 UnixUnusedFd *pUnused = 0;
5467
5468 /* Do not search for an unused file descriptor on vxworks. Not because
5469 ** vxworks would not benefit from the change (it might, we're not sure),
5470 ** but because no way to test it is currently available. It is better
5471 ** not to risk breaking vxworks support for the sake of such an obscure
5472 ** feature. */
5473#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005474 struct stat sStat; /* Results of stat() call */
5475
5476 /* A stat() call may fail for various reasons. If this happens, it is
5477 ** almost certain that an open() call on the same path will also fail.
5478 ** For this reason, if an error occurs in the stat() call here, it is
5479 ** ignored and -1 is returned. The caller will try to open a new file
5480 ** descriptor on the same path, fail, and return an error to SQLite.
5481 **
5482 ** Even if a subsequent open() call does succeed, the consequences of
5483 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005484 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005485 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005486
5487 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005488 pInode = inodeList;
5489 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5490 || pInode->fileId.ino!=sStat.st_ino) ){
5491 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005492 }
drh8af6c222010-05-14 12:43:01 +00005493 if( pInode ){
dane946c392009-08-22 11:39:46 +00005494 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005495 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005496 pUnused = *pp;
5497 if( pUnused ){
5498 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005499 }
5500 }
5501 unixLeaveMutex();
5502 }
dane946c392009-08-22 11:39:46 +00005503#endif /* if !OS_VXWORKS */
5504 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005505}
danielk197717b90b52008-06-06 11:11:25 +00005506
5507/*
danddb0ac42010-07-14 14:48:58 +00005508** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005509** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005510** and a value suitable for passing as the third argument to open(2) is
5511** written to *pMode. If an IO error occurs, an SQLite error code is
5512** returned and the value of *pMode is not modified.
5513**
drh8c815d12012-02-13 20:16:37 +00005514** In most cases cases, this routine sets *pMode to 0, which will become
5515** an indication to robust_open() to create the file using
5516** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5517** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005518** this function queries the file-system for the permissions on the
5519** corresponding database file and sets *pMode to this value. Whenever
5520** possible, WAL and journal files are created using the same permissions
5521** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005522**
5523** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5524** original filename is unavailable. But 8_3_NAMES is only used for
5525** FAT filesystems and permissions do not matter there, so just use
5526** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005527*/
5528static int findCreateFileMode(
5529 const char *zPath, /* Path of file (possibly) being created */
5530 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005531 mode_t *pMode, /* OUT: Permissions to open file with */
5532 uid_t *pUid, /* OUT: uid to set on the file */
5533 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005534){
5535 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005536 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005537 *pUid = 0;
5538 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005539 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005540 char zDb[MAX_PATHNAME+1]; /* Database file path */
5541 int nDb; /* Number of valid bytes in zDb */
5542 struct stat sStat; /* Output of stat() on database file */
5543
dana0c989d2010-11-05 18:07:37 +00005544 /* zPath is a path to a WAL or journal file. The following block derives
5545 ** the path to the associated database file from zPath. This block handles
5546 ** the following naming conventions:
5547 **
5548 ** "<path to db>-journal"
5549 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005550 ** "<path to db>-journalNN"
5551 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005552 **
drhd337c5b2011-10-20 18:23:35 +00005553 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005554 ** used by the test_multiplex.c module.
5555 */
5556 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005557#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005558 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005559 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005560#else
5561 while( zPath[nDb]!='-' ){
5562 assert( nDb>0 );
5563 assert( zPath[nDb]!='\n' );
5564 nDb--;
5565 }
5566#endif
danddb0ac42010-07-14 14:48:58 +00005567 memcpy(zDb, zPath, nDb);
5568 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005569
drh58384f12011-07-28 00:14:45 +00005570 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005571 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005572 *pUid = sStat.st_uid;
5573 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005574 }else{
5575 rc = SQLITE_IOERR_FSTAT;
5576 }
5577 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5578 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005579 }
5580 return rc;
5581}
5582
5583/*
danielk1977ad94b582007-08-20 06:44:22 +00005584** Open the file zPath.
5585**
danielk1977b4b47412007-08-17 15:53:36 +00005586** Previously, the SQLite OS layer used three functions in place of this
5587** one:
5588**
5589** sqlite3OsOpenReadWrite();
5590** sqlite3OsOpenReadOnly();
5591** sqlite3OsOpenExclusive();
5592**
5593** These calls correspond to the following combinations of flags:
5594**
5595** ReadWrite() -> (READWRITE | CREATE)
5596** ReadOnly() -> (READONLY)
5597** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5598**
5599** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5600** true, the file was configured to be automatically deleted when the
5601** file handle closed. To achieve the same effect using this new
5602** interface, add the DELETEONCLOSE flag to those specified above for
5603** OpenExclusive().
5604*/
5605static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005606 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5607 const char *zPath, /* Pathname of file to be opened */
5608 sqlite3_file *pFile, /* The file descriptor to be filled in */
5609 int flags, /* Input flags to control the opening */
5610 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005611){
dan08da86a2009-08-21 17:18:03 +00005612 unixFile *p = (unixFile *)pFile;
5613 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005614 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005615 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005616 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005617 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005618 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005619
5620 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5621 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5622 int isCreate = (flags & SQLITE_OPEN_CREATE);
5623 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5624 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005625#if SQLITE_ENABLE_LOCKING_STYLE
5626 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5627#endif
drh3d4435b2011-08-26 20:55:50 +00005628#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5629 struct statfs fsInfo;
5630#endif
danielk1977b4b47412007-08-17 15:53:36 +00005631
danielk1977fee2d252007-08-18 10:59:19 +00005632 /* If creating a master or main-file journal, this function will open
5633 ** a file-descriptor on the directory too. The first time unixSync()
5634 ** is called the directory file descriptor will be fsync()ed and close()d.
5635 */
drh0059eae2011-08-08 23:48:40 +00005636 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005637 eType==SQLITE_OPEN_MASTER_JOURNAL
5638 || eType==SQLITE_OPEN_MAIN_JOURNAL
5639 || eType==SQLITE_OPEN_WAL
5640 ));
danielk1977fee2d252007-08-18 10:59:19 +00005641
danielk197717b90b52008-06-06 11:11:25 +00005642 /* If argument zPath is a NULL pointer, this function is required to open
5643 ** a temporary file. Use this buffer to store the file name in.
5644 */
drhc02a43a2012-01-10 23:18:38 +00005645 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005646 const char *zName = zPath;
5647
danielk1977fee2d252007-08-18 10:59:19 +00005648 /* Check the following statements are true:
5649 **
5650 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5651 ** (b) if CREATE is set, then READWRITE must also be set, and
5652 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005653 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005654 */
danielk1977b4b47412007-08-17 15:53:36 +00005655 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005656 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005657 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005658 assert(isDelete==0 || isCreate);
5659
danddb0ac42010-07-14 14:48:58 +00005660 /* The main DB, main journal, WAL file and master journal are never
5661 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005662 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5663 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5664 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005665 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005666
danielk1977fee2d252007-08-18 10:59:19 +00005667 /* Assert that the upper layer has set one of the "file-type" flags. */
5668 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5669 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5670 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005671 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005672 );
5673
drhb00d8622014-01-01 15:18:36 +00005674 /* Detect a pid change and reset the PRNG. There is a race condition
5675 ** here such that two or more threads all trying to open databases at
5676 ** the same instant might all reset the PRNG. But multiple resets
5677 ** are harmless.
5678 */
5679 if( randomnessPid!=getpid() ){
5680 randomnessPid = getpid();
5681 sqlite3_randomness(0,0);
5682 }
5683
dan08da86a2009-08-21 17:18:03 +00005684 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005685
dan08da86a2009-08-21 17:18:03 +00005686 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005687 UnixUnusedFd *pUnused;
5688 pUnused = findReusableFd(zName, flags);
5689 if( pUnused ){
5690 fd = pUnused->fd;
5691 }else{
dan6aa657f2009-08-24 18:57:58 +00005692 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005693 if( !pUnused ){
5694 return SQLITE_NOMEM;
5695 }
5696 }
5697 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005698
5699 /* Database filenames are double-zero terminated if they are not
5700 ** URIs with parameters. Hence, they can always be passed into
5701 ** sqlite3_uri_parameter(). */
5702 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5703
dan08da86a2009-08-21 17:18:03 +00005704 }else if( !zName ){
5705 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005706 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005707 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005708 if( rc!=SQLITE_OK ){
5709 return rc;
5710 }
5711 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005712
5713 /* Generated temporary filenames are always double-zero terminated
5714 ** for use by sqlite3_uri_parameter(). */
5715 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005716 }
5717
dan08da86a2009-08-21 17:18:03 +00005718 /* Determine the value of the flags parameter passed to POSIX function
5719 ** open(). These must be calculated even if open() is not called, as
5720 ** they may be stored as part of the file handle and used by the
5721 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005722 if( isReadonly ) openFlags |= O_RDONLY;
5723 if( isReadWrite ) openFlags |= O_RDWR;
5724 if( isCreate ) openFlags |= O_CREAT;
5725 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5726 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005727
danielk1977b4b47412007-08-17 15:53:36 +00005728 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005729 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005730 uid_t uid; /* Userid for the file */
5731 gid_t gid; /* Groupid for the file */
5732 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005733 if( rc!=SQLITE_OK ){
5734 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005735 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005736 return rc;
5737 }
drhad4f1e52011-03-04 15:43:57 +00005738 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005739 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005740 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5741 /* Failed to open the file for read/write access. Try read-only. */
5742 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005743 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005744 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005745 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005746 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005747 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005748 }
5749 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005750 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005751 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005752 }
drhac7c3ac2012-02-11 19:23:48 +00005753
5754 /* If this process is running as root and if creating a new rollback
5755 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005756 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005757 */
5758 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005759 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005760 }
danielk1977b4b47412007-08-17 15:53:36 +00005761 }
dan08da86a2009-08-21 17:18:03 +00005762 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005763 if( pOutFlags ){
5764 *pOutFlags = flags;
5765 }
5766
dane946c392009-08-22 11:39:46 +00005767 if( p->pUnused ){
5768 p->pUnused->fd = fd;
5769 p->pUnused->flags = flags;
5770 }
5771
danielk1977b4b47412007-08-17 15:53:36 +00005772 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005773#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005774 zPath = zName;
5775#else
drh036ac7f2011-08-08 23:18:05 +00005776 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005777#endif
danielk1977b4b47412007-08-17 15:53:36 +00005778 }
drh41022642008-11-21 00:24:42 +00005779#if SQLITE_ENABLE_LOCKING_STYLE
5780 else{
dan08da86a2009-08-21 17:18:03 +00005781 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005782 }
5783#endif
5784
drhda0e7682008-07-30 15:27:54 +00005785 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005786
drh7ed97b92010-01-20 13:07:21 +00005787
5788#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005789 if( fstatfs(fd, &fsInfo) == -1 ){
5790 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005791 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005792 return SQLITE_IOERR_ACCESS;
5793 }
5794 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5795 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5796 }
5797#endif
drhc02a43a2012-01-10 23:18:38 +00005798
5799 /* Set up appropriate ctrlFlags */
5800 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5801 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5802 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5803 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5804 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5805
drh7ed97b92010-01-20 13:07:21 +00005806#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005807#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005808 isAutoProxy = 1;
5809#endif
5810 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005811 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5812 int useProxy = 0;
5813
dan08da86a2009-08-21 17:18:03 +00005814 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5815 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005816 if( envforce!=NULL ){
5817 useProxy = atoi(envforce)>0;
5818 }else{
aswiftaebf4132008-11-21 00:10:35 +00005819 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005820 /* In theory, the close(fd) call is sub-optimal. If the file opened
5821 ** with fd is a database file, and there are other connections open
5822 ** on that file that are currently holding advisory locks on it,
5823 ** then the call to close() will cancel those locks. In practice,
5824 ** we're assuming that statfs() doesn't fail very often. At least
5825 ** not while other file descriptors opened by the same process on
5826 ** the same file are working. */
5827 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005828 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005829 rc = SQLITE_IOERR_ACCESS;
5830 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005831 }
5832 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5833 }
5834 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005835 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005836 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005837 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005838 if( rc!=SQLITE_OK ){
5839 /* Use unixClose to clean up the resources added in fillInUnixFile
5840 ** and clear all the structure's references. Specifically,
5841 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5842 */
5843 unixClose(pFile);
5844 return rc;
5845 }
aswiftaebf4132008-11-21 00:10:35 +00005846 }
dane946c392009-08-22 11:39:46 +00005847 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005848 }
5849 }
5850#endif
5851
drhc02a43a2012-01-10 23:18:38 +00005852 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5853
dane946c392009-08-22 11:39:46 +00005854open_finished:
5855 if( rc!=SQLITE_OK ){
5856 sqlite3_free(p->pUnused);
5857 }
5858 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005859}
5860
dane946c392009-08-22 11:39:46 +00005861
danielk1977b4b47412007-08-17 15:53:36 +00005862/*
danielk1977fee2d252007-08-18 10:59:19 +00005863** Delete the file at zPath. If the dirSync argument is true, fsync()
5864** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005865*/
drh6b9d6dd2008-12-03 19:34:47 +00005866static int unixDelete(
5867 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5868 const char *zPath, /* Name of file to be deleted */
5869 int dirSync /* If true, fsync() directory after deleting file */
5870){
danielk1977fee2d252007-08-18 10:59:19 +00005871 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005872 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005873 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005874 if( osUnlink(zPath)==(-1) ){
5875 if( errno==ENOENT ){
5876 rc = SQLITE_IOERR_DELETE_NOENT;
5877 }else{
drhb4308162012-11-09 21:40:02 +00005878 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005879 }
drhb4308162012-11-09 21:40:02 +00005880 return rc;
drh5d4feff2010-07-14 01:45:22 +00005881 }
danielk1977d39fa702008-10-16 13:27:40 +00005882#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005883 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005884 int fd;
drh90315a22011-08-10 01:52:12 +00005885 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005886 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005887#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005888 if( fsync(fd)==-1 )
5889#else
5890 if( fsync(fd) )
5891#endif
5892 {
dane18d4952011-02-21 11:46:24 +00005893 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005894 }
drh0e9365c2011-03-02 02:08:13 +00005895 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005896 }else if( rc==SQLITE_CANTOPEN ){
5897 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005898 }
5899 }
danielk1977d138dd82008-10-15 16:02:48 +00005900#endif
danielk1977fee2d252007-08-18 10:59:19 +00005901 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005902}
5903
danielk197790949c22007-08-17 16:50:38 +00005904/*
mistachkin48864df2013-03-21 21:20:32 +00005905** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005906** test performed depends on the value of flags:
5907**
5908** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5909** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5910** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5911**
5912** Otherwise return 0.
5913*/
danielk1977861f7452008-06-05 11:39:11 +00005914static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005915 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5916 const char *zPath, /* Path of the file to examine */
5917 int flags, /* What do we want to learn about the zPath file? */
5918 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005919){
rse25c0d1a2007-09-20 08:38:14 +00005920 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005921 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005922 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005923 switch( flags ){
5924 case SQLITE_ACCESS_EXISTS:
5925 amode = F_OK;
5926 break;
5927 case SQLITE_ACCESS_READWRITE:
5928 amode = W_OK|R_OK;
5929 break;
drh50d3f902007-08-27 21:10:36 +00005930 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005931 amode = R_OK;
5932 break;
5933
5934 default:
5935 assert(!"Invalid flags argument");
5936 }
drh99ab3b12011-03-02 15:09:07 +00005937 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005938 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5939 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005940 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005941 *pResOut = 0;
5942 }
5943 }
danielk1977861f7452008-06-05 11:39:11 +00005944 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005945}
5946
danielk1977b4b47412007-08-17 15:53:36 +00005947
5948/*
5949** Turn a relative pathname into a full pathname. The relative path
5950** is stored as a nul-terminated string in the buffer pointed to by
5951** zPath.
5952**
5953** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5954** (in this case, MAX_PATHNAME bytes). The full-path is written to
5955** this buffer before returning.
5956*/
danielk1977adfb9b02007-09-17 07:02:56 +00005957static int unixFullPathname(
5958 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5959 const char *zPath, /* Possibly relative input path */
5960 int nOut, /* Size of output buffer in bytes */
5961 char *zOut /* Output buffer */
5962){
danielk1977843e65f2007-09-01 16:16:15 +00005963
5964 /* It's odd to simulate an io-error here, but really this is just
5965 ** using the io-error infrastructure to test that SQLite handles this
5966 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005967 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005968 */
5969 SimulateIOError( return SQLITE_ERROR );
5970
drh153c62c2007-08-24 03:51:33 +00005971 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005972 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005973
drh3c7f2dc2007-12-06 13:26:20 +00005974 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005975 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005976 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005977 }else{
5978 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005979 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005980 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005981 }
drhea678832008-12-10 19:26:22 +00005982 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005983 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005984 }
5985 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005986}
5987
drh0ccebe72005-06-07 22:22:50 +00005988
drh761df872006-12-21 01:29:22 +00005989#ifndef SQLITE_OMIT_LOAD_EXTENSION
5990/*
5991** Interfaces for opening a shared library, finding entry points
5992** within the shared library, and closing the shared library.
5993*/
5994#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005995static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5996 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005997 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5998}
danielk197795c8a542007-09-01 06:51:27 +00005999
6000/*
6001** SQLite calls this function immediately after a call to unixDlSym() or
6002** unixDlOpen() fails (returns a null pointer). If a more detailed error
6003** message is available, it is written to zBufOut. If no error message
6004** is available, zBufOut is left unmodified and SQLite uses a default
6005** error message.
6006*/
danielk1977397d65f2008-11-19 11:35:39 +00006007static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006008 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006009 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006010 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006011 zErr = dlerror();
6012 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006013 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006014 }
drh6c7d5c52008-11-21 20:32:33 +00006015 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006016}
drh1875f7a2008-12-08 18:19:17 +00006017static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6018 /*
6019 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6020 ** cast into a pointer to a function. And yet the library dlsym() routine
6021 ** returns a void* which is really a pointer to a function. So how do we
6022 ** use dlsym() with -pedantic-errors?
6023 **
6024 ** Variable x below is defined to be a pointer to a function taking
6025 ** parameters void* and const char* and returning a pointer to a function.
6026 ** We initialize x by assigning it a pointer to the dlsym() function.
6027 ** (That assignment requires a cast.) Then we call the function that
6028 ** x points to.
6029 **
6030 ** This work-around is unlikely to work correctly on any system where
6031 ** you really cannot cast a function pointer into void*. But then, on the
6032 ** other hand, dlsym() will not work on such a system either, so we have
6033 ** not really lost anything.
6034 */
6035 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006036 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006037 x = (void(*(*)(void*,const char*))(void))dlsym;
6038 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006039}
danielk1977397d65f2008-11-19 11:35:39 +00006040static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6041 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006042 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006043}
danielk1977b4b47412007-08-17 15:53:36 +00006044#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6045 #define unixDlOpen 0
6046 #define unixDlError 0
6047 #define unixDlSym 0
6048 #define unixDlClose 0
6049#endif
6050
6051/*
danielk197790949c22007-08-17 16:50:38 +00006052** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006053*/
danielk1977397d65f2008-11-19 11:35:39 +00006054static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6055 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006056 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006057
drhbbd42a62004-05-22 17:41:58 +00006058 /* We have to initialize zBuf to prevent valgrind from reporting
6059 ** errors. The reports issued by valgrind are incorrect - we would
6060 ** prefer that the randomness be increased by making use of the
6061 ** uninitialized space in zBuf - but valgrind errors tend to worry
6062 ** some users. Rather than argue, it seems easier just to initialize
6063 ** the whole array and silence valgrind, even if that means less randomness
6064 ** in the random seed.
6065 **
6066 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006067 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006068 ** tests repeatable.
6069 */
danielk1977b4b47412007-08-17 15:53:36 +00006070 memset(zBuf, 0, nBuf);
drhb00d8622014-01-01 15:18:36 +00006071 randomnessPid = getpid();
drhbbd42a62004-05-22 17:41:58 +00006072#if !defined(SQLITE_TEST)
6073 {
drhb00d8622014-01-01 15:18:36 +00006074 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006075 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006076 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006077 time_t t;
6078 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006079 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006080 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6081 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6082 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006083 }else{
drhc18b4042012-02-10 03:10:27 +00006084 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006085 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006086 }
drhbbd42a62004-05-22 17:41:58 +00006087 }
6088#endif
drh72cbd072008-10-14 17:58:38 +00006089 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006090}
6091
danielk1977b4b47412007-08-17 15:53:36 +00006092
drhbbd42a62004-05-22 17:41:58 +00006093/*
6094** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006095** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006096** The return value is the number of microseconds of sleep actually
6097** requested from the underlying operating system, a number which
6098** might be greater than or equal to the argument, but not less
6099** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006100*/
danielk1977397d65f2008-11-19 11:35:39 +00006101static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006102#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006103 struct timespec sp;
6104
6105 sp.tv_sec = microseconds / 1000000;
6106 sp.tv_nsec = (microseconds % 1000000) * 1000;
6107 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006108 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006109 return microseconds;
6110#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006111 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006112 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006113 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006114#else
danielk1977b4b47412007-08-17 15:53:36 +00006115 int seconds = (microseconds+999999)/1000000;
6116 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006117 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006118 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006119#endif
drh88f474a2006-01-02 20:00:12 +00006120}
6121
6122/*
drh6b9d6dd2008-12-03 19:34:47 +00006123** The following variable, if set to a non-zero value, is interpreted as
6124** the number of seconds since 1970 and is used to set the result of
6125** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006126*/
6127#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006128int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006129#endif
6130
6131/*
drhb7e8ea22010-05-03 14:32:30 +00006132** Find the current time (in Universal Coordinated Time). Write into *piNow
6133** the current time and date as a Julian Day number times 86_400_000. In
6134** other words, write into *piNow the number of milliseconds since the Julian
6135** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6136** proleptic Gregorian calendar.
6137**
drh31702252011-10-12 23:13:43 +00006138** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6139** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006140*/
6141static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6142 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006143 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006144#if defined(NO_GETTOD)
6145 time_t t;
6146 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006147 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006148#elif OS_VXWORKS
6149 struct timespec sNow;
6150 clock_gettime(CLOCK_REALTIME, &sNow);
6151 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6152#else
6153 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006154 if( gettimeofday(&sNow, 0)==0 ){
6155 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6156 }else{
6157 rc = SQLITE_ERROR;
6158 }
drhb7e8ea22010-05-03 14:32:30 +00006159#endif
6160
6161#ifdef SQLITE_TEST
6162 if( sqlite3_current_time ){
6163 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6164 }
6165#endif
6166 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006167 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006168}
6169
6170/*
drhbbd42a62004-05-22 17:41:58 +00006171** Find the current time (in Universal Coordinated Time). Write the
6172** current time and date as a Julian Day number into *prNow and
6173** return 0. Return 1 if the time and date cannot be found.
6174*/
danielk1977397d65f2008-11-19 11:35:39 +00006175static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006176 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006177 int rc;
drhff828942010-06-26 21:34:06 +00006178 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006179 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006180 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006181 return rc;
drhbbd42a62004-05-22 17:41:58 +00006182}
danielk1977b4b47412007-08-17 15:53:36 +00006183
drh6b9d6dd2008-12-03 19:34:47 +00006184/*
6185** We added the xGetLastError() method with the intention of providing
6186** better low-level error messages when operating-system problems come up
6187** during SQLite operation. But so far, none of that has been implemented
6188** in the core. So this routine is never called. For now, it is merely
6189** a place-holder.
6190*/
danielk1977397d65f2008-11-19 11:35:39 +00006191static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6192 UNUSED_PARAMETER(NotUsed);
6193 UNUSED_PARAMETER(NotUsed2);
6194 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006195 return 0;
6196}
6197
drhf2424c52010-04-26 00:04:55 +00006198
6199/*
drh734c9862008-11-28 15:37:20 +00006200************************ End of sqlite3_vfs methods ***************************
6201******************************************************************************/
6202
drh715ff302008-12-03 22:32:44 +00006203/******************************************************************************
6204************************** Begin Proxy Locking ********************************
6205**
6206** Proxy locking is a "uber-locking-method" in this sense: It uses the
6207** other locking methods on secondary lock files. Proxy locking is a
6208** meta-layer over top of the primitive locking implemented above. For
6209** this reason, the division that implements of proxy locking is deferred
6210** until late in the file (here) after all of the other I/O methods have
6211** been defined - so that the primitive locking methods are available
6212** as services to help with the implementation of proxy locking.
6213**
6214****
6215**
6216** The default locking schemes in SQLite use byte-range locks on the
6217** database file to coordinate safe, concurrent access by multiple readers
6218** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6219** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6220** as POSIX read & write locks over fixed set of locations (via fsctl),
6221** on AFP and SMB only exclusive byte-range locks are available via fsctl
6222** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6223** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6224** address in the shared range is taken for a SHARED lock, the entire
6225** shared range is taken for an EXCLUSIVE lock):
6226**
drhf2f105d2012-08-20 15:53:54 +00006227** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006228** RESERVED_BYTE 0x40000001
6229** SHARED_RANGE 0x40000002 -> 0x40000200
6230**
6231** This works well on the local file system, but shows a nearly 100x
6232** slowdown in read performance on AFP because the AFP client disables
6233** the read cache when byte-range locks are present. Enabling the read
6234** cache exposes a cache coherency problem that is present on all OS X
6235** supported network file systems. NFS and AFP both observe the
6236** close-to-open semantics for ensuring cache coherency
6237** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6238** address the requirements for concurrent database access by multiple
6239** readers and writers
6240** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6241**
6242** To address the performance and cache coherency issues, proxy file locking
6243** changes the way database access is controlled by limiting access to a
6244** single host at a time and moving file locks off of the database file
6245** and onto a proxy file on the local file system.
6246**
6247**
6248** Using proxy locks
6249** -----------------
6250**
6251** C APIs
6252**
6253** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6254** <proxy_path> | ":auto:");
6255** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6256**
6257**
6258** SQL pragmas
6259**
6260** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6261** PRAGMA [database.]lock_proxy_file
6262**
6263** Specifying ":auto:" means that if there is a conch file with a matching
6264** host ID in it, the proxy path in the conch file will be used, otherwise
6265** a proxy path based on the user's temp dir
6266** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6267** actual proxy file name is generated from the name and path of the
6268** database file. For example:
6269**
6270** For database path "/Users/me/foo.db"
6271** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6272**
6273** Once a lock proxy is configured for a database connection, it can not
6274** be removed, however it may be switched to a different proxy path via
6275** the above APIs (assuming the conch file is not being held by another
6276** connection or process).
6277**
6278**
6279** How proxy locking works
6280** -----------------------
6281**
6282** Proxy file locking relies primarily on two new supporting files:
6283**
6284** * conch file to limit access to the database file to a single host
6285** at a time
6286**
6287** * proxy file to act as a proxy for the advisory locks normally
6288** taken on the database
6289**
6290** The conch file - to use a proxy file, sqlite must first "hold the conch"
6291** by taking an sqlite-style shared lock on the conch file, reading the
6292** contents and comparing the host's unique host ID (see below) and lock
6293** proxy path against the values stored in the conch. The conch file is
6294** stored in the same directory as the database file and the file name
6295** is patterned after the database file name as ".<databasename>-conch".
6296** If the conch file does not exist, or it's contents do not match the
6297** host ID and/or proxy path, then the lock is escalated to an exclusive
6298** lock and the conch file contents is updated with the host ID and proxy
6299** path and the lock is downgraded to a shared lock again. If the conch
6300** is held by another process (with a shared lock), the exclusive lock
6301** will fail and SQLITE_BUSY is returned.
6302**
6303** The proxy file - a single-byte file used for all advisory file locks
6304** normally taken on the database file. This allows for safe sharing
6305** of the database file for multiple readers and writers on the same
6306** host (the conch ensures that they all use the same local lock file).
6307**
drh715ff302008-12-03 22:32:44 +00006308** Requesting the lock proxy does not immediately take the conch, it is
6309** only taken when the first request to lock database file is made.
6310** This matches the semantics of the traditional locking behavior, where
6311** opening a connection to a database file does not take a lock on it.
6312** The shared lock and an open file descriptor are maintained until
6313** the connection to the database is closed.
6314**
6315** The proxy file and the lock file are never deleted so they only need
6316** to be created the first time they are used.
6317**
6318** Configuration options
6319** ---------------------
6320**
6321** SQLITE_PREFER_PROXY_LOCKING
6322**
6323** Database files accessed on non-local file systems are
6324** automatically configured for proxy locking, lock files are
6325** named automatically using the same logic as
6326** PRAGMA lock_proxy_file=":auto:"
6327**
6328** SQLITE_PROXY_DEBUG
6329**
6330** Enables the logging of error messages during host id file
6331** retrieval and creation
6332**
drh715ff302008-12-03 22:32:44 +00006333** LOCKPROXYDIR
6334**
6335** Overrides the default directory used for lock proxy files that
6336** are named automatically via the ":auto:" setting
6337**
6338** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6339**
6340** Permissions to use when creating a directory for storing the
6341** lock proxy files, only used when LOCKPROXYDIR is not set.
6342**
6343**
6344** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6345** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6346** force proxy locking to be used for every database file opened, and 0
6347** will force automatic proxy locking to be disabled for all database
6348** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6349** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6350*/
6351
6352/*
6353** Proxy locking is only available on MacOSX
6354*/
drhd2cb50b2009-01-09 21:41:17 +00006355#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006356
drh715ff302008-12-03 22:32:44 +00006357/*
6358** The proxyLockingContext has the path and file structures for the remote
6359** and local proxy files in it
6360*/
6361typedef struct proxyLockingContext proxyLockingContext;
6362struct proxyLockingContext {
6363 unixFile *conchFile; /* Open conch file */
6364 char *conchFilePath; /* Name of the conch file */
6365 unixFile *lockProxy; /* Open proxy lock file */
6366 char *lockProxyPath; /* Name of the proxy lock file */
6367 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006368 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006369 void *oldLockingContext; /* Original lockingcontext to restore on close */
6370 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6371};
6372
drh7ed97b92010-01-20 13:07:21 +00006373/*
6374** The proxy lock file path for the database at dbPath is written into lPath,
6375** which must point to valid, writable memory large enough for a maxLen length
6376** file path.
drh715ff302008-12-03 22:32:44 +00006377*/
drh715ff302008-12-03 22:32:44 +00006378static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6379 int len;
6380 int dbLen;
6381 int i;
6382
6383#ifdef LOCKPROXYDIR
6384 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6385#else
6386# ifdef _CS_DARWIN_USER_TEMP_DIR
6387 {
drh7ed97b92010-01-20 13:07:21 +00006388 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006389 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6390 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006391 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006392 }
drh7ed97b92010-01-20 13:07:21 +00006393 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006394 }
6395# else
6396 len = strlcpy(lPath, "/tmp/", maxLen);
6397# endif
6398#endif
6399
6400 if( lPath[len-1]!='/' ){
6401 len = strlcat(lPath, "/", maxLen);
6402 }
6403
6404 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006405 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006406 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006407 char c = dbPath[i];
6408 lPath[i+len] = (c=='/')?'_':c;
6409 }
6410 lPath[i+len]='\0';
6411 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006412 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006413 return SQLITE_OK;
6414}
6415
drh7ed97b92010-01-20 13:07:21 +00006416/*
6417 ** Creates the lock file and any missing directories in lockPath
6418 */
6419static int proxyCreateLockPath(const char *lockPath){
6420 int i, len;
6421 char buf[MAXPATHLEN];
6422 int start = 0;
6423
6424 assert(lockPath!=NULL);
6425 /* try to create all the intermediate directories */
6426 len = (int)strlen(lockPath);
6427 buf[0] = lockPath[0];
6428 for( i=1; i<len; i++ ){
6429 if( lockPath[i] == '/' && (i - start > 0) ){
6430 /* only mkdir if leaf dir != "." or "/" or ".." */
6431 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6432 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6433 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006434 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006435 int err=errno;
6436 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006437 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006438 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006439 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006440 return err;
6441 }
6442 }
6443 }
6444 start=i+1;
6445 }
6446 buf[i] = lockPath[i];
6447 }
drh308c2a52010-05-14 11:30:18 +00006448 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006449 return 0;
6450}
6451
drh715ff302008-12-03 22:32:44 +00006452/*
6453** Create a new VFS file descriptor (stored in memory obtained from
6454** sqlite3_malloc) and open the file named "path" in the file descriptor.
6455**
6456** The caller is responsible not only for closing the file descriptor
6457** but also for freeing the memory associated with the file descriptor.
6458*/
drh7ed97b92010-01-20 13:07:21 +00006459static int proxyCreateUnixFile(
6460 const char *path, /* path for the new unixFile */
6461 unixFile **ppFile, /* unixFile created and returned by ref */
6462 int islockfile /* if non zero missing dirs will be created */
6463) {
6464 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006465 unixFile *pNew;
6466 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006467 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006468 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006469 int terrno = 0;
6470 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006471
drh7ed97b92010-01-20 13:07:21 +00006472 /* 1. first try to open/create the file
6473 ** 2. if that fails, and this is a lock file (not-conch), try creating
6474 ** the parent directories and then try again.
6475 ** 3. if that fails, try to open the file read-only
6476 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6477 */
6478 pUnused = findReusableFd(path, openFlags);
6479 if( pUnused ){
6480 fd = pUnused->fd;
6481 }else{
6482 pUnused = sqlite3_malloc(sizeof(*pUnused));
6483 if( !pUnused ){
6484 return SQLITE_NOMEM;
6485 }
6486 }
6487 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006488 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006489 terrno = errno;
6490 if( fd<0 && errno==ENOENT && islockfile ){
6491 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006492 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006493 }
6494 }
6495 }
6496 if( fd<0 ){
6497 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006498 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006499 terrno = errno;
6500 }
6501 if( fd<0 ){
6502 if( islockfile ){
6503 return SQLITE_BUSY;
6504 }
6505 switch (terrno) {
6506 case EACCES:
6507 return SQLITE_PERM;
6508 case EIO:
6509 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6510 default:
drh9978c972010-02-23 17:36:32 +00006511 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006512 }
6513 }
6514
6515 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6516 if( pNew==NULL ){
6517 rc = SQLITE_NOMEM;
6518 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006519 }
6520 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006521 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006522 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006523 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006524 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006525 pUnused->fd = fd;
6526 pUnused->flags = openFlags;
6527 pNew->pUnused = pUnused;
6528
drhc02a43a2012-01-10 23:18:38 +00006529 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006530 if( rc==SQLITE_OK ){
6531 *ppFile = pNew;
6532 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006533 }
drh7ed97b92010-01-20 13:07:21 +00006534end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006535 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006536 sqlite3_free(pNew);
6537 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006538 return rc;
6539}
6540
drh7ed97b92010-01-20 13:07:21 +00006541#ifdef SQLITE_TEST
6542/* simulate multiple hosts by creating unique hostid file paths */
6543int sqlite3_hostid_num = 0;
6544#endif
6545
6546#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6547
drh0ab216a2010-07-02 17:10:40 +00006548/* Not always defined in the headers as it ought to be */
6549extern int gethostuuid(uuid_t id, const struct timespec *wait);
6550
drh7ed97b92010-01-20 13:07:21 +00006551/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6552** bytes of writable memory.
6553*/
6554static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006555 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6556 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006557#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6558 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006559 {
6560 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6561 if( gethostuuid(pHostID, &timeout) ){
6562 int err = errno;
6563 if( pError ){
6564 *pError = err;
6565 }
6566 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006567 }
drh7ed97b92010-01-20 13:07:21 +00006568 }
drh3d4435b2011-08-26 20:55:50 +00006569#else
6570 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006571#endif
drh7ed97b92010-01-20 13:07:21 +00006572#ifdef SQLITE_TEST
6573 /* simulate multiple hosts by creating unique hostid file paths */
6574 if( sqlite3_hostid_num != 0){
6575 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6576 }
6577#endif
6578
6579 return SQLITE_OK;
6580}
6581
6582/* The conch file contains the header, host id and lock file path
6583 */
6584#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6585#define PROXY_HEADERLEN 1 /* conch file header length */
6586#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6587#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6588
6589/*
6590** Takes an open conch file, copies the contents to a new path and then moves
6591** it back. The newly created file's file descriptor is assigned to the
6592** conch file structure and finally the original conch file descriptor is
6593** closed. Returns zero if successful.
6594*/
6595static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6596 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6597 unixFile *conchFile = pCtx->conchFile;
6598 char tPath[MAXPATHLEN];
6599 char buf[PROXY_MAXCONCHLEN];
6600 char *cPath = pCtx->conchFilePath;
6601 size_t readLen = 0;
6602 size_t pathLen = 0;
6603 char errmsg[64] = "";
6604 int fd = -1;
6605 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006606 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006607
6608 /* create a new path by replace the trailing '-conch' with '-break' */
6609 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6610 if( pathLen>MAXPATHLEN || pathLen<6 ||
6611 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006612 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006613 goto end_breaklock;
6614 }
6615 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006616 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006617 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006618 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006619 goto end_breaklock;
6620 }
6621 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006622 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006623 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006624 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006625 goto end_breaklock;
6626 }
drhe562be52011-03-02 18:01:10 +00006627 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006628 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006629 goto end_breaklock;
6630 }
6631 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006632 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006633 goto end_breaklock;
6634 }
6635 rc = 0;
6636 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006637 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006638 conchFile->h = fd;
6639 conchFile->openFlags = O_RDWR | O_CREAT;
6640
6641end_breaklock:
6642 if( rc ){
6643 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006644 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006645 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006646 }
6647 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6648 }
6649 return rc;
6650}
6651
6652/* Take the requested lock on the conch file and break a stale lock if the
6653** host id matches.
6654*/
6655static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6656 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6657 unixFile *conchFile = pCtx->conchFile;
6658 int rc = SQLITE_OK;
6659 int nTries = 0;
6660 struct timespec conchModTime;
6661
drh3d4435b2011-08-26 20:55:50 +00006662 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006663 do {
6664 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6665 nTries ++;
6666 if( rc==SQLITE_BUSY ){
6667 /* If the lock failed (busy):
6668 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6669 * 2nd try: fail if the mod time changed or host id is different, wait
6670 * 10 sec and try again
6671 * 3rd try: break the lock unless the mod time has changed.
6672 */
6673 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006674 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006675 pFile->lastErrno = errno;
6676 return SQLITE_IOERR_LOCK;
6677 }
6678
6679 if( nTries==1 ){
6680 conchModTime = buf.st_mtimespec;
6681 usleep(500000); /* wait 0.5 sec and try the lock again*/
6682 continue;
6683 }
6684
6685 assert( nTries>1 );
6686 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6687 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6688 return SQLITE_BUSY;
6689 }
6690
6691 if( nTries==2 ){
6692 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006693 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006694 if( len<0 ){
6695 pFile->lastErrno = errno;
6696 return SQLITE_IOERR_LOCK;
6697 }
6698 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6699 /* don't break the lock if the host id doesn't match */
6700 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6701 return SQLITE_BUSY;
6702 }
6703 }else{
6704 /* don't break the lock on short read or a version mismatch */
6705 return SQLITE_BUSY;
6706 }
6707 usleep(10000000); /* wait 10 sec and try the lock again */
6708 continue;
6709 }
6710
6711 assert( nTries==3 );
6712 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6713 rc = SQLITE_OK;
6714 if( lockType==EXCLUSIVE_LOCK ){
6715 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6716 }
6717 if( !rc ){
6718 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6719 }
6720 }
6721 }
6722 } while( rc==SQLITE_BUSY && nTries<3 );
6723
6724 return rc;
6725}
6726
6727/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006728** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6729** lockPath means that the lockPath in the conch file will be used if the
6730** host IDs match, or a new lock path will be generated automatically
6731** and written to the conch file.
6732*/
6733static int proxyTakeConch(unixFile *pFile){
6734 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6735
drh7ed97b92010-01-20 13:07:21 +00006736 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006737 return SQLITE_OK;
6738 }else{
6739 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006740 uuid_t myHostID;
6741 int pError = 0;
6742 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006743 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006744 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006745 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006746 int createConch = 0;
6747 int hostIdMatch = 0;
6748 int readLen = 0;
6749 int tryOldLockPath = 0;
6750 int forceNewLockPath = 0;
6751
drh308c2a52010-05-14 11:30:18 +00006752 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6753 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006754
drh7ed97b92010-01-20 13:07:21 +00006755 rc = proxyGetHostID(myHostID, &pError);
6756 if( (rc&0xff)==SQLITE_IOERR ){
6757 pFile->lastErrno = pError;
6758 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006759 }
drh7ed97b92010-01-20 13:07:21 +00006760 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006761 if( rc!=SQLITE_OK ){
6762 goto end_takeconch;
6763 }
drh7ed97b92010-01-20 13:07:21 +00006764 /* read the existing conch file */
6765 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6766 if( readLen<0 ){
6767 /* I/O error: lastErrno set by seekAndRead */
6768 pFile->lastErrno = conchFile->lastErrno;
6769 rc = SQLITE_IOERR_READ;
6770 goto end_takeconch;
6771 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6772 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6773 /* a short read or version format mismatch means we need to create a new
6774 ** conch file.
6775 */
6776 createConch = 1;
6777 }
6778 /* if the host id matches and the lock path already exists in the conch
6779 ** we'll try to use the path there, if we can't open that path, we'll
6780 ** retry with a new auto-generated path
6781 */
6782 do { /* in case we need to try again for an :auto: named lock file */
6783
6784 if( !createConch && !forceNewLockPath ){
6785 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6786 PROXY_HOSTIDLEN);
6787 /* if the conch has data compare the contents */
6788 if( !pCtx->lockProxyPath ){
6789 /* for auto-named local lock file, just check the host ID and we'll
6790 ** use the local lock file path that's already in there
6791 */
6792 if( hostIdMatch ){
6793 size_t pathLen = (readLen - PROXY_PATHINDEX);
6794
6795 if( pathLen>=MAXPATHLEN ){
6796 pathLen=MAXPATHLEN-1;
6797 }
6798 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6799 lockPath[pathLen] = 0;
6800 tempLockPath = lockPath;
6801 tryOldLockPath = 1;
6802 /* create a copy of the lock path if the conch is taken */
6803 goto end_takeconch;
6804 }
6805 }else if( hostIdMatch
6806 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6807 readLen-PROXY_PATHINDEX)
6808 ){
6809 /* conch host and lock path match */
6810 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006811 }
drh7ed97b92010-01-20 13:07:21 +00006812 }
6813
6814 /* if the conch isn't writable and doesn't match, we can't take it */
6815 if( (conchFile->openFlags&O_RDWR) == 0 ){
6816 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006817 goto end_takeconch;
6818 }
drh7ed97b92010-01-20 13:07:21 +00006819
6820 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006821 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006822 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6823 tempLockPath = lockPath;
6824 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006825 }
drh7ed97b92010-01-20 13:07:21 +00006826
6827 /* update conch with host and path (this will fail if other process
6828 ** has a shared lock already), if the host id matches, use the big
6829 ** stick.
drh715ff302008-12-03 22:32:44 +00006830 */
drh7ed97b92010-01-20 13:07:21 +00006831 futimes(conchFile->h, NULL);
6832 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006833 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006834 /* We are trying for an exclusive lock but another thread in this
6835 ** same process is still holding a shared lock. */
6836 rc = SQLITE_BUSY;
6837 } else {
6838 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006839 }
drh715ff302008-12-03 22:32:44 +00006840 }else{
drh7ed97b92010-01-20 13:07:21 +00006841 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006842 }
drh7ed97b92010-01-20 13:07:21 +00006843 if( rc==SQLITE_OK ){
6844 char writeBuffer[PROXY_MAXCONCHLEN];
6845 int writeSize = 0;
6846
6847 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6848 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6849 if( pCtx->lockProxyPath!=NULL ){
6850 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6851 }else{
6852 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6853 }
6854 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006855 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006856 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6857 fsync(conchFile->h);
6858 /* If we created a new conch file (not just updated the contents of a
6859 ** valid conch file), try to match the permissions of the database
6860 */
6861 if( rc==SQLITE_OK && createConch ){
6862 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006863 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006864 if( err==0 ){
6865 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6866 S_IROTH|S_IWOTH);
6867 /* try to match the database file R/W permissions, ignore failure */
6868#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006869 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006870#else
drhff812312011-02-23 13:33:46 +00006871 do{
drhe562be52011-03-02 18:01:10 +00006872 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006873 }while( rc==(-1) && errno==EINTR );
6874 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006875 int code = errno;
6876 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6877 cmode, code, strerror(code));
6878 } else {
6879 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6880 }
6881 }else{
6882 int code = errno;
6883 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6884 err, code, strerror(code));
6885#endif
6886 }
drh715ff302008-12-03 22:32:44 +00006887 }
6888 }
drh7ed97b92010-01-20 13:07:21 +00006889 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6890
6891 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006892 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006893 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006894 int fd;
drh7ed97b92010-01-20 13:07:21 +00006895 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006896 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006897 }
6898 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006899 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006900 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006901 if( fd>=0 ){
6902 pFile->h = fd;
6903 }else{
drh9978c972010-02-23 17:36:32 +00006904 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006905 during locking */
6906 }
6907 }
6908 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6909 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6910 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6911 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6912 /* we couldn't create the proxy lock file with the old lock file path
6913 ** so try again via auto-naming
6914 */
6915 forceNewLockPath = 1;
6916 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006917 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006918 }
6919 }
6920 if( rc==SQLITE_OK ){
6921 /* Need to make a copy of path if we extracted the value
6922 ** from the conch file or the path was allocated on the stack
6923 */
6924 if( tempLockPath ){
6925 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6926 if( !pCtx->lockProxyPath ){
6927 rc = SQLITE_NOMEM;
6928 }
6929 }
6930 }
6931 if( rc==SQLITE_OK ){
6932 pCtx->conchHeld = 1;
6933
6934 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6935 afpLockingContext *afpCtx;
6936 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6937 afpCtx->dbPath = pCtx->lockProxyPath;
6938 }
6939 } else {
6940 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6941 }
drh308c2a52010-05-14 11:30:18 +00006942 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6943 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006944 return rc;
drh308c2a52010-05-14 11:30:18 +00006945 } while (1); /* in case we need to retry the :auto: lock file -
6946 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006947 }
6948}
6949
6950/*
6951** If pFile holds a lock on a conch file, then release that lock.
6952*/
6953static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006954 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006955 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6956 unixFile *conchFile; /* Name of the conch file */
6957
6958 pCtx = (proxyLockingContext *)pFile->lockingContext;
6959 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006960 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006961 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006962 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006963 if( pCtx->conchHeld>0 ){
6964 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6965 }
drh715ff302008-12-03 22:32:44 +00006966 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006967 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6968 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006969 return rc;
6970}
6971
6972/*
6973** Given the name of a database file, compute the name of its conch file.
6974** Store the conch filename in memory obtained from sqlite3_malloc().
6975** Make *pConchPath point to the new name. Return SQLITE_OK on success
6976** or SQLITE_NOMEM if unable to obtain memory.
6977**
6978** The caller is responsible for ensuring that the allocated memory
6979** space is eventually freed.
6980**
6981** *pConchPath is set to NULL if a memory allocation error occurs.
6982*/
6983static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6984 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006985 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006986 char *conchPath; /* buffer in which to construct conch name */
6987
6988 /* Allocate space for the conch filename and initialize the name to
6989 ** the name of the original database file. */
6990 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6991 if( conchPath==0 ){
6992 return SQLITE_NOMEM;
6993 }
6994 memcpy(conchPath, dbPath, len+1);
6995
6996 /* now insert a "." before the last / character */
6997 for( i=(len-1); i>=0; i-- ){
6998 if( conchPath[i]=='/' ){
6999 i++;
7000 break;
7001 }
7002 }
7003 conchPath[i]='.';
7004 while ( i<len ){
7005 conchPath[i+1]=dbPath[i];
7006 i++;
7007 }
7008
7009 /* append the "-conch" suffix to the file */
7010 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007011 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007012
7013 return SQLITE_OK;
7014}
7015
7016
7017/* Takes a fully configured proxy locking-style unix file and switches
7018** the local lock file path
7019*/
7020static int switchLockProxyPath(unixFile *pFile, const char *path) {
7021 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7022 char *oldPath = pCtx->lockProxyPath;
7023 int rc = SQLITE_OK;
7024
drh308c2a52010-05-14 11:30:18 +00007025 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007026 return SQLITE_BUSY;
7027 }
7028
7029 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7030 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7031 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7032 return SQLITE_OK;
7033 }else{
7034 unixFile *lockProxy = pCtx->lockProxy;
7035 pCtx->lockProxy=NULL;
7036 pCtx->conchHeld = 0;
7037 if( lockProxy!=NULL ){
7038 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7039 if( rc ) return rc;
7040 sqlite3_free(lockProxy);
7041 }
7042 sqlite3_free(oldPath);
7043 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7044 }
7045
7046 return rc;
7047}
7048
7049/*
7050** pFile is a file that has been opened by a prior xOpen call. dbPath
7051** is a string buffer at least MAXPATHLEN+1 characters in size.
7052**
7053** This routine find the filename associated with pFile and writes it
7054** int dbPath.
7055*/
7056static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007057#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007058 if( pFile->pMethod == &afpIoMethods ){
7059 /* afp style keeps a reference to the db path in the filePath field
7060 ** of the struct */
drhea678832008-12-10 19:26:22 +00007061 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007062 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7063 } else
drh715ff302008-12-03 22:32:44 +00007064#endif
7065 if( pFile->pMethod == &dotlockIoMethods ){
7066 /* dot lock style uses the locking context to store the dot lock
7067 ** file path */
7068 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7069 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7070 }else{
7071 /* all other styles use the locking context to store the db file path */
7072 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007073 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007074 }
7075 return SQLITE_OK;
7076}
7077
7078/*
7079** Takes an already filled in unix file and alters it so all file locking
7080** will be performed on the local proxy lock file. The following fields
7081** are preserved in the locking context so that they can be restored and
7082** the unix structure properly cleaned up at close time:
7083** ->lockingContext
7084** ->pMethod
7085*/
7086static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7087 proxyLockingContext *pCtx;
7088 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7089 char *lockPath=NULL;
7090 int rc = SQLITE_OK;
7091
drh308c2a52010-05-14 11:30:18 +00007092 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007093 return SQLITE_BUSY;
7094 }
7095 proxyGetDbPathForUnixFile(pFile, dbPath);
7096 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7097 lockPath=NULL;
7098 }else{
7099 lockPath=(char *)path;
7100 }
7101
drh308c2a52010-05-14 11:30:18 +00007102 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7103 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007104
7105 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7106 if( pCtx==0 ){
7107 return SQLITE_NOMEM;
7108 }
7109 memset(pCtx, 0, sizeof(*pCtx));
7110
7111 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7112 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007113 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7114 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7115 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7116 ** (c) the file system is read-only, then enable no-locking access.
7117 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7118 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7119 */
7120 struct statfs fsInfo;
7121 struct stat conchInfo;
7122 int goLockless = 0;
7123
drh99ab3b12011-03-02 15:09:07 +00007124 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007125 int err = errno;
7126 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7127 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7128 }
7129 }
7130 if( goLockless ){
7131 pCtx->conchHeld = -1; /* read only FS/ lockless */
7132 rc = SQLITE_OK;
7133 }
7134 }
drh715ff302008-12-03 22:32:44 +00007135 }
7136 if( rc==SQLITE_OK && lockPath ){
7137 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7138 }
7139
7140 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007141 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7142 if( pCtx->dbPath==NULL ){
7143 rc = SQLITE_NOMEM;
7144 }
7145 }
7146 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007147 /* all memory is allocated, proxys are created and assigned,
7148 ** switch the locking context and pMethod then return.
7149 */
drh715ff302008-12-03 22:32:44 +00007150 pCtx->oldLockingContext = pFile->lockingContext;
7151 pFile->lockingContext = pCtx;
7152 pCtx->pOldMethod = pFile->pMethod;
7153 pFile->pMethod = &proxyIoMethods;
7154 }else{
7155 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007156 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007157 sqlite3_free(pCtx->conchFile);
7158 }
drhd56b1212010-08-11 06:14:15 +00007159 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007160 sqlite3_free(pCtx->conchFilePath);
7161 sqlite3_free(pCtx);
7162 }
drh308c2a52010-05-14 11:30:18 +00007163 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7164 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007165 return rc;
7166}
7167
7168
7169/*
7170** This routine handles sqlite3_file_control() calls that are specific
7171** to proxy locking.
7172*/
7173static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7174 switch( op ){
7175 case SQLITE_GET_LOCKPROXYFILE: {
7176 unixFile *pFile = (unixFile*)id;
7177 if( pFile->pMethod == &proxyIoMethods ){
7178 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7179 proxyTakeConch(pFile);
7180 if( pCtx->lockProxyPath ){
7181 *(const char **)pArg = pCtx->lockProxyPath;
7182 }else{
7183 *(const char **)pArg = ":auto: (not held)";
7184 }
7185 } else {
7186 *(const char **)pArg = NULL;
7187 }
7188 return SQLITE_OK;
7189 }
7190 case SQLITE_SET_LOCKPROXYFILE: {
7191 unixFile *pFile = (unixFile*)id;
7192 int rc = SQLITE_OK;
7193 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7194 if( pArg==NULL || (const char *)pArg==0 ){
7195 if( isProxyStyle ){
7196 /* turn off proxy locking - not supported */
7197 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7198 }else{
7199 /* turn off proxy locking - already off - NOOP */
7200 rc = SQLITE_OK;
7201 }
7202 }else{
7203 const char *proxyPath = (const char *)pArg;
7204 if( isProxyStyle ){
7205 proxyLockingContext *pCtx =
7206 (proxyLockingContext*)pFile->lockingContext;
7207 if( !strcmp(pArg, ":auto:")
7208 || (pCtx->lockProxyPath &&
7209 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7210 ){
7211 rc = SQLITE_OK;
7212 }else{
7213 rc = switchLockProxyPath(pFile, proxyPath);
7214 }
7215 }else{
7216 /* turn on proxy file locking */
7217 rc = proxyTransformUnixFile(pFile, proxyPath);
7218 }
7219 }
7220 return rc;
7221 }
7222 default: {
7223 assert( 0 ); /* The call assures that only valid opcodes are sent */
7224 }
7225 }
7226 /*NOTREACHED*/
7227 return SQLITE_ERROR;
7228}
7229
7230/*
7231** Within this division (the proxying locking implementation) the procedures
7232** above this point are all utilities. The lock-related methods of the
7233** proxy-locking sqlite3_io_method object follow.
7234*/
7235
7236
7237/*
7238** This routine checks if there is a RESERVED lock held on the specified
7239** file by this or any other process. If such a lock is held, set *pResOut
7240** to a non-zero value otherwise *pResOut is set to zero. The return value
7241** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7242*/
7243static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7244 unixFile *pFile = (unixFile*)id;
7245 int rc = proxyTakeConch(pFile);
7246 if( rc==SQLITE_OK ){
7247 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007248 if( pCtx->conchHeld>0 ){
7249 unixFile *proxy = pCtx->lockProxy;
7250 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7251 }else{ /* conchHeld < 0 is lockless */
7252 pResOut=0;
7253 }
drh715ff302008-12-03 22:32:44 +00007254 }
7255 return rc;
7256}
7257
7258/*
drh308c2a52010-05-14 11:30:18 +00007259** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007260** of the following:
7261**
7262** (1) SHARED_LOCK
7263** (2) RESERVED_LOCK
7264** (3) PENDING_LOCK
7265** (4) EXCLUSIVE_LOCK
7266**
7267** Sometimes when requesting one lock state, additional lock states
7268** are inserted in between. The locking might fail on one of the later
7269** transitions leaving the lock state different from what it started but
7270** still short of its goal. The following chart shows the allowed
7271** transitions and the inserted intermediate states:
7272**
7273** UNLOCKED -> SHARED
7274** SHARED -> RESERVED
7275** SHARED -> (PENDING) -> EXCLUSIVE
7276** RESERVED -> (PENDING) -> EXCLUSIVE
7277** PENDING -> EXCLUSIVE
7278**
7279** This routine will only increase a lock. Use the sqlite3OsUnlock()
7280** routine to lower a locking level.
7281*/
drh308c2a52010-05-14 11:30:18 +00007282static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007283 unixFile *pFile = (unixFile*)id;
7284 int rc = proxyTakeConch(pFile);
7285 if( rc==SQLITE_OK ){
7286 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007287 if( pCtx->conchHeld>0 ){
7288 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007289 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7290 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007291 }else{
7292 /* conchHeld < 0 is lockless */
7293 }
drh715ff302008-12-03 22:32:44 +00007294 }
7295 return rc;
7296}
7297
7298
7299/*
drh308c2a52010-05-14 11:30:18 +00007300** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007301** must be either NO_LOCK or SHARED_LOCK.
7302**
7303** If the locking level of the file descriptor is already at or below
7304** the requested locking level, this routine is a no-op.
7305*/
drh308c2a52010-05-14 11:30:18 +00007306static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007307 unixFile *pFile = (unixFile*)id;
7308 int rc = proxyTakeConch(pFile);
7309 if( rc==SQLITE_OK ){
7310 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007311 if( pCtx->conchHeld>0 ){
7312 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007313 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7314 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007315 }else{
7316 /* conchHeld < 0 is lockless */
7317 }
drh715ff302008-12-03 22:32:44 +00007318 }
7319 return rc;
7320}
7321
7322/*
7323** Close a file that uses proxy locks.
7324*/
7325static int proxyClose(sqlite3_file *id) {
7326 if( id ){
7327 unixFile *pFile = (unixFile*)id;
7328 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7329 unixFile *lockProxy = pCtx->lockProxy;
7330 unixFile *conchFile = pCtx->conchFile;
7331 int rc = SQLITE_OK;
7332
7333 if( lockProxy ){
7334 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7335 if( rc ) return rc;
7336 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7337 if( rc ) return rc;
7338 sqlite3_free(lockProxy);
7339 pCtx->lockProxy = 0;
7340 }
7341 if( conchFile ){
7342 if( pCtx->conchHeld ){
7343 rc = proxyReleaseConch(pFile);
7344 if( rc ) return rc;
7345 }
7346 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7347 if( rc ) return rc;
7348 sqlite3_free(conchFile);
7349 }
drhd56b1212010-08-11 06:14:15 +00007350 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007351 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007352 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007353 /* restore the original locking context and pMethod then close it */
7354 pFile->lockingContext = pCtx->oldLockingContext;
7355 pFile->pMethod = pCtx->pOldMethod;
7356 sqlite3_free(pCtx);
7357 return pFile->pMethod->xClose(id);
7358 }
7359 return SQLITE_OK;
7360}
7361
7362
7363
drhd2cb50b2009-01-09 21:41:17 +00007364#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007365/*
7366** The proxy locking style is intended for use with AFP filesystems.
7367** And since AFP is only supported on MacOSX, the proxy locking is also
7368** restricted to MacOSX.
7369**
7370**
7371******************* End of the proxy lock implementation **********************
7372******************************************************************************/
7373
drh734c9862008-11-28 15:37:20 +00007374/*
danielk1977e339d652008-06-28 11:23:00 +00007375** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007376**
7377** This routine registers all VFS implementations for unix-like operating
7378** systems. This routine, and the sqlite3_os_end() routine that follows,
7379** should be the only routines in this file that are visible from other
7380** files.
drh6b9d6dd2008-12-03 19:34:47 +00007381**
7382** This routine is called once during SQLite initialization and by a
7383** single thread. The memory allocation and mutex subsystems have not
7384** necessarily been initialized when this routine is called, and so they
7385** should not be used.
drh153c62c2007-08-24 03:51:33 +00007386*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007387int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007388 /*
7389 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007390 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7391 ** to the "finder" function. (pAppData is a pointer to a pointer because
7392 ** silly C90 rules prohibit a void* from being cast to a function pointer
7393 ** and so we have to go through the intermediate pointer to avoid problems
7394 ** when compiling with -pedantic-errors on GCC.)
7395 **
7396 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007397 ** finder-function. The finder-function returns a pointer to the
7398 ** sqlite_io_methods object that implements the desired locking
7399 ** behaviors. See the division above that contains the IOMETHODS
7400 ** macro for addition information on finder-functions.
7401 **
7402 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7403 ** object. But the "autolockIoFinder" available on MacOSX does a little
7404 ** more than that; it looks at the filesystem type that hosts the
7405 ** database file and tries to choose an locking method appropriate for
7406 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007407 */
drh7708e972008-11-29 00:56:52 +00007408 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007409 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007410 sizeof(unixFile), /* szOsFile */ \
7411 MAX_PATHNAME, /* mxPathname */ \
7412 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007413 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007414 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007415 unixOpen, /* xOpen */ \
7416 unixDelete, /* xDelete */ \
7417 unixAccess, /* xAccess */ \
7418 unixFullPathname, /* xFullPathname */ \
7419 unixDlOpen, /* xDlOpen */ \
7420 unixDlError, /* xDlError */ \
7421 unixDlSym, /* xDlSym */ \
7422 unixDlClose, /* xDlClose */ \
7423 unixRandomness, /* xRandomness */ \
7424 unixSleep, /* xSleep */ \
7425 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007426 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007427 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007428 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007429 unixGetSystemCall, /* xGetSystemCall */ \
7430 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007431 }
7432
drh6b9d6dd2008-12-03 19:34:47 +00007433 /*
7434 ** All default VFSes for unix are contained in the following array.
7435 **
7436 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7437 ** by the SQLite core when the VFS is registered. So the following
7438 ** array cannot be const.
7439 */
danielk1977e339d652008-06-28 11:23:00 +00007440 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007441#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007442 UNIXVFS("unix", autolockIoFinder ),
7443#else
7444 UNIXVFS("unix", posixIoFinder ),
7445#endif
7446 UNIXVFS("unix-none", nolockIoFinder ),
7447 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007448 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007449#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007450 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007451#endif
7452#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007453 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007454#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007455 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007456#endif
chw78a13182009-04-07 05:35:03 +00007457#endif
drhd2cb50b2009-01-09 21:41:17 +00007458#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007459 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007460 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007461 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007462#endif
drh153c62c2007-08-24 03:51:33 +00007463 };
drh6b9d6dd2008-12-03 19:34:47 +00007464 unsigned int i; /* Loop counter */
7465
drh2aa5a002011-04-13 13:42:25 +00007466 /* Double-check that the aSyscall[] array has been constructed
7467 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007468 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007469
drh6b9d6dd2008-12-03 19:34:47 +00007470 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007471 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007472 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007473 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007474 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007475}
danielk1977e339d652008-06-28 11:23:00 +00007476
7477/*
drh6b9d6dd2008-12-03 19:34:47 +00007478** Shutdown the operating system interface.
7479**
7480** Some operating systems might need to do some cleanup in this routine,
7481** to release dynamically allocated objects. But not on unix.
7482** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007483*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007484int sqlite3_os_end(void){
7485 return SQLITE_OK;
7486}
drhdce8bdb2007-08-16 13:01:44 +00007487
danielk197729bafea2008-06-26 10:41:19 +00007488#endif /* SQLITE_OS_UNIX */