blob: 347e82220c2a98e184873b22dcc53fd98fcde558 [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)
danbc760632014-03-20 09:42:09 +0000448 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
449#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
450
dan702eec12014-06-23 10:04:58 +0000451#endif
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
drh0bdbc902014-06-16 18:35:06 +00001922#ifdef SQLITE_UNLINK_AFTER_CLOSE
1923 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1924 osUnlink(pFile->zPath);
1925 sqlite3_free(*(char**)&pFile->zPath);
1926 pFile->zPath = 0;
1927 }
1928#endif
dan661d71a2011-03-30 19:08:03 +00001929 OSTRACE(("CLOSE %-3d\n", pFile->h));
1930 OpenCounter(-1);
1931 sqlite3_free(pFile->pUnused);
1932 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001933 return SQLITE_OK;
1934}
1935
1936/*
danielk1977e3026632004-06-22 11:29:02 +00001937** Close a file.
1938*/
danielk197762079062007-08-15 17:08:46 +00001939static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001940 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001941 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001942 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001943 unixUnlock(id, NO_LOCK);
1944 unixEnterMutex();
1945
1946 /* unixFile.pInode is always valid here. Otherwise, a different close
1947 ** routine (e.g. nolockClose()) would be called instead.
1948 */
1949 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1950 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1951 /* If there are outstanding locks, do not actually close the file just
1952 ** yet because that would clear those locks. Instead, add the file
1953 ** descriptor to pInode->pUnused list. It will be automatically closed
1954 ** when the last lock is cleared.
1955 */
1956 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001957 }
dan661d71a2011-03-30 19:08:03 +00001958 releaseInodeInfo(pFile);
1959 rc = closeUnixFile(id);
1960 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001961 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001962}
1963
drh734c9862008-11-28 15:37:20 +00001964/************** End of the posix advisory lock implementation *****************
1965******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001966
drh734c9862008-11-28 15:37:20 +00001967/******************************************************************************
1968****************************** No-op Locking **********************************
1969**
1970** Of the various locking implementations available, this is by far the
1971** simplest: locking is ignored. No attempt is made to lock the database
1972** file for reading or writing.
1973**
1974** This locking mode is appropriate for use on read-only databases
1975** (ex: databases that are burned into CD-ROM, for example.) It can
1976** also be used if the application employs some external mechanism to
1977** prevent simultaneous access of the same database by two or more
1978** database connections. But there is a serious risk of database
1979** corruption if this locking mode is used in situations where multiple
1980** database connections are accessing the same database file at the same
1981** time and one or more of those connections are writing.
1982*/
drhbfe66312006-10-03 17:40:40 +00001983
drh734c9862008-11-28 15:37:20 +00001984static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1985 UNUSED_PARAMETER(NotUsed);
1986 *pResOut = 0;
1987 return SQLITE_OK;
1988}
drh734c9862008-11-28 15:37:20 +00001989static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1990 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1991 return SQLITE_OK;
1992}
drh734c9862008-11-28 15:37:20 +00001993static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1994 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1995 return SQLITE_OK;
1996}
1997
1998/*
drh9b35ea62008-11-29 02:20:26 +00001999** Close the file.
drh734c9862008-11-28 15:37:20 +00002000*/
2001static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002002 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002003}
2004
2005/******************* End of the no-op lock implementation *********************
2006******************************************************************************/
2007
2008/******************************************************************************
2009************************* Begin dot-file Locking ******************************
2010**
mistachkin48864df2013-03-21 21:20:32 +00002011** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002012** files (really a directory) to control access to the database. This works
2013** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002014**
2015** (1) There is zero concurrency. A single reader blocks all other
2016** connections from reading or writing the database.
2017**
2018** (2) An application crash or power loss can leave stale lock files
2019** sitting around that need to be cleared manually.
2020**
2021** Nevertheless, a dotlock is an appropriate locking mode for use if no
2022** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002023**
drh9ef6bc42011-11-04 02:24:02 +00002024** Dotfile locking works by creating a subdirectory in the same directory as
2025** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002026** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002027** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002028*/
2029
2030/*
2031** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002032** lock directory.
drh734c9862008-11-28 15:37:20 +00002033*/
2034#define DOTLOCK_SUFFIX ".lock"
2035
drh7708e972008-11-29 00:56:52 +00002036/*
2037** This routine checks if there is a RESERVED lock held on the specified
2038** file by this or any other process. If such a lock is held, set *pResOut
2039** to a non-zero value otherwise *pResOut is set to zero. The return value
2040** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2041**
2042** In dotfile locking, either a lock exists or it does not. So in this
2043** variation of CheckReservedLock(), *pResOut is set to true if any lock
2044** is held on the file and false if the file is unlocked.
2045*/
drh734c9862008-11-28 15:37:20 +00002046static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2047 int rc = SQLITE_OK;
2048 int reserved = 0;
2049 unixFile *pFile = (unixFile*)id;
2050
2051 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2052
2053 assert( pFile );
2054
2055 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002056 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002057 /* Either this connection or some other connection in the same process
2058 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002059 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002060 }else{
2061 /* The lock is held if and only if the lockfile exists */
2062 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002063 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002064 }
drh308c2a52010-05-14 11:30:18 +00002065 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002066 *pResOut = reserved;
2067 return rc;
2068}
2069
drh7708e972008-11-29 00:56:52 +00002070/*
drh308c2a52010-05-14 11:30:18 +00002071** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002072** of the following:
2073**
2074** (1) SHARED_LOCK
2075** (2) RESERVED_LOCK
2076** (3) PENDING_LOCK
2077** (4) EXCLUSIVE_LOCK
2078**
2079** Sometimes when requesting one lock state, additional lock states
2080** are inserted in between. The locking might fail on one of the later
2081** transitions leaving the lock state different from what it started but
2082** still short of its goal. The following chart shows the allowed
2083** transitions and the inserted intermediate states:
2084**
2085** UNLOCKED -> SHARED
2086** SHARED -> RESERVED
2087** SHARED -> (PENDING) -> EXCLUSIVE
2088** RESERVED -> (PENDING) -> EXCLUSIVE
2089** PENDING -> EXCLUSIVE
2090**
2091** This routine will only increase a lock. Use the sqlite3OsUnlock()
2092** routine to lower a locking level.
2093**
2094** With dotfile locking, we really only support state (4): EXCLUSIVE.
2095** But we track the other locking levels internally.
2096*/
drh308c2a52010-05-14 11:30:18 +00002097static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002098 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002099 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002100 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002101
drh7708e972008-11-29 00:56:52 +00002102
2103 /* If we have any lock, then the lock file already exists. All we have
2104 ** to do is adjust our internal record of the lock level.
2105 */
drh308c2a52010-05-14 11:30:18 +00002106 if( pFile->eFileLock > NO_LOCK ){
2107 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002108 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002109#ifdef HAVE_UTIME
2110 utime(zLockFile, NULL);
2111#else
drh734c9862008-11-28 15:37:20 +00002112 utimes(zLockFile, NULL);
2113#endif
drh7708e972008-11-29 00:56:52 +00002114 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002115 }
2116
2117 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002118 rc = osMkdir(zLockFile, 0777);
2119 if( rc<0 ){
2120 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002121 int tErrno = errno;
2122 if( EEXIST == tErrno ){
2123 rc = SQLITE_BUSY;
2124 } else {
2125 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2126 if( IS_LOCK_ERROR(rc) ){
2127 pFile->lastErrno = tErrno;
2128 }
2129 }
drh7708e972008-11-29 00:56:52 +00002130 return rc;
drh734c9862008-11-28 15:37:20 +00002131 }
drh734c9862008-11-28 15:37:20 +00002132
2133 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002134 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002135 return rc;
2136}
2137
drh7708e972008-11-29 00:56:52 +00002138/*
drh308c2a52010-05-14 11:30:18 +00002139** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002140** must be either NO_LOCK or SHARED_LOCK.
2141**
2142** If the locking level of the file descriptor is already at or below
2143** the requested locking level, this routine is a no-op.
2144**
2145** When the locking level reaches NO_LOCK, delete the lock file.
2146*/
drh308c2a52010-05-14 11:30:18 +00002147static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002148 unixFile *pFile = (unixFile*)id;
2149 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002150 int rc;
drh734c9862008-11-28 15:37:20 +00002151
2152 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002153 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002154 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002155 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002156
2157 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002158 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002159 return SQLITE_OK;
2160 }
drh7708e972008-11-29 00:56:52 +00002161
2162 /* To downgrade to shared, simply update our internal notion of the
2163 ** lock state. No need to mess with the file on disk.
2164 */
drh308c2a52010-05-14 11:30:18 +00002165 if( eFileLock==SHARED_LOCK ){
2166 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002167 return SQLITE_OK;
2168 }
2169
drh7708e972008-11-29 00:56:52 +00002170 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002171 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002172 rc = osRmdir(zLockFile);
2173 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2174 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002175 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002176 rc = 0;
drh734c9862008-11-28 15:37:20 +00002177 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002178 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002179 }
2180 if( IS_LOCK_ERROR(rc) ){
2181 pFile->lastErrno = tErrno;
2182 }
2183 return rc;
2184 }
drh308c2a52010-05-14 11:30:18 +00002185 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002186 return SQLITE_OK;
2187}
2188
2189/*
drh9b35ea62008-11-29 02:20:26 +00002190** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002191*/
2192static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002193 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002194 if( id ){
2195 unixFile *pFile = (unixFile*)id;
2196 dotlockUnlock(id, NO_LOCK);
2197 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002198 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002199 }
drh734c9862008-11-28 15:37:20 +00002200 return rc;
2201}
2202/****************** End of the dot-file lock implementation *******************
2203******************************************************************************/
2204
2205/******************************************************************************
2206************************** Begin flock Locking ********************************
2207**
2208** Use the flock() system call to do file locking.
2209**
drh6b9d6dd2008-12-03 19:34:47 +00002210** flock() locking is like dot-file locking in that the various
2211** fine-grain locking levels supported by SQLite are collapsed into
2212** a single exclusive lock. In other words, SHARED, RESERVED, and
2213** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2214** still works when you do this, but concurrency is reduced since
2215** only a single process can be reading the database at a time.
2216**
drh734c9862008-11-28 15:37:20 +00002217** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2218** compiling for VXWORKS.
2219*/
2220#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002221
drh6b9d6dd2008-12-03 19:34:47 +00002222/*
drhff812312011-02-23 13:33:46 +00002223** Retry flock() calls that fail with EINTR
2224*/
2225#ifdef EINTR
2226static int robust_flock(int fd, int op){
2227 int rc;
2228 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2229 return rc;
2230}
2231#else
drh5c819272011-02-23 14:00:12 +00002232# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002233#endif
2234
2235
2236/*
drh6b9d6dd2008-12-03 19:34:47 +00002237** This routine checks if there is a RESERVED lock held on the specified
2238** file by this or any other process. If such a lock is held, set *pResOut
2239** to a non-zero value otherwise *pResOut is set to zero. The return value
2240** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2241*/
drh734c9862008-11-28 15:37:20 +00002242static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2243 int rc = SQLITE_OK;
2244 int reserved = 0;
2245 unixFile *pFile = (unixFile*)id;
2246
2247 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2248
2249 assert( pFile );
2250
2251 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002252 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002253 reserved = 1;
2254 }
2255
2256 /* Otherwise see if some other process holds it. */
2257 if( !reserved ){
2258 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002259 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002260 if( !lrc ){
2261 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002262 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002263 if ( lrc ) {
2264 int tErrno = errno;
2265 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002266 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002267 if( IS_LOCK_ERROR(lrc) ){
2268 pFile->lastErrno = tErrno;
2269 rc = lrc;
2270 }
2271 }
2272 } else {
2273 int tErrno = errno;
2274 reserved = 1;
2275 /* someone else might have it reserved */
2276 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2277 if( IS_LOCK_ERROR(lrc) ){
2278 pFile->lastErrno = tErrno;
2279 rc = lrc;
2280 }
2281 }
2282 }
drh308c2a52010-05-14 11:30:18 +00002283 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002284
2285#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2286 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2287 rc = SQLITE_OK;
2288 reserved=1;
2289 }
2290#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2291 *pResOut = reserved;
2292 return rc;
2293}
2294
drh6b9d6dd2008-12-03 19:34:47 +00002295/*
drh308c2a52010-05-14 11:30:18 +00002296** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002297** of the following:
2298**
2299** (1) SHARED_LOCK
2300** (2) RESERVED_LOCK
2301** (3) PENDING_LOCK
2302** (4) EXCLUSIVE_LOCK
2303**
2304** Sometimes when requesting one lock state, additional lock states
2305** are inserted in between. The locking might fail on one of the later
2306** transitions leaving the lock state different from what it started but
2307** still short of its goal. The following chart shows the allowed
2308** transitions and the inserted intermediate states:
2309**
2310** UNLOCKED -> SHARED
2311** SHARED -> RESERVED
2312** SHARED -> (PENDING) -> EXCLUSIVE
2313** RESERVED -> (PENDING) -> EXCLUSIVE
2314** PENDING -> EXCLUSIVE
2315**
2316** flock() only really support EXCLUSIVE locks. We track intermediate
2317** lock states in the sqlite3_file structure, but all locks SHARED or
2318** above are really EXCLUSIVE locks and exclude all other processes from
2319** access the file.
2320**
2321** This routine will only increase a lock. Use the sqlite3OsUnlock()
2322** routine to lower a locking level.
2323*/
drh308c2a52010-05-14 11:30:18 +00002324static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002325 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002326 unixFile *pFile = (unixFile*)id;
2327
2328 assert( pFile );
2329
2330 /* if we already have a lock, it is exclusive.
2331 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002332 if (pFile->eFileLock > NO_LOCK) {
2333 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002334 return SQLITE_OK;
2335 }
2336
2337 /* grab an exclusive lock */
2338
drhff812312011-02-23 13:33:46 +00002339 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002340 int tErrno = errno;
2341 /* didn't get, must be busy */
2342 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2343 if( IS_LOCK_ERROR(rc) ){
2344 pFile->lastErrno = tErrno;
2345 }
2346 } else {
2347 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002348 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002349 }
drh308c2a52010-05-14 11:30:18 +00002350 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2351 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002352#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2353 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2354 rc = SQLITE_BUSY;
2355 }
2356#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2357 return rc;
2358}
2359
drh6b9d6dd2008-12-03 19:34:47 +00002360
2361/*
drh308c2a52010-05-14 11:30:18 +00002362** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002363** must be either NO_LOCK or SHARED_LOCK.
2364**
2365** If the locking level of the file descriptor is already at or below
2366** the requested locking level, this routine is a no-op.
2367*/
drh308c2a52010-05-14 11:30:18 +00002368static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002369 unixFile *pFile = (unixFile*)id;
2370
2371 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002372 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2373 pFile->eFileLock, getpid()));
2374 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002375
2376 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002377 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002378 return SQLITE_OK;
2379 }
2380
2381 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002382 if (eFileLock==SHARED_LOCK) {
2383 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002384 return SQLITE_OK;
2385 }
2386
2387 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002388 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002389#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002390 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002391#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002392 return SQLITE_IOERR_UNLOCK;
2393 }else{
drh308c2a52010-05-14 11:30:18 +00002394 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002395 return SQLITE_OK;
2396 }
2397}
2398
2399/*
2400** Close a file.
2401*/
2402static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002403 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002404 if( id ){
2405 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002406 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002407 }
drh5a05be12012-10-09 18:51:44 +00002408 return rc;
drh734c9862008-11-28 15:37:20 +00002409}
2410
2411#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2412
2413/******************* End of the flock lock implementation *********************
2414******************************************************************************/
2415
2416/******************************************************************************
2417************************ Begin Named Semaphore Locking ************************
2418**
2419** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002420**
2421** Semaphore locking is like dot-lock and flock in that it really only
2422** supports EXCLUSIVE locking. Only a single process can read or write
2423** the database file at a time. This reduces potential concurrency, but
2424** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002425*/
2426#if OS_VXWORKS
2427
drh6b9d6dd2008-12-03 19:34:47 +00002428/*
2429** This routine checks if there is a RESERVED lock held on the specified
2430** file by this or any other process. If such a lock is held, set *pResOut
2431** to a non-zero value otherwise *pResOut is set to zero. The return value
2432** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2433*/
drh734c9862008-11-28 15:37:20 +00002434static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2435 int rc = SQLITE_OK;
2436 int reserved = 0;
2437 unixFile *pFile = (unixFile*)id;
2438
2439 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2440
2441 assert( pFile );
2442
2443 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002444 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002445 reserved = 1;
2446 }
2447
2448 /* Otherwise see if some other process holds it. */
2449 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002450 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002451 struct stat statBuf;
2452
2453 if( sem_trywait(pSem)==-1 ){
2454 int tErrno = errno;
2455 if( EAGAIN != tErrno ){
2456 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2457 pFile->lastErrno = tErrno;
2458 } else {
2459 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002460 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002461 }
2462 }else{
2463 /* we could have it if we want it */
2464 sem_post(pSem);
2465 }
2466 }
drh308c2a52010-05-14 11:30:18 +00002467 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002468
2469 *pResOut = reserved;
2470 return rc;
2471}
2472
drh6b9d6dd2008-12-03 19:34:47 +00002473/*
drh308c2a52010-05-14 11:30:18 +00002474** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002475** of the following:
2476**
2477** (1) SHARED_LOCK
2478** (2) RESERVED_LOCK
2479** (3) PENDING_LOCK
2480** (4) EXCLUSIVE_LOCK
2481**
2482** Sometimes when requesting one lock state, additional lock states
2483** are inserted in between. The locking might fail on one of the later
2484** transitions leaving the lock state different from what it started but
2485** still short of its goal. The following chart shows the allowed
2486** transitions and the inserted intermediate states:
2487**
2488** UNLOCKED -> SHARED
2489** SHARED -> RESERVED
2490** SHARED -> (PENDING) -> EXCLUSIVE
2491** RESERVED -> (PENDING) -> EXCLUSIVE
2492** PENDING -> EXCLUSIVE
2493**
2494** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2495** lock states in the sqlite3_file structure, but all locks SHARED or
2496** above are really EXCLUSIVE locks and exclude all other processes from
2497** access the file.
2498**
2499** This routine will only increase a lock. Use the sqlite3OsUnlock()
2500** routine to lower a locking level.
2501*/
drh308c2a52010-05-14 11:30:18 +00002502static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002503 unixFile *pFile = (unixFile*)id;
2504 int fd;
drh8af6c222010-05-14 12:43:01 +00002505 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002506 int rc = SQLITE_OK;
2507
2508 /* if we already have a lock, it is exclusive.
2509 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002510 if (pFile->eFileLock > NO_LOCK) {
2511 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002512 rc = SQLITE_OK;
2513 goto sem_end_lock;
2514 }
2515
2516 /* lock semaphore now but bail out when already locked. */
2517 if( sem_trywait(pSem)==-1 ){
2518 rc = SQLITE_BUSY;
2519 goto sem_end_lock;
2520 }
2521
2522 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002523 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002524
2525 sem_end_lock:
2526 return rc;
2527}
2528
drh6b9d6dd2008-12-03 19:34:47 +00002529/*
drh308c2a52010-05-14 11:30:18 +00002530** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002531** must be either NO_LOCK or SHARED_LOCK.
2532**
2533** If the locking level of the file descriptor is already at or below
2534** the requested locking level, this routine is a no-op.
2535*/
drh308c2a52010-05-14 11:30:18 +00002536static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002537 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002538 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002539
2540 assert( pFile );
2541 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002542 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002543 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002544 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002545
2546 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002547 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002548 return SQLITE_OK;
2549 }
2550
2551 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002552 if (eFileLock==SHARED_LOCK) {
2553 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002554 return SQLITE_OK;
2555 }
2556
2557 /* no, really unlock. */
2558 if ( sem_post(pSem)==-1 ) {
2559 int rc, tErrno = errno;
2560 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2561 if( IS_LOCK_ERROR(rc) ){
2562 pFile->lastErrno = tErrno;
2563 }
2564 return rc;
2565 }
drh308c2a52010-05-14 11:30:18 +00002566 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002567 return SQLITE_OK;
2568}
2569
2570/*
2571 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002572 */
drh734c9862008-11-28 15:37:20 +00002573static int semClose(sqlite3_file *id) {
2574 if( id ){
2575 unixFile *pFile = (unixFile*)id;
2576 semUnlock(id, NO_LOCK);
2577 assert( pFile );
2578 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002579 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002580 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002581 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002582 }
2583 return SQLITE_OK;
2584}
2585
2586#endif /* OS_VXWORKS */
2587/*
2588** Named semaphore locking is only available on VxWorks.
2589**
2590*************** End of the named semaphore lock implementation ****************
2591******************************************************************************/
2592
2593
2594/******************************************************************************
2595*************************** Begin AFP Locking *********************************
2596**
2597** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2598** on Apple Macintosh computers - both OS9 and OSX.
2599**
2600** Third-party implementations of AFP are available. But this code here
2601** only works on OSX.
2602*/
2603
drhd2cb50b2009-01-09 21:41:17 +00002604#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002605/*
2606** The afpLockingContext structure contains all afp lock specific state
2607*/
drhbfe66312006-10-03 17:40:40 +00002608typedef struct afpLockingContext afpLockingContext;
2609struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002610 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002611 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002612};
2613
2614struct ByteRangeLockPB2
2615{
2616 unsigned long long offset; /* offset to first byte to lock */
2617 unsigned long long length; /* nbr of bytes to lock */
2618 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2619 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2620 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2621 int fd; /* file desc to assoc this lock with */
2622};
2623
drhfd131da2007-08-07 17:13:03 +00002624#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002625
drh6b9d6dd2008-12-03 19:34:47 +00002626/*
2627** This is a utility for setting or clearing a bit-range lock on an
2628** AFP filesystem.
2629**
2630** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2631*/
2632static int afpSetLock(
2633 const char *path, /* Name of the file to be locked or unlocked */
2634 unixFile *pFile, /* Open file descriptor on path */
2635 unsigned long long offset, /* First byte to be locked */
2636 unsigned long long length, /* Number of bytes to lock */
2637 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002638){
drh6b9d6dd2008-12-03 19:34:47 +00002639 struct ByteRangeLockPB2 pb;
2640 int err;
drhbfe66312006-10-03 17:40:40 +00002641
2642 pb.unLockFlag = setLockFlag ? 0 : 1;
2643 pb.startEndFlag = 0;
2644 pb.offset = offset;
2645 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002646 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002647
drh308c2a52010-05-14 11:30:18 +00002648 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002649 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002650 offset, length));
drhbfe66312006-10-03 17:40:40 +00002651 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2652 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002653 int rc;
2654 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002655 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2656 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002657#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2658 rc = SQLITE_BUSY;
2659#else
drh734c9862008-11-28 15:37:20 +00002660 rc = sqliteErrorFromPosixError(tErrno,
2661 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002662#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002663 if( IS_LOCK_ERROR(rc) ){
2664 pFile->lastErrno = tErrno;
2665 }
2666 return rc;
drhbfe66312006-10-03 17:40:40 +00002667 } else {
aswift5b1a2562008-08-22 00:22:35 +00002668 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002669 }
2670}
2671
drh6b9d6dd2008-12-03 19:34:47 +00002672/*
2673** This routine checks if there is a RESERVED lock held on the specified
2674** file by this or any other process. If such a lock is held, set *pResOut
2675** to a non-zero value otherwise *pResOut is set to zero. The return value
2676** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2677*/
danielk1977e339d652008-06-28 11:23:00 +00002678static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002679 int rc = SQLITE_OK;
2680 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002681 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002682 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002683
aswift5b1a2562008-08-22 00:22:35 +00002684 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2685
2686 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002687 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002688 if( context->reserved ){
2689 *pResOut = 1;
2690 return SQLITE_OK;
2691 }
drh8af6c222010-05-14 12:43:01 +00002692 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002693
2694 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002695 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002696 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002697 }
2698
2699 /* Otherwise see if some other process holds it.
2700 */
aswift5b1a2562008-08-22 00:22:35 +00002701 if( !reserved ){
2702 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002703 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002704 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002705 /* if we succeeded in taking the reserved lock, unlock it to restore
2706 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002707 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002708 } else {
2709 /* if we failed to get the lock then someone else must have it */
2710 reserved = 1;
2711 }
2712 if( IS_LOCK_ERROR(lrc) ){
2713 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002714 }
2715 }
drhbfe66312006-10-03 17:40:40 +00002716
drh7ed97b92010-01-20 13:07:21 +00002717 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002718 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002719
2720 *pResOut = reserved;
2721 return rc;
drhbfe66312006-10-03 17:40:40 +00002722}
2723
drh6b9d6dd2008-12-03 19:34:47 +00002724/*
drh308c2a52010-05-14 11:30:18 +00002725** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002726** of the following:
2727**
2728** (1) SHARED_LOCK
2729** (2) RESERVED_LOCK
2730** (3) PENDING_LOCK
2731** (4) EXCLUSIVE_LOCK
2732**
2733** Sometimes when requesting one lock state, additional lock states
2734** are inserted in between. The locking might fail on one of the later
2735** transitions leaving the lock state different from what it started but
2736** still short of its goal. The following chart shows the allowed
2737** transitions and the inserted intermediate states:
2738**
2739** UNLOCKED -> SHARED
2740** SHARED -> RESERVED
2741** SHARED -> (PENDING) -> EXCLUSIVE
2742** RESERVED -> (PENDING) -> EXCLUSIVE
2743** PENDING -> EXCLUSIVE
2744**
2745** This routine will only increase a lock. Use the sqlite3OsUnlock()
2746** routine to lower a locking level.
2747*/
drh308c2a52010-05-14 11:30:18 +00002748static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002749 int rc = SQLITE_OK;
2750 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002751 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002752 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002753
2754 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002755 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2756 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002757 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002758
drhbfe66312006-10-03 17:40:40 +00002759 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002760 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002761 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002762 */
drh308c2a52010-05-14 11:30:18 +00002763 if( pFile->eFileLock>=eFileLock ){
2764 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2765 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002766 return SQLITE_OK;
2767 }
2768
2769 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002770 ** (1) We never move from unlocked to anything higher than shared lock.
2771 ** (2) SQLite never explicitly requests a pendig lock.
2772 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002773 */
drh308c2a52010-05-14 11:30:18 +00002774 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2775 assert( eFileLock!=PENDING_LOCK );
2776 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002777
drh8af6c222010-05-14 12:43:01 +00002778 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002779 */
drh6c7d5c52008-11-21 20:32:33 +00002780 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002781 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002782
2783 /* If some thread using this PID has a lock via a different unixFile*
2784 ** handle that precludes the requested lock, return BUSY.
2785 */
drh8af6c222010-05-14 12:43:01 +00002786 if( (pFile->eFileLock!=pInode->eFileLock &&
2787 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002788 ){
2789 rc = SQLITE_BUSY;
2790 goto afp_end_lock;
2791 }
2792
2793 /* If a SHARED lock is requested, and some thread using this PID already
2794 ** has a SHARED or RESERVED lock, then increment reference counts and
2795 ** return SQLITE_OK.
2796 */
drh308c2a52010-05-14 11:30:18 +00002797 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002798 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002799 assert( eFileLock==SHARED_LOCK );
2800 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002801 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002802 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002803 pInode->nShared++;
2804 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002805 goto afp_end_lock;
2806 }
drhbfe66312006-10-03 17:40:40 +00002807
2808 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002809 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2810 ** be released.
2811 */
drh308c2a52010-05-14 11:30:18 +00002812 if( eFileLock==SHARED_LOCK
2813 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002814 ){
2815 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002816 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002817 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002818 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002819 goto afp_end_lock;
2820 }
2821 }
2822
2823 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002824 ** operating system calls for the specified lock.
2825 */
drh308c2a52010-05-14 11:30:18 +00002826 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002827 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002828 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002829
drh8af6c222010-05-14 12:43:01 +00002830 assert( pInode->nShared==0 );
2831 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002832
2833 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002834 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002835 /* note that the quality of the randomness doesn't matter that much */
2836 lk = random();
drh8af6c222010-05-14 12:43:01 +00002837 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002838 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002839 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002840 if( IS_LOCK_ERROR(lrc1) ){
2841 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002842 }
aswift5b1a2562008-08-22 00:22:35 +00002843 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002844 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002845
aswift5b1a2562008-08-22 00:22:35 +00002846 if( IS_LOCK_ERROR(lrc1) ) {
2847 pFile->lastErrno = lrc1Errno;
2848 rc = lrc1;
2849 goto afp_end_lock;
2850 } else if( IS_LOCK_ERROR(lrc2) ){
2851 rc = lrc2;
2852 goto afp_end_lock;
2853 } else if( lrc1 != SQLITE_OK ) {
2854 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002855 } else {
drh308c2a52010-05-14 11:30:18 +00002856 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002857 pInode->nLock++;
2858 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002859 }
drh8af6c222010-05-14 12:43:01 +00002860 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002861 /* We are trying for an exclusive lock but another thread in this
2862 ** same process is still holding a shared lock. */
2863 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002864 }else{
2865 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2866 ** assumed that there is a SHARED or greater lock on the file
2867 ** already.
2868 */
2869 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002870 assert( 0!=pFile->eFileLock );
2871 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002872 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002873 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002874 if( !failed ){
2875 context->reserved = 1;
2876 }
drhbfe66312006-10-03 17:40:40 +00002877 }
drh308c2a52010-05-14 11:30:18 +00002878 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002879 /* Acquire an EXCLUSIVE lock */
2880
2881 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002882 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002883 */
drh6b9d6dd2008-12-03 19:34:47 +00002884 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002885 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002886 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002887 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002888 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002889 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002890 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002891 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002892 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2893 ** a critical I/O error
2894 */
2895 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2896 SQLITE_IOERR_LOCK;
2897 goto afp_end_lock;
2898 }
2899 }else{
aswift5b1a2562008-08-22 00:22:35 +00002900 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002901 }
2902 }
aswift5b1a2562008-08-22 00:22:35 +00002903 if( failed ){
2904 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002905 }
2906 }
2907
2908 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002909 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002910 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002911 }else if( eFileLock==EXCLUSIVE_LOCK ){
2912 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002913 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002914 }
2915
2916afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002917 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002918 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2919 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002920 return rc;
2921}
2922
2923/*
drh308c2a52010-05-14 11:30:18 +00002924** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002925** must be either NO_LOCK or SHARED_LOCK.
2926**
2927** If the locking level of the file descriptor is already at or below
2928** the requested locking level, this routine is a no-op.
2929*/
drh308c2a52010-05-14 11:30:18 +00002930static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002931 int rc = SQLITE_OK;
2932 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002933 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002934 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2935 int skipShared = 0;
2936#ifdef SQLITE_TEST
2937 int h = pFile->h;
2938#endif
drhbfe66312006-10-03 17:40:40 +00002939
2940 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002941 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002942 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002943 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002944
drh308c2a52010-05-14 11:30:18 +00002945 assert( eFileLock<=SHARED_LOCK );
2946 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002947 return SQLITE_OK;
2948 }
drh6c7d5c52008-11-21 20:32:33 +00002949 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002950 pInode = pFile->pInode;
2951 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002952 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002953 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002954 SimulateIOErrorBenign(1);
2955 SimulateIOError( h=(-1) )
2956 SimulateIOErrorBenign(0);
2957
drhd3d8c042012-05-29 17:02:40 +00002958#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002959 /* When reducing a lock such that other processes can start
2960 ** reading the database file again, make sure that the
2961 ** transaction counter was updated if any part of the database
2962 ** file changed. If the transaction counter is not updated,
2963 ** other connections to the same file might not realize that
2964 ** the file has changed and hence might not know to flush their
2965 ** cache. The use of a stale cache can lead to database corruption.
2966 */
2967 assert( pFile->inNormalWrite==0
2968 || pFile->dbUpdate==0
2969 || pFile->transCntrChng==1 );
2970 pFile->inNormalWrite = 0;
2971#endif
aswiftaebf4132008-11-21 00:10:35 +00002972
drh308c2a52010-05-14 11:30:18 +00002973 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002974 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002975 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002976 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002977 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002978 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2979 } else {
2980 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002981 }
2982 }
drh308c2a52010-05-14 11:30:18 +00002983 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002984 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002985 }
drh308c2a52010-05-14 11:30:18 +00002986 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002987 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2988 if( !rc ){
2989 context->reserved = 0;
2990 }
aswiftaebf4132008-11-21 00:10:35 +00002991 }
drh8af6c222010-05-14 12:43:01 +00002992 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2993 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002994 }
aswiftaebf4132008-11-21 00:10:35 +00002995 }
drh308c2a52010-05-14 11:30:18 +00002996 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002997
drh7ed97b92010-01-20 13:07:21 +00002998 /* Decrement the shared lock counter. Release the lock using an
2999 ** OS call only when all threads in this same process have released
3000 ** the lock.
3001 */
drh8af6c222010-05-14 12:43:01 +00003002 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3003 pInode->nShared--;
3004 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003005 SimulateIOErrorBenign(1);
3006 SimulateIOError( h=(-1) )
3007 SimulateIOErrorBenign(0);
3008 if( !skipShared ){
3009 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3010 }
3011 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003012 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003013 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003014 }
3015 }
3016 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003017 pInode->nLock--;
3018 assert( pInode->nLock>=0 );
3019 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003020 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003021 }
3022 }
drhbfe66312006-10-03 17:40:40 +00003023 }
drh7ed97b92010-01-20 13:07:21 +00003024
drh6c7d5c52008-11-21 20:32:33 +00003025 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003026 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003027 return rc;
3028}
3029
3030/*
drh339eb0b2008-03-07 15:34:11 +00003031** Close a file & cleanup AFP specific locking context
3032*/
danielk1977e339d652008-06-28 11:23:00 +00003033static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003034 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003035 if( id ){
3036 unixFile *pFile = (unixFile*)id;
3037 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003038 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003039 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003040 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003041 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003042 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003043 ** the last lock is cleared.
3044 */
dan08da86a2009-08-21 17:18:03 +00003045 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003046 }
danb0ac3e32010-06-16 10:55:42 +00003047 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003048 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003049 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003050 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003051 }
drh7ed97b92010-01-20 13:07:21 +00003052 return rc;
drhbfe66312006-10-03 17:40:40 +00003053}
3054
drhd2cb50b2009-01-09 21:41:17 +00003055#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003056/*
3057** The code above is the AFP lock implementation. The code is specific
3058** to MacOSX and does not work on other unix platforms. No alternative
3059** is available. If you don't compile for a mac, then the "unix-afp"
3060** VFS is not available.
3061**
3062********************* End of the AFP lock implementation **********************
3063******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003064
drh7ed97b92010-01-20 13:07:21 +00003065/******************************************************************************
3066*************************** Begin NFS Locking ********************************/
3067
3068#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3069/*
drh308c2a52010-05-14 11:30:18 +00003070 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003071 ** must be either NO_LOCK or SHARED_LOCK.
3072 **
3073 ** If the locking level of the file descriptor is already at or below
3074 ** the requested locking level, this routine is a no-op.
3075 */
drh308c2a52010-05-14 11:30:18 +00003076static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003077 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003078}
3079
3080#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3081/*
3082** The code above is the NFS lock implementation. The code is specific
3083** to MacOSX and does not work on other unix platforms. No alternative
3084** is available.
3085**
3086********************* End of the NFS lock implementation **********************
3087******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003088
3089/******************************************************************************
3090**************** Non-locking sqlite3_file methods *****************************
3091**
3092** The next division contains implementations for all methods of the
3093** sqlite3_file object other than the locking methods. The locking
3094** methods were defined in divisions above (one locking method per
3095** division). Those methods that are common to all locking modes
3096** are gather together into this division.
3097*/
drhbfe66312006-10-03 17:40:40 +00003098
3099/*
drh734c9862008-11-28 15:37:20 +00003100** Seek to the offset passed as the second argument, then read cnt
3101** bytes into pBuf. Return the number of bytes actually read.
3102**
3103** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3104** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3105** one system to another. Since SQLite does not define USE_PREAD
3106** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3107** See tickets #2741 and #2681.
3108**
3109** To avoid stomping the errno value on a failed read the lastErrno value
3110** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003111*/
drh734c9862008-11-28 15:37:20 +00003112static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3113 int got;
drh58024642011-11-07 18:16:00 +00003114 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003115#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003116 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003117#endif
drh734c9862008-11-28 15:37:20 +00003118 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003119 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003120 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003121 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003122 do{
drh734c9862008-11-28 15:37:20 +00003123#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003124 got = osPread(id->h, pBuf, cnt, offset);
3125 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003126#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003127 got = osPread64(id->h, pBuf, cnt, offset);
3128 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003129#else
drh58024642011-11-07 18:16:00 +00003130 newOffset = lseek(id->h, offset, SEEK_SET);
3131 SimulateIOError( newOffset-- );
3132 if( newOffset!=offset ){
3133 if( newOffset == -1 ){
3134 ((unixFile*)id)->lastErrno = errno;
3135 }else{
drhf2f105d2012-08-20 15:53:54 +00003136 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003137 }
3138 return -1;
drh734c9862008-11-28 15:37:20 +00003139 }
drh58024642011-11-07 18:16:00 +00003140 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003141#endif
drh58024642011-11-07 18:16:00 +00003142 if( got==cnt ) break;
3143 if( got<0 ){
3144 if( errno==EINTR ){ got = 1; continue; }
3145 prior = 0;
3146 ((unixFile*)id)->lastErrno = errno;
3147 break;
3148 }else if( got>0 ){
3149 cnt -= got;
3150 offset += got;
3151 prior += got;
3152 pBuf = (void*)(got + (char*)pBuf);
3153 }
3154 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003155 TIMER_END;
drh58024642011-11-07 18:16:00 +00003156 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3157 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3158 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003159}
3160
3161/*
drh734c9862008-11-28 15:37:20 +00003162** Read data from a file into a buffer. Return SQLITE_OK if all
3163** bytes were read successfully and SQLITE_IOERR if anything goes
3164** wrong.
drh339eb0b2008-03-07 15:34:11 +00003165*/
drh734c9862008-11-28 15:37:20 +00003166static int unixRead(
3167 sqlite3_file *id,
3168 void *pBuf,
3169 int amt,
3170 sqlite3_int64 offset
3171){
dan08da86a2009-08-21 17:18:03 +00003172 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003173 int got;
3174 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003175 assert( offset>=0 );
3176 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003177
dan08da86a2009-08-21 17:18:03 +00003178 /* If this is a database file (not a journal, master-journal or temp
3179 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003180#if 0
dane946c392009-08-22 11:39:46 +00003181 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003182 || offset>=PENDING_BYTE+512
3183 || offset+amt<=PENDING_BYTE
3184 );
dan7c246102010-04-12 19:00:29 +00003185#endif
drh08c6d442009-02-09 17:34:07 +00003186
drh9b4c59f2013-04-15 17:03:42 +00003187#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003188 /* Deal with as much of this read request as possible by transfering
3189 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003190 if( offset<pFile->mmapSize ){
3191 if( offset+amt <= pFile->mmapSize ){
3192 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3193 return SQLITE_OK;
3194 }else{
3195 int nCopy = pFile->mmapSize - offset;
3196 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3197 pBuf = &((u8 *)pBuf)[nCopy];
3198 amt -= nCopy;
3199 offset += nCopy;
3200 }
3201 }
drh6e0b6d52013-04-09 16:19:20 +00003202#endif
danf23da962013-03-23 21:00:41 +00003203
dan08da86a2009-08-21 17:18:03 +00003204 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003205 if( got==amt ){
3206 return SQLITE_OK;
3207 }else if( got<0 ){
3208 /* lastErrno set by seekAndRead */
3209 return SQLITE_IOERR_READ;
3210 }else{
dan08da86a2009-08-21 17:18:03 +00003211 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003212 /* Unread parts of the buffer must be zero-filled */
3213 memset(&((char*)pBuf)[got], 0, amt-got);
3214 return SQLITE_IOERR_SHORT_READ;
3215 }
3216}
3217
3218/*
dan47a2b4a2013-04-26 16:09:29 +00003219** Attempt to seek the file-descriptor passed as the first argument to
3220** absolute offset iOff, then attempt to write nBuf bytes of data from
3221** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3222** return the actual number of bytes written (which may be less than
3223** nBuf).
3224*/
3225static int seekAndWriteFd(
3226 int fd, /* File descriptor to write to */
3227 i64 iOff, /* File offset to begin writing at */
3228 const void *pBuf, /* Copy data from this buffer to the file */
3229 int nBuf, /* Size of buffer pBuf in bytes */
3230 int *piErrno /* OUT: Error number if error occurs */
3231){
3232 int rc = 0; /* Value returned by system call */
3233
3234 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003235 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003236 nBuf &= 0x1ffff;
3237 TIMER_START;
3238
3239#if defined(USE_PREAD)
3240 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3241#elif defined(USE_PREAD64)
3242 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3243#else
3244 do{
3245 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3246 SimulateIOError( iSeek-- );
3247
3248 if( iSeek!=iOff ){
3249 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3250 return -1;
3251 }
3252 rc = osWrite(fd, pBuf, nBuf);
3253 }while( rc<0 && errno==EINTR );
3254#endif
3255
3256 TIMER_END;
3257 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3258
3259 if( rc<0 && piErrno ) *piErrno = errno;
3260 return rc;
3261}
3262
3263
3264/*
drh734c9862008-11-28 15:37:20 +00003265** Seek to the offset in id->offset then read cnt bytes into pBuf.
3266** Return the number of bytes actually read. Update the offset.
3267**
3268** To avoid stomping the errno value on a failed write the lastErrno value
3269** is set before returning.
3270*/
3271static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003272 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003273}
3274
3275
3276/*
3277** Write data from a buffer into a file. Return SQLITE_OK on success
3278** or some other error code on failure.
3279*/
3280static int unixWrite(
3281 sqlite3_file *id,
3282 const void *pBuf,
3283 int amt,
3284 sqlite3_int64 offset
3285){
dan08da86a2009-08-21 17:18:03 +00003286 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003287 int wrote = 0;
3288 assert( id );
3289 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003290
dan08da86a2009-08-21 17:18:03 +00003291 /* If this is a database file (not a journal, master-journal or temp
3292 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003293#if 0
dane946c392009-08-22 11:39:46 +00003294 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003295 || offset>=PENDING_BYTE+512
3296 || offset+amt<=PENDING_BYTE
3297 );
dan7c246102010-04-12 19:00:29 +00003298#endif
drh08c6d442009-02-09 17:34:07 +00003299
drhd3d8c042012-05-29 17:02:40 +00003300#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003301 /* If we are doing a normal write to a database file (as opposed to
3302 ** doing a hot-journal rollback or a write to some file other than a
3303 ** normal database file) then record the fact that the database
3304 ** has changed. If the transaction counter is modified, record that
3305 ** fact too.
3306 */
dan08da86a2009-08-21 17:18:03 +00003307 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003308 pFile->dbUpdate = 1; /* The database has been modified */
3309 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003310 int rc;
drh8f941bc2009-01-14 23:03:40 +00003311 char oldCntr[4];
3312 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003313 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003314 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003315 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003316 pFile->transCntrChng = 1; /* The transaction counter has changed */
3317 }
3318 }
3319 }
3320#endif
3321
drh9b4c59f2013-04-15 17:03:42 +00003322#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003323 /* Deal with as much of this write request as possible by transfering
3324 ** data from the memory mapping using memcpy(). */
3325 if( offset<pFile->mmapSize ){
3326 if( offset+amt <= pFile->mmapSize ){
3327 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3328 return SQLITE_OK;
3329 }else{
3330 int nCopy = pFile->mmapSize - offset;
3331 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3332 pBuf = &((u8 *)pBuf)[nCopy];
3333 amt -= nCopy;
3334 offset += nCopy;
3335 }
3336 }
drh6e0b6d52013-04-09 16:19:20 +00003337#endif
danf23da962013-03-23 21:00:41 +00003338
dan08da86a2009-08-21 17:18:03 +00003339 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003340 amt -= wrote;
3341 offset += wrote;
3342 pBuf = &((char*)pBuf)[wrote];
3343 }
3344 SimulateIOError(( wrote=(-1), amt=1 ));
3345 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003346
drh734c9862008-11-28 15:37:20 +00003347 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003348 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003349 /* lastErrno set by seekAndWrite */
3350 return SQLITE_IOERR_WRITE;
3351 }else{
dan08da86a2009-08-21 17:18:03 +00003352 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003353 return SQLITE_FULL;
3354 }
3355 }
dan6e09d692010-07-27 18:34:15 +00003356
drh734c9862008-11-28 15:37:20 +00003357 return SQLITE_OK;
3358}
3359
3360#ifdef SQLITE_TEST
3361/*
3362** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003363** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003364*/
3365int sqlite3_sync_count = 0;
3366int sqlite3_fullsync_count = 0;
3367#endif
3368
3369/*
drh89240432009-03-25 01:06:01 +00003370** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003371** Others do no. To be safe, we will stick with the (slightly slower)
3372** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003373** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003374*/
drh20f8e132011-08-31 21:01:55 +00003375#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003376# define fdatasync fsync
3377#endif
3378
3379/*
3380** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3381** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3382** only available on Mac OS X. But that could change.
3383*/
3384#ifdef F_FULLFSYNC
3385# define HAVE_FULLFSYNC 1
3386#else
3387# define HAVE_FULLFSYNC 0
3388#endif
3389
3390
3391/*
3392** The fsync() system call does not work as advertised on many
3393** unix systems. The following procedure is an attempt to make
3394** it work better.
3395**
3396** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3397** for testing when we want to run through the test suite quickly.
3398** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3399** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3400** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003401**
3402** SQLite sets the dataOnly flag if the size of the file is unchanged.
3403** The idea behind dataOnly is that it should only write the file content
3404** to disk, not the inode. We only set dataOnly if the file size is
3405** unchanged since the file size is part of the inode. However,
3406** Ted Ts'o tells us that fdatasync() will also write the inode if the
3407** file size has changed. The only real difference between fdatasync()
3408** and fsync(), Ted tells us, is that fdatasync() will not flush the
3409** inode if the mtime or owner or other inode attributes have changed.
3410** We only care about the file size, not the other file attributes, so
3411** as far as SQLite is concerned, an fdatasync() is always adequate.
3412** So, we always use fdatasync() if it is available, regardless of
3413** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003414*/
3415static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003416 int rc;
drh734c9862008-11-28 15:37:20 +00003417
3418 /* The following "ifdef/elif/else/" block has the same structure as
3419 ** the one below. It is replicated here solely to avoid cluttering
3420 ** up the real code with the UNUSED_PARAMETER() macros.
3421 */
3422#ifdef SQLITE_NO_SYNC
3423 UNUSED_PARAMETER(fd);
3424 UNUSED_PARAMETER(fullSync);
3425 UNUSED_PARAMETER(dataOnly);
3426#elif HAVE_FULLFSYNC
3427 UNUSED_PARAMETER(dataOnly);
3428#else
3429 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003430 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003431#endif
3432
3433 /* Record the number of times that we do a normal fsync() and
3434 ** FULLSYNC. This is used during testing to verify that this procedure
3435 ** gets called with the correct arguments.
3436 */
3437#ifdef SQLITE_TEST
3438 if( fullSync ) sqlite3_fullsync_count++;
3439 sqlite3_sync_count++;
3440#endif
3441
3442 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3443 ** no-op
3444 */
3445#ifdef SQLITE_NO_SYNC
3446 rc = SQLITE_OK;
3447#elif HAVE_FULLFSYNC
3448 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003449 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003450 }else{
3451 rc = 1;
3452 }
3453 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003454 ** It shouldn't be possible for fullfsync to fail on the local
3455 ** file system (on OSX), so failure indicates that FULLFSYNC
3456 ** isn't supported for this file system. So, attempt an fsync
3457 ** and (for now) ignore the overhead of a superfluous fcntl call.
3458 ** It'd be better to detect fullfsync support once and avoid
3459 ** the fcntl call every time sync is called.
3460 */
drh734c9862008-11-28 15:37:20 +00003461 if( rc ) rc = fsync(fd);
3462
drh7ed97b92010-01-20 13:07:21 +00003463#elif defined(__APPLE__)
3464 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3465 ** so currently we default to the macro that redefines fdatasync to fsync
3466 */
3467 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003468#else
drh0b647ff2009-03-21 14:41:04 +00003469 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003470#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003471 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003472 rc = fsync(fd);
3473 }
drh0b647ff2009-03-21 14:41:04 +00003474#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003475#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3476
3477 if( OS_VXWORKS && rc!= -1 ){
3478 rc = 0;
3479 }
chw97185482008-11-17 08:05:31 +00003480 return rc;
drhbfe66312006-10-03 17:40:40 +00003481}
3482
drh734c9862008-11-28 15:37:20 +00003483/*
drh0059eae2011-08-08 23:48:40 +00003484** Open a file descriptor to the directory containing file zFilename.
3485** If successful, *pFd is set to the opened file descriptor and
3486** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3487** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3488** value.
3489**
drh90315a22011-08-10 01:52:12 +00003490** The directory file descriptor is used for only one thing - to
3491** fsync() a directory to make sure file creation and deletion events
3492** are flushed to disk. Such fsyncs are not needed on newer
3493** journaling filesystems, but are required on older filesystems.
3494**
3495** This routine can be overridden using the xSetSysCall interface.
3496** The ability to override this routine was added in support of the
3497** chromium sandbox. Opening a directory is a security risk (we are
3498** told) so making it overrideable allows the chromium sandbox to
3499** replace this routine with a harmless no-op. To make this routine
3500** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3501** *pFd set to a negative number.
3502**
drh0059eae2011-08-08 23:48:40 +00003503** If SQLITE_OK is returned, the caller is responsible for closing
3504** the file descriptor *pFd using close().
3505*/
3506static int openDirectory(const char *zFilename, int *pFd){
3507 int ii;
3508 int fd = -1;
3509 char zDirname[MAX_PATHNAME+1];
3510
3511 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3512 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3513 if( ii>0 ){
3514 zDirname[ii] = '\0';
3515 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3516 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003517 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3518 }
3519 }
3520 *pFd = fd;
3521 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3522}
3523
3524/*
drh734c9862008-11-28 15:37:20 +00003525** Make sure all writes to a particular file are committed to disk.
3526**
3527** If dataOnly==0 then both the file itself and its metadata (file
3528** size, access time, etc) are synced. If dataOnly!=0 then only the
3529** file data is synced.
3530**
3531** Under Unix, also make sure that the directory entry for the file
3532** has been created by fsync-ing the directory that contains the file.
3533** If we do not do this and we encounter a power failure, the directory
3534** entry for the journal might not exist after we reboot. The next
3535** SQLite to access the file will not know that the journal exists (because
3536** the directory entry for the journal was never created) and the transaction
3537** will not roll back - possibly leading to database corruption.
3538*/
3539static int unixSync(sqlite3_file *id, int flags){
3540 int rc;
3541 unixFile *pFile = (unixFile*)id;
3542
3543 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3544 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3545
3546 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3547 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3548 || (flags&0x0F)==SQLITE_SYNC_FULL
3549 );
3550
3551 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3552 ** line is to test that doing so does not cause any problems.
3553 */
3554 SimulateDiskfullError( return SQLITE_FULL );
3555
3556 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003557 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003558 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3559 SimulateIOError( rc=1 );
3560 if( rc ){
3561 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003562 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003563 }
drh0059eae2011-08-08 23:48:40 +00003564
3565 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003566 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003567 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003568 */
3569 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3570 int dirfd;
3571 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003572 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003573 rc = osOpenDirectory(pFile->zPath, &dirfd);
3574 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003575 full_fsync(dirfd, 0, 0);
3576 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003577 }else if( rc==SQLITE_CANTOPEN ){
3578 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003579 }
drh0059eae2011-08-08 23:48:40 +00003580 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003581 }
3582 return rc;
3583}
3584
3585/*
3586** Truncate an open file to a specified size
3587*/
3588static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003589 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003590 int rc;
dan6e09d692010-07-27 18:34:15 +00003591 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003592 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003593
3594 /* If the user has configured a chunk-size for this file, truncate the
3595 ** file so that it consists of an integer number of chunks (i.e. the
3596 ** actual file size after the operation may be larger than the requested
3597 ** size).
3598 */
drhb8af4b72012-04-05 20:04:39 +00003599 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003600 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3601 }
3602
drhff812312011-02-23 13:33:46 +00003603 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003604 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003605 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003606 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003607 }else{
drhd3d8c042012-05-29 17:02:40 +00003608#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003609 /* If we are doing a normal write to a database file (as opposed to
3610 ** doing a hot-journal rollback or a write to some file other than a
3611 ** normal database file) and we truncate the file to zero length,
3612 ** that effectively updates the change counter. This might happen
3613 ** when restoring a database using the backup API from a zero-length
3614 ** source.
3615 */
dan6e09d692010-07-27 18:34:15 +00003616 if( pFile->inNormalWrite && nByte==0 ){
3617 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003618 }
danf23da962013-03-23 21:00:41 +00003619#endif
danc0003312013-03-22 17:46:11 +00003620
mistachkine98844f2013-08-24 00:59:24 +00003621#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003622 /* If the file was just truncated to a size smaller than the currently
3623 ** mapped region, reduce the effective mapping size as well. SQLite will
3624 ** use read() and write() to access data beyond this point from now on.
3625 */
3626 if( nByte<pFile->mmapSize ){
3627 pFile->mmapSize = nByte;
3628 }
mistachkine98844f2013-08-24 00:59:24 +00003629#endif
drh3313b142009-11-06 04:13:18 +00003630
drh734c9862008-11-28 15:37:20 +00003631 return SQLITE_OK;
3632 }
3633}
3634
3635/*
3636** Determine the current size of a file in bytes
3637*/
3638static int unixFileSize(sqlite3_file *id, i64 *pSize){
3639 int rc;
3640 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003641 assert( id );
3642 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003643 SimulateIOError( rc=1 );
3644 if( rc!=0 ){
drh3044b512014-06-16 16:41:52 +00003645 ((unixFile*)id)->lastErrno = errno;
drh734c9862008-11-28 15:37:20 +00003646 return SQLITE_IOERR_FSTAT;
3647 }
3648 *pSize = buf.st_size;
3649
drh8af6c222010-05-14 12:43:01 +00003650 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003651 ** writes a single byte into that file in order to work around a bug
3652 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3653 ** layers, we need to report this file size as zero even though it is
3654 ** really 1. Ticket #3260.
3655 */
3656 if( *pSize==1 ) *pSize = 0;
3657
3658
3659 return SQLITE_OK;
3660}
3661
drhd2cb50b2009-01-09 21:41:17 +00003662#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003663/*
3664** Handler for proxy-locking file-control verbs. Defined below in the
3665** proxying locking division.
3666*/
3667static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003668#endif
drh715ff302008-12-03 22:32:44 +00003669
dan502019c2010-07-28 14:26:17 +00003670/*
3671** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003672** file-control operation. Enlarge the database to nBytes in size
3673** (rounded up to the next chunk-size). If the database is already
3674** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003675*/
3676static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003677 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003678 i64 nSize; /* Required file size */
3679 struct stat buf; /* Used to hold return values of fstat() */
3680
drh99ab3b12011-03-02 15:09:07 +00003681 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003682
3683 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3684 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003685
dan502019c2010-07-28 14:26:17 +00003686#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003687 /* The code below is handling the return value of osFallocate()
3688 ** correctly. posix_fallocate() is defined to "returns zero on success,
3689 ** or an error number on failure". See the manpage for details. */
3690 int err;
drhff812312011-02-23 13:33:46 +00003691 do{
dan661d71a2011-03-30 19:08:03 +00003692 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3693 }while( err==EINTR );
3694 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003695#else
3696 /* If the OS does not have posix_fallocate(), fake it. First use
3697 ** ftruncate() to set the file size, then write a single byte to
3698 ** the last byte in each block within the extended region. This
3699 ** is the same technique used by glibc to implement posix_fallocate()
3700 ** on systems that do not have a real fallocate() system call.
3701 */
3702 int nBlk = buf.st_blksize; /* File-system block size */
3703 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003704
drhff812312011-02-23 13:33:46 +00003705 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003706 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003707 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003708 }
3709 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003710 while( iWrite<nSize ){
3711 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3712 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003713 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003714 }
dan502019c2010-07-28 14:26:17 +00003715#endif
3716 }
3717 }
3718
mistachkine98844f2013-08-24 00:59:24 +00003719#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003720 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003721 int rc;
3722 if( pFile->szChunk<=0 ){
3723 if( robust_ftruncate(pFile->h, nByte) ){
3724 pFile->lastErrno = errno;
3725 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3726 }
3727 }
3728
3729 rc = unixMapfile(pFile, nByte);
3730 return rc;
3731 }
mistachkine98844f2013-08-24 00:59:24 +00003732#endif
danf23da962013-03-23 21:00:41 +00003733
dan502019c2010-07-28 14:26:17 +00003734 return SQLITE_OK;
3735}
danielk1977ad94b582007-08-20 06:44:22 +00003736
danielk1977e3026632004-06-22 11:29:02 +00003737/*
drhf12b3f62011-12-21 14:42:29 +00003738** If *pArg is inititially negative then this is a query. Set *pArg to
3739** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3740**
3741** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3742*/
3743static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3744 if( *pArg<0 ){
3745 *pArg = (pFile->ctrlFlags & mask)!=0;
3746 }else if( (*pArg)==0 ){
3747 pFile->ctrlFlags &= ~mask;
3748 }else{
3749 pFile->ctrlFlags |= mask;
3750 }
3751}
3752
drh696b33e2012-12-06 19:01:42 +00003753/* Forward declaration */
3754static int unixGetTempname(int nBuf, char *zBuf);
3755
drhf12b3f62011-12-21 14:42:29 +00003756/*
drh9e33c2c2007-08-31 18:34:59 +00003757** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003758*/
drhcc6bb3e2007-08-31 16:11:35 +00003759static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003760 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003761 switch( op ){
3762 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003763 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003764 return SQLITE_OK;
3765 }
drh7708e972008-11-29 00:56:52 +00003766 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003767 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003768 return SQLITE_OK;
3769 }
dan6e09d692010-07-27 18:34:15 +00003770 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003771 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003772 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003773 }
drh9ff27ec2010-05-19 19:26:05 +00003774 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003775 int rc;
3776 SimulateIOErrorBenign(1);
3777 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3778 SimulateIOErrorBenign(0);
3779 return rc;
drhf0b190d2011-07-26 16:03:07 +00003780 }
3781 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003782 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3783 return SQLITE_OK;
3784 }
drhcb15f352011-12-23 01:04:17 +00003785 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3786 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003787 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003788 }
drhde60fc22011-12-14 17:53:36 +00003789 case SQLITE_FCNTL_VFSNAME: {
3790 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3791 return SQLITE_OK;
3792 }
drh696b33e2012-12-06 19:01:42 +00003793 case SQLITE_FCNTL_TEMPFILENAME: {
3794 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3795 if( zTFile ){
3796 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3797 *(char**)pArg = zTFile;
3798 }
3799 return SQLITE_OK;
3800 }
drhb959a012013-12-07 12:29:22 +00003801 case SQLITE_FCNTL_HAS_MOVED: {
3802 *(int*)pArg = fileHasMoved(pFile);
3803 return SQLITE_OK;
3804 }
mistachkine98844f2013-08-24 00:59:24 +00003805#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003806 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003807 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003808 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003809 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3810 newLimit = sqlite3GlobalConfig.mxMmap;
3811 }
3812 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003813 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003814 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003815 if( pFile->mmapSize>0 ){
3816 unixUnmapfile(pFile);
3817 rc = unixMapfile(pFile, -1);
3818 }
danbcb8a862013-04-08 15:30:41 +00003819 }
drh34e258c2013-05-23 01:40:53 +00003820 return rc;
danb2d3de32013-03-14 18:34:37 +00003821 }
mistachkine98844f2013-08-24 00:59:24 +00003822#endif
drhd3d8c042012-05-29 17:02:40 +00003823#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003824 /* The pager calls this method to signal that it has done
3825 ** a rollback and that the database is therefore unchanged and
3826 ** it hence it is OK for the transaction change counter to be
3827 ** unchanged.
3828 */
3829 case SQLITE_FCNTL_DB_UNCHANGED: {
3830 ((unixFile*)id)->dbUpdate = 0;
3831 return SQLITE_OK;
3832 }
3833#endif
drhd2cb50b2009-01-09 21:41:17 +00003834#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003835 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003836 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003837 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003838 }
drhd2cb50b2009-01-09 21:41:17 +00003839#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003840 }
drh0b52b7d2011-01-26 19:46:22 +00003841 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003842}
3843
3844/*
danielk1977a3d4c882007-03-23 10:08:38 +00003845** Return the sector size in bytes of the underlying block device for
3846** the specified file. This is almost always 512 bytes, but may be
3847** larger for some devices.
3848**
3849** SQLite code assumes this function cannot fail. It also assumes that
3850** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003851** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003852** same for both.
3853*/
drh537dddf2012-10-26 13:46:24 +00003854#ifndef __QNXNTO__
3855static int unixSectorSize(sqlite3_file *NotUsed){
3856 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003857 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003858}
drh537dddf2012-10-26 13:46:24 +00003859#endif
3860
3861/*
3862** The following version of unixSectorSize() is optimized for QNX.
3863*/
3864#ifdef __QNXNTO__
3865#include <sys/dcmd_blk.h>
3866#include <sys/statvfs.h>
3867static int unixSectorSize(sqlite3_file *id){
3868 unixFile *pFile = (unixFile*)id;
3869 if( pFile->sectorSize == 0 ){
3870 struct statvfs fsInfo;
3871
3872 /* Set defaults for non-supported filesystems */
3873 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3874 pFile->deviceCharacteristics = 0;
3875 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3876 return pFile->sectorSize;
3877 }
3878
3879 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3880 pFile->sectorSize = fsInfo.f_bsize;
3881 pFile->deviceCharacteristics =
3882 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3883 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3884 ** the write succeeds */
3885 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3886 ** so it is ordered */
3887 0;
3888 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3889 pFile->sectorSize = fsInfo.f_bsize;
3890 pFile->deviceCharacteristics =
3891 /* etfs cluster size writes are atomic */
3892 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3893 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3894 ** the write succeeds */
3895 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3896 ** so it is ordered */
3897 0;
3898 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3899 pFile->sectorSize = fsInfo.f_bsize;
3900 pFile->deviceCharacteristics =
3901 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3902 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3903 ** the write succeeds */
3904 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3905 ** so it is ordered */
3906 0;
3907 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3908 pFile->sectorSize = fsInfo.f_bsize;
3909 pFile->deviceCharacteristics =
3910 /* full bitset of atomics from max sector size and smaller */
3911 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3912 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3913 ** so it is ordered */
3914 0;
3915 }else if( strstr(fsInfo.f_basetype, "dos") ){
3916 pFile->sectorSize = fsInfo.f_bsize;
3917 pFile->deviceCharacteristics =
3918 /* full bitset of atomics from max sector size and smaller */
3919 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3920 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3921 ** so it is ordered */
3922 0;
3923 }else{
3924 pFile->deviceCharacteristics =
3925 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3926 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3927 ** the write succeeds */
3928 0;
3929 }
3930 }
3931 /* Last chance verification. If the sector size isn't a multiple of 512
3932 ** then it isn't valid.*/
3933 if( pFile->sectorSize % 512 != 0 ){
3934 pFile->deviceCharacteristics = 0;
3935 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3936 }
3937 return pFile->sectorSize;
3938}
3939#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003940
danielk197790949c22007-08-17 16:50:38 +00003941/*
drhf12b3f62011-12-21 14:42:29 +00003942** Return the device characteristics for the file.
3943**
drhcb15f352011-12-23 01:04:17 +00003944** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3945** However, that choice is contraversial since technically the underlying
3946** file system does not always provide powersafe overwrites. (In other
3947** words, after a power-loss event, parts of the file that were never
3948** written might end up being altered.) However, non-PSOW behavior is very,
3949** very rare. And asserting PSOW makes a large reduction in the amount
3950** of required I/O for journaling, since a lot of padding is eliminated.
3951** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3952** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003953*/
drhf12b3f62011-12-21 14:42:29 +00003954static int unixDeviceCharacteristics(sqlite3_file *id){
3955 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003956 int rc = 0;
3957#ifdef __QNXNTO__
3958 if( p->sectorSize==0 ) unixSectorSize(id);
3959 rc = p->deviceCharacteristics;
3960#endif
drhcb15f352011-12-23 01:04:17 +00003961 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003962 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003963 }
drh537dddf2012-10-26 13:46:24 +00003964 return rc;
danielk197762079062007-08-15 17:08:46 +00003965}
3966
dan702eec12014-06-23 10:04:58 +00003967#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003968
dan702eec12014-06-23 10:04:58 +00003969/*
3970** Return the system page size.
3971**
3972** This function should not be called directly by other code in this file.
3973** Instead, it should be called via macro osGetpagesize().
3974*/
3975static int unixGetpagesize(void){
3976#if defined(_BSD_SOURCE)
3977 return getpagesize();
3978#else
3979 return (int)sysconf(_SC_PAGESIZE);
3980#endif
3981}
3982
3983#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3984
3985#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003986
3987/*
drhd91c68f2010-05-14 14:52:25 +00003988** Object used to represent an shared memory buffer.
3989**
3990** When multiple threads all reference the same wal-index, each thread
3991** has its own unixShm object, but they all point to a single instance
3992** of this unixShmNode object. In other words, each wal-index is opened
3993** only once per process.
3994**
3995** Each unixShmNode object is connected to a single unixInodeInfo object.
3996** We could coalesce this object into unixInodeInfo, but that would mean
3997** every open file that does not use shared memory (in other words, most
3998** open files) would have to carry around this extra information. So
3999** the unixInodeInfo object contains a pointer to this unixShmNode object
4000** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004001**
4002** unixMutexHeld() must be true when creating or destroying
4003** this object or while reading or writing the following fields:
4004**
4005** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004006**
4007** The following fields are read-only after the object is created:
4008**
4009** fid
4010** zFilename
4011**
drhd91c68f2010-05-14 14:52:25 +00004012** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004013** unixMutexHeld() is true when reading or writing any other field
4014** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004015*/
drhd91c68f2010-05-14 14:52:25 +00004016struct unixShmNode {
4017 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004018 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004019 char *zFilename; /* Name of the mmapped file */
4020 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004021 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004022 u16 nRegion; /* Size of array apRegion */
4023 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004024 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004025 int nRef; /* Number of unixShm objects pointing to this */
4026 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004027#ifdef SQLITE_DEBUG
4028 u8 exclMask; /* Mask of exclusive locks held */
4029 u8 sharedMask; /* Mask of shared locks held */
4030 u8 nextShmId; /* Next available unixShm.id value */
4031#endif
4032};
4033
4034/*
drhd9e5c4f2010-05-12 18:01:39 +00004035** Structure used internally by this VFS to record the state of an
4036** open shared memory connection.
4037**
drhd91c68f2010-05-14 14:52:25 +00004038** The following fields are initialized when this object is created and
4039** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004040**
drhd91c68f2010-05-14 14:52:25 +00004041** unixShm.pFile
4042** unixShm.id
4043**
4044** All other fields are read/write. The unixShm.pFile->mutex must be held
4045** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004046*/
4047struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004048 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4049 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004050 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004051 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004052 u16 sharedMask; /* Mask of shared locks held */
4053 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004054};
4055
4056/*
drhd9e5c4f2010-05-12 18:01:39 +00004057** Constants used for locking
4058*/
drhbd9676c2010-06-23 17:58:38 +00004059#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004060#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004061
drhd9e5c4f2010-05-12 18:01:39 +00004062/*
drh73b64e42010-05-30 19:55:15 +00004063** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004064**
4065** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4066** otherwise.
4067*/
4068static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004069 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4070 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004071 int ofst, /* First byte of the locking range */
4072 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004073){
4074 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004075 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004076
drhd91c68f2010-05-14 14:52:25 +00004077 /* Access to the unixShmNode object is serialized by the caller */
4078 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004079
drh73b64e42010-05-30 19:55:15 +00004080 /* Shared locks never span more than one byte */
4081 assert( n==1 || lockType!=F_RDLCK );
4082
4083 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004084 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004085
drh3cb93392011-03-12 18:10:44 +00004086 if( pShmNode->h>=0 ){
4087 /* Initialize the locking parameters */
4088 memset(&f, 0, sizeof(f));
4089 f.l_type = lockType;
4090 f.l_whence = SEEK_SET;
4091 f.l_start = ofst;
4092 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004093
drh3cb93392011-03-12 18:10:44 +00004094 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4095 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4096 }
drhd9e5c4f2010-05-12 18:01:39 +00004097
4098 /* Update the global lock state and do debug tracing */
4099#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004100 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004101 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004102 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004103 if( rc==SQLITE_OK ){
4104 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004105 OSTRACE(("unlock %d ok", ofst));
4106 pShmNode->exclMask &= ~mask;
4107 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004108 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004109 OSTRACE(("read-lock %d ok", ofst));
4110 pShmNode->exclMask &= ~mask;
4111 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004112 }else{
4113 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004114 OSTRACE(("write-lock %d ok", ofst));
4115 pShmNode->exclMask |= mask;
4116 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004117 }
4118 }else{
4119 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004120 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004121 }else if( lockType==F_RDLCK ){
4122 OSTRACE(("read-lock failed"));
4123 }else{
4124 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004125 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004126 }
4127 }
drh20e1f082010-05-31 16:10:12 +00004128 OSTRACE((" - afterwards %03x,%03x\n",
4129 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004130 }
drhd9e5c4f2010-05-12 18:01:39 +00004131#endif
4132
4133 return rc;
4134}
4135
dan781e34c2014-03-20 08:59:47 +00004136/*
dan781e34c2014-03-20 08:59:47 +00004137** Return the minimum number of 32KB shm regions that should be mapped at
4138** a time, assuming that each mapping must be an integer multiple of the
4139** current system page-size.
4140**
4141** Usually, this is 1. The exception seems to be systems that are configured
4142** to use 64KB pages - in this case each mapping must cover at least two
4143** shm regions.
4144*/
4145static int unixShmRegionPerMap(void){
4146 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004147 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004148 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4149 if( pgsz<shmsz ) return 1;
4150 return pgsz/shmsz;
4151}
drhd9e5c4f2010-05-12 18:01:39 +00004152
4153/*
drhd91c68f2010-05-14 14:52:25 +00004154** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004155**
4156** This is not a VFS shared-memory method; it is a utility function called
4157** by VFS shared-memory methods.
4158*/
drhd91c68f2010-05-14 14:52:25 +00004159static void unixShmPurge(unixFile *pFd){
4160 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004161 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004162 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004163 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004164 int i;
drhd91c68f2010-05-14 14:52:25 +00004165 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004166 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004167 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004168 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004169 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004170 }else{
4171 sqlite3_free(p->apRegion[i]);
4172 }
dan13a3cb82010-06-11 19:04:21 +00004173 }
dan18801912010-06-14 14:07:50 +00004174 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004175 if( p->h>=0 ){
4176 robust_close(pFd, p->h, __LINE__);
4177 p->h = -1;
4178 }
drhd91c68f2010-05-14 14:52:25 +00004179 p->pInode->pShmNode = 0;
4180 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004181 }
4182}
4183
4184/*
danda9fe0c2010-07-13 18:44:03 +00004185** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004186** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004187**
drh7234c6d2010-06-19 15:10:09 +00004188** The file used to implement shared-memory is in the same directory
4189** as the open database file and has the same name as the open database
4190** file with the "-shm" suffix added. For example, if the database file
4191** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004192** for shared memory will be called "/home/user1/config.db-shm".
4193**
4194** Another approach to is to use files in /dev/shm or /dev/tmp or an
4195** some other tmpfs mount. But if a file in a different directory
4196** from the database file is used, then differing access permissions
4197** or a chroot() might cause two different processes on the same
4198** database to end up using different files for shared memory -
4199** meaning that their memory would not really be shared - resulting
4200** in database corruption. Nevertheless, this tmpfs file usage
4201** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4202** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4203** option results in an incompatible build of SQLite; builds of SQLite
4204** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4205** same database file at the same time, database corruption will likely
4206** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4207** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004208**
4209** When opening a new shared-memory file, if no other instances of that
4210** file are currently open, in this process or in other processes, then
4211** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004212**
4213** If the original database file (pDbFd) is using the "unix-excl" VFS
4214** that means that an exclusive lock is held on the database file and
4215** that no other processes are able to read or write the database. In
4216** that case, we do not really need shared memory. No shared memory
4217** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004218*/
danda9fe0c2010-07-13 18:44:03 +00004219static int unixOpenSharedMemory(unixFile *pDbFd){
4220 struct unixShm *p = 0; /* The connection to be opened */
4221 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4222 int rc; /* Result code */
4223 unixInodeInfo *pInode; /* The inode of fd */
4224 char *zShmFilename; /* Name of the file used for SHM */
4225 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004226
danda9fe0c2010-07-13 18:44:03 +00004227 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004228 p = sqlite3_malloc( sizeof(*p) );
4229 if( p==0 ) return SQLITE_NOMEM;
4230 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004231 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004232
danda9fe0c2010-07-13 18:44:03 +00004233 /* Check to see if a unixShmNode object already exists. Reuse an existing
4234 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004235 */
4236 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004237 pInode = pDbFd->pInode;
4238 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004239 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004240 struct stat sStat; /* fstat() info for database file */
4241
4242 /* Call fstat() to figure out the permissions on the database file. If
4243 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004244 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004245 */
drh3cb93392011-03-12 18:10:44 +00004246 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004247 rc = SQLITE_IOERR_FSTAT;
4248 goto shm_open_err;
4249 }
4250
drha4ced192010-07-15 18:32:40 +00004251#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004252 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004253#else
drh52bcde02012-01-03 14:50:45 +00004254 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004255#endif
drh7234c6d2010-06-19 15:10:09 +00004256 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004257 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004258 rc = SQLITE_NOMEM;
4259 goto shm_open_err;
4260 }
drh9cb5a0d2012-01-05 21:19:54 +00004261 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004262 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004263#ifdef SQLITE_SHM_DIRECTORY
4264 sqlite3_snprintf(nShmFilename, zShmFilename,
4265 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4266 (u32)sStat.st_ino, (u32)sStat.st_dev);
4267#else
drh7234c6d2010-06-19 15:10:09 +00004268 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004269 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004270#endif
drhd91c68f2010-05-14 14:52:25 +00004271 pShmNode->h = -1;
4272 pDbFd->pInode->pShmNode = pShmNode;
4273 pShmNode->pInode = pDbFd->pInode;
4274 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4275 if( pShmNode->mutex==0 ){
4276 rc = SQLITE_NOMEM;
4277 goto shm_open_err;
4278 }
drhd9e5c4f2010-05-12 18:01:39 +00004279
drh3cb93392011-03-12 18:10:44 +00004280 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004281 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004282 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004283 openFlags = O_RDONLY;
4284 pShmNode->isReadonly = 1;
4285 }
4286 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004287 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004288 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4289 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004290 }
drhac7c3ac2012-02-11 19:23:48 +00004291
4292 /* If this process is running as root, make sure that the SHM file
4293 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004294 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004295 */
drhed466822012-05-31 13:10:49 +00004296 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004297
4298 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004299 ** If not, truncate the file to zero length.
4300 */
4301 rc = SQLITE_OK;
4302 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4303 if( robust_ftruncate(pShmNode->h, 0) ){
4304 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004305 }
4306 }
drh66dfec8b2011-06-01 20:01:49 +00004307 if( rc==SQLITE_OK ){
4308 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4309 }
4310 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004311 }
drhd9e5c4f2010-05-12 18:01:39 +00004312 }
4313
drhd91c68f2010-05-14 14:52:25 +00004314 /* Make the new connection a child of the unixShmNode */
4315 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004316#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004317 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004318#endif
drhd91c68f2010-05-14 14:52:25 +00004319 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004320 pDbFd->pShm = p;
4321 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004322
4323 /* The reference count on pShmNode has already been incremented under
4324 ** the cover of the unixEnterMutex() mutex and the pointer from the
4325 ** new (struct unixShm) object to the pShmNode has been set. All that is
4326 ** left to do is to link the new object into the linked list starting
4327 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4328 ** mutex.
4329 */
4330 sqlite3_mutex_enter(pShmNode->mutex);
4331 p->pNext = pShmNode->pFirst;
4332 pShmNode->pFirst = p;
4333 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004334 return SQLITE_OK;
4335
4336 /* Jump here on any error */
4337shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004338 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004339 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004340 unixLeaveMutex();
4341 return rc;
4342}
4343
4344/*
danda9fe0c2010-07-13 18:44:03 +00004345** This function is called to obtain a pointer to region iRegion of the
4346** shared-memory associated with the database file fd. Shared-memory regions
4347** are numbered starting from zero. Each shared-memory region is szRegion
4348** bytes in size.
4349**
4350** If an error occurs, an error code is returned and *pp is set to NULL.
4351**
4352** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4353** region has not been allocated (by any client, including one running in a
4354** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4355** bExtend is non-zero and the requested shared-memory region has not yet
4356** been allocated, it is allocated by this function.
4357**
4358** If the shared-memory region has already been allocated or is allocated by
4359** this call as described above, then it is mapped into this processes
4360** address space (if it is not already), *pp is set to point to the mapped
4361** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004362*/
danda9fe0c2010-07-13 18:44:03 +00004363static int unixShmMap(
4364 sqlite3_file *fd, /* Handle open on database file */
4365 int iRegion, /* Region to retrieve */
4366 int szRegion, /* Size of regions */
4367 int bExtend, /* True to extend file if necessary */
4368 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004369){
danda9fe0c2010-07-13 18:44:03 +00004370 unixFile *pDbFd = (unixFile*)fd;
4371 unixShm *p;
4372 unixShmNode *pShmNode;
4373 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004374 int nShmPerMap = unixShmRegionPerMap();
4375 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004376
danda9fe0c2010-07-13 18:44:03 +00004377 /* If the shared-memory file has not yet been opened, open it now. */
4378 if( pDbFd->pShm==0 ){
4379 rc = unixOpenSharedMemory(pDbFd);
4380 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004381 }
drhd9e5c4f2010-05-12 18:01:39 +00004382
danda9fe0c2010-07-13 18:44:03 +00004383 p = pDbFd->pShm;
4384 pShmNode = p->pShmNode;
4385 sqlite3_mutex_enter(pShmNode->mutex);
4386 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004387 assert( pShmNode->pInode==pDbFd->pInode );
4388 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4389 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004390
dan781e34c2014-03-20 08:59:47 +00004391 /* Minimum number of regions required to be mapped. */
4392 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4393
4394 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004395 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004396 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004397 struct stat sStat; /* Used by fstat() */
4398
4399 pShmNode->szRegion = szRegion;
4400
drh3cb93392011-03-12 18:10:44 +00004401 if( pShmNode->h>=0 ){
4402 /* The requested region is not mapped into this processes address space.
4403 ** Check to see if it has been allocated (i.e. if the wal-index file is
4404 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004405 */
drh3cb93392011-03-12 18:10:44 +00004406 if( osFstat(pShmNode->h, &sStat) ){
4407 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004408 goto shmpage_out;
4409 }
drh3cb93392011-03-12 18:10:44 +00004410
4411 if( sStat.st_size<nByte ){
4412 /* The requested memory region does not exist. If bExtend is set to
4413 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004414 */
dan47a2b4a2013-04-26 16:09:29 +00004415 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004416 goto shmpage_out;
4417 }
dan47a2b4a2013-04-26 16:09:29 +00004418
4419 /* Alternatively, if bExtend is true, extend the file. Do this by
4420 ** writing a single byte to the end of each (OS) page being
4421 ** allocated or extended. Technically, we need only write to the
4422 ** last page in order to extend the file. But writing to all new
4423 ** pages forces the OS to allocate them immediately, which reduces
4424 ** the chances of SIGBUS while accessing the mapped region later on.
4425 */
4426 else{
4427 static const int pgsz = 4096;
4428 int iPg;
4429
4430 /* Write to the last byte of each newly allocated or extended page */
4431 assert( (nByte % pgsz)==0 );
4432 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4433 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4434 const char *zFile = pShmNode->zFilename;
4435 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4436 goto shmpage_out;
4437 }
4438 }
drh3cb93392011-03-12 18:10:44 +00004439 }
4440 }
danda9fe0c2010-07-13 18:44:03 +00004441 }
4442
4443 /* Map the requested memory region into this processes address space. */
4444 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004445 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004446 );
4447 if( !apNew ){
4448 rc = SQLITE_IOERR_NOMEM;
4449 goto shmpage_out;
4450 }
4451 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004452 while( pShmNode->nRegion<nReqRegion ){
4453 int nMap = szRegion*nShmPerMap;
4454 int i;
drh3cb93392011-03-12 18:10:44 +00004455 void *pMem;
4456 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004457 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004458 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004459 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004460 );
4461 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004462 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004463 goto shmpage_out;
4464 }
4465 }else{
4466 pMem = sqlite3_malloc(szRegion);
4467 if( pMem==0 ){
4468 rc = SQLITE_NOMEM;
4469 goto shmpage_out;
4470 }
4471 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004472 }
dan781e34c2014-03-20 08:59:47 +00004473
4474 for(i=0; i<nShmPerMap; i++){
4475 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4476 }
4477 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004478 }
4479 }
4480
4481shmpage_out:
4482 if( pShmNode->nRegion>iRegion ){
4483 *pp = pShmNode->apRegion[iRegion];
4484 }else{
4485 *pp = 0;
4486 }
drh66dfec8b2011-06-01 20:01:49 +00004487 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004488 sqlite3_mutex_leave(pShmNode->mutex);
4489 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004490}
4491
4492/*
drhd9e5c4f2010-05-12 18:01:39 +00004493** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004494**
4495** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4496** different here than in posix. In xShmLock(), one can go from unlocked
4497** to shared and back or from unlocked to exclusive and back. But one may
4498** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004499*/
4500static int unixShmLock(
4501 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004502 int ofst, /* First lock to acquire or release */
4503 int n, /* Number of locks to acquire or release */
4504 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004505){
drh73b64e42010-05-30 19:55:15 +00004506 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4507 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4508 unixShm *pX; /* For looping over all siblings */
4509 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4510 int rc = SQLITE_OK; /* Result code */
4511 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004512
drhd91c68f2010-05-14 14:52:25 +00004513 assert( pShmNode==pDbFd->pInode->pShmNode );
4514 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004515 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004516 assert( n>=1 );
4517 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4518 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4519 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4520 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4521 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004522 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4523 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004524
drhc99597c2010-05-31 01:41:15 +00004525 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004526 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004527 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004528 if( flags & SQLITE_SHM_UNLOCK ){
4529 u16 allMask = 0; /* Mask of locks held by siblings */
4530
4531 /* See if any siblings hold this same lock */
4532 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4533 if( pX==p ) continue;
4534 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4535 allMask |= pX->sharedMask;
4536 }
4537
4538 /* Unlock the system-level locks */
4539 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004540 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004541 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004542 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004543 }
drh73b64e42010-05-30 19:55:15 +00004544
4545 /* Undo the local locks */
4546 if( rc==SQLITE_OK ){
4547 p->exclMask &= ~mask;
4548 p->sharedMask &= ~mask;
4549 }
4550 }else if( flags & SQLITE_SHM_SHARED ){
4551 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4552
4553 /* Find out which shared locks are already held by sibling connections.
4554 ** If any sibling already holds an exclusive lock, go ahead and return
4555 ** SQLITE_BUSY.
4556 */
4557 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004558 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004559 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004560 break;
4561 }
4562 allShared |= pX->sharedMask;
4563 }
4564
4565 /* Get shared locks at the system level, if necessary */
4566 if( rc==SQLITE_OK ){
4567 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004568 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004569 }else{
drh73b64e42010-05-30 19:55:15 +00004570 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004571 }
drhd9e5c4f2010-05-12 18:01:39 +00004572 }
drh73b64e42010-05-30 19:55:15 +00004573
4574 /* Get the local shared locks */
4575 if( rc==SQLITE_OK ){
4576 p->sharedMask |= mask;
4577 }
4578 }else{
4579 /* Make sure no sibling connections hold locks that will block this
4580 ** lock. If any do, return SQLITE_BUSY right away.
4581 */
4582 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004583 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4584 rc = SQLITE_BUSY;
4585 break;
4586 }
4587 }
4588
4589 /* Get the exclusive locks at the system level. Then if successful
4590 ** also mark the local connection as being locked.
4591 */
4592 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004593 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004594 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004595 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004596 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004597 }
drhd9e5c4f2010-05-12 18:01:39 +00004598 }
4599 }
drhd91c68f2010-05-14 14:52:25 +00004600 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004601 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4602 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004603 return rc;
4604}
4605
drh286a2882010-05-20 23:51:06 +00004606/*
4607** Implement a memory barrier or memory fence on shared memory.
4608**
4609** All loads and stores begun before the barrier must complete before
4610** any load or store begun after the barrier.
4611*/
4612static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004613 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004614){
drhff828942010-06-26 21:34:06 +00004615 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004616 unixEnterMutex();
4617 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004618}
4619
dan18801912010-06-14 14:07:50 +00004620/*
danda9fe0c2010-07-13 18:44:03 +00004621** Close a connection to shared-memory. Delete the underlying
4622** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004623**
4624** If there is no shared memory associated with the connection then this
4625** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004626*/
danda9fe0c2010-07-13 18:44:03 +00004627static int unixShmUnmap(
4628 sqlite3_file *fd, /* The underlying database file */
4629 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004630){
danda9fe0c2010-07-13 18:44:03 +00004631 unixShm *p; /* The connection to be closed */
4632 unixShmNode *pShmNode; /* The underlying shared-memory file */
4633 unixShm **pp; /* For looping over sibling connections */
4634 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004635
danda9fe0c2010-07-13 18:44:03 +00004636 pDbFd = (unixFile*)fd;
4637 p = pDbFd->pShm;
4638 if( p==0 ) return SQLITE_OK;
4639 pShmNode = p->pShmNode;
4640
4641 assert( pShmNode==pDbFd->pInode->pShmNode );
4642 assert( pShmNode->pInode==pDbFd->pInode );
4643
4644 /* Remove connection p from the set of connections associated
4645 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004646 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004647 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4648 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004649
danda9fe0c2010-07-13 18:44:03 +00004650 /* Free the connection p */
4651 sqlite3_free(p);
4652 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004653 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004654
4655 /* If pShmNode->nRef has reached 0, then close the underlying
4656 ** shared-memory file, too */
4657 unixEnterMutex();
4658 assert( pShmNode->nRef>0 );
4659 pShmNode->nRef--;
4660 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004661 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004662 unixShmPurge(pDbFd);
4663 }
4664 unixLeaveMutex();
4665
4666 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004667}
drh286a2882010-05-20 23:51:06 +00004668
danda9fe0c2010-07-13 18:44:03 +00004669
drhd9e5c4f2010-05-12 18:01:39 +00004670#else
drh6b017cc2010-06-14 18:01:46 +00004671# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004672# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004673# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004674# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004675#endif /* #ifndef SQLITE_OMIT_WAL */
4676
mistachkine98844f2013-08-24 00:59:24 +00004677#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004678/*
danaef49d72013-03-25 16:28:54 +00004679** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004680*/
danf23da962013-03-23 21:00:41 +00004681static void unixUnmapfile(unixFile *pFd){
4682 assert( pFd->nFetchOut==0 );
4683 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004684 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004685 pFd->pMapRegion = 0;
4686 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004687 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004688 }
4689}
dan5d8a1372013-03-19 19:28:06 +00004690
danaef49d72013-03-25 16:28:54 +00004691/*
dane6ecd662013-04-01 17:56:59 +00004692** Attempt to set the size of the memory mapping maintained by file
4693** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4694**
4695** If successful, this function sets the following variables:
4696**
4697** unixFile.pMapRegion
4698** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004699** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004700**
4701** If unsuccessful, an error message is logged via sqlite3_log() and
4702** the three variables above are zeroed. In this case SQLite should
4703** continue accessing the database using the xRead() and xWrite()
4704** methods.
4705*/
4706static void unixRemapfile(
4707 unixFile *pFd, /* File descriptor object */
4708 i64 nNew /* Required mapping size */
4709){
dan4ff7bc42013-04-02 12:04:09 +00004710 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004711 int h = pFd->h; /* File descriptor open on db file */
4712 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004713 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004714 u8 *pNew = 0; /* Location of new mapping */
4715 int flags = PROT_READ; /* Flags to pass to mmap() */
4716
4717 assert( pFd->nFetchOut==0 );
4718 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004719 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004720 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004721 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004722 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004723
4724 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4725
4726 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004727#if HAVE_MREMAP
4728 i64 nReuse = pFd->mmapSize;
4729#else
danbc760632014-03-20 09:42:09 +00004730 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004731 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004732#endif
dane6ecd662013-04-01 17:56:59 +00004733 u8 *pReq = &pOrig[nReuse];
4734
4735 /* Unmap any pages of the existing mapping that cannot be reused. */
4736 if( nReuse!=nOrig ){
4737 osMunmap(pReq, nOrig-nReuse);
4738 }
4739
4740#if HAVE_MREMAP
4741 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004742 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004743#else
4744 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4745 if( pNew!=MAP_FAILED ){
4746 if( pNew!=pReq ){
4747 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004748 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004749 }else{
4750 pNew = pOrig;
4751 }
4752 }
4753#endif
4754
dan48ccef82013-04-02 20:55:01 +00004755 /* The attempt to extend the existing mapping failed. Free it. */
4756 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004757 osMunmap(pOrig, nReuse);
4758 }
4759 }
4760
4761 /* If pNew is still NULL, try to create an entirely new mapping. */
4762 if( pNew==0 ){
4763 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004764 }
4765
dan4ff7bc42013-04-02 12:04:09 +00004766 if( pNew==MAP_FAILED ){
4767 pNew = 0;
4768 nNew = 0;
4769 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4770
4771 /* If the mmap() above failed, assume that all subsequent mmap() calls
4772 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4773 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004774 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004775 }
dane6ecd662013-04-01 17:56:59 +00004776 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004777 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004778}
4779
4780/*
danaef49d72013-03-25 16:28:54 +00004781** Memory map or remap the file opened by file-descriptor pFd (if the file
4782** is already mapped, the existing mapping is replaced by the new). Or, if
4783** there already exists a mapping for this file, and there are still
4784** outstanding xFetch() references to it, this function is a no-op.
4785**
4786** If parameter nByte is non-negative, then it is the requested size of
4787** the mapping to create. Otherwise, if nByte is less than zero, then the
4788** requested size is the size of the file on disk. The actual size of the
4789** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004790** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004791**
4792** SQLITE_OK is returned if no error occurs (even if the mapping is not
4793** recreated as a result of outstanding references) or an SQLite error
4794** code otherwise.
4795*/
danf23da962013-03-23 21:00:41 +00004796static int unixMapfile(unixFile *pFd, i64 nByte){
4797 i64 nMap = nByte;
4798 int rc;
daneb97b292013-03-20 14:26:59 +00004799
danf23da962013-03-23 21:00:41 +00004800 assert( nMap>=0 || pFd->nFetchOut==0 );
4801 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4802
4803 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004804 struct stat statbuf; /* Low-level file information */
4805 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004806 if( rc!=SQLITE_OK ){
4807 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004808 }
drh3044b512014-06-16 16:41:52 +00004809 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004810 }
drh9b4c59f2013-04-15 17:03:42 +00004811 if( nMap>pFd->mmapSizeMax ){
4812 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004813 }
4814
danf23da962013-03-23 21:00:41 +00004815 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004816 if( nMap>0 ){
4817 unixRemapfile(pFd, nMap);
4818 }else{
danb7e3a322013-03-25 20:30:13 +00004819 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004820 }
4821 }
4822
danf23da962013-03-23 21:00:41 +00004823 return SQLITE_OK;
4824}
mistachkine98844f2013-08-24 00:59:24 +00004825#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004826
danaef49d72013-03-25 16:28:54 +00004827/*
4828** If possible, return a pointer to a mapping of file fd starting at offset
4829** iOff. The mapping must be valid for at least nAmt bytes.
4830**
4831** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4832** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4833** Finally, if an error does occur, return an SQLite error code. The final
4834** value of *pp is undefined in this case.
4835**
4836** If this function does return a pointer, the caller must eventually
4837** release the reference by calling unixUnfetch().
4838*/
danf23da962013-03-23 21:00:41 +00004839static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004840#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004841 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004842#endif
danf23da962013-03-23 21:00:41 +00004843 *pp = 0;
4844
drh9b4c59f2013-04-15 17:03:42 +00004845#if SQLITE_MAX_MMAP_SIZE>0
4846 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004847 if( pFd->pMapRegion==0 ){
4848 int rc = unixMapfile(pFd, -1);
4849 if( rc!=SQLITE_OK ) return rc;
4850 }
4851 if( pFd->mmapSize >= iOff+nAmt ){
4852 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4853 pFd->nFetchOut++;
4854 }
4855 }
drh6e0b6d52013-04-09 16:19:20 +00004856#endif
danf23da962013-03-23 21:00:41 +00004857 return SQLITE_OK;
4858}
4859
danaef49d72013-03-25 16:28:54 +00004860/*
dandf737fe2013-03-25 17:00:24 +00004861** If the third argument is non-NULL, then this function releases a
4862** reference obtained by an earlier call to unixFetch(). The second
4863** argument passed to this function must be the same as the corresponding
4864** argument that was passed to the unixFetch() invocation.
4865**
4866** Or, if the third argument is NULL, then this function is being called
4867** to inform the VFS layer that, according to POSIX, any existing mapping
4868** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004869*/
dandf737fe2013-03-25 17:00:24 +00004870static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004871#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004872 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004873 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004874
danaef49d72013-03-25 16:28:54 +00004875 /* If p==0 (unmap the entire file) then there must be no outstanding
4876 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4877 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004878 assert( (p==0)==(pFd->nFetchOut==0) );
4879
dandf737fe2013-03-25 17:00:24 +00004880 /* If p!=0, it must match the iOff value. */
4881 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4882
danf23da962013-03-23 21:00:41 +00004883 if( p ){
4884 pFd->nFetchOut--;
4885 }else{
4886 unixUnmapfile(pFd);
4887 }
4888
4889 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004890#else
4891 UNUSED_PARAMETER(fd);
4892 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004893 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004894#endif
danf23da962013-03-23 21:00:41 +00004895 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004896}
4897
4898/*
drh734c9862008-11-28 15:37:20 +00004899** Here ends the implementation of all sqlite3_file methods.
4900**
4901********************** End sqlite3_file Methods *******************************
4902******************************************************************************/
4903
4904/*
drh6b9d6dd2008-12-03 19:34:47 +00004905** This division contains definitions of sqlite3_io_methods objects that
4906** implement various file locking strategies. It also contains definitions
4907** of "finder" functions. A finder-function is used to locate the appropriate
4908** sqlite3_io_methods object for a particular database file. The pAppData
4909** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4910** the correct finder-function for that VFS.
4911**
4912** Most finder functions return a pointer to a fixed sqlite3_io_methods
4913** object. The only interesting finder-function is autolockIoFinder, which
4914** looks at the filesystem type and tries to guess the best locking
4915** strategy from that.
4916**
drh1875f7a2008-12-08 18:19:17 +00004917** For finder-funtion F, two objects are created:
4918**
4919** (1) The real finder-function named "FImpt()".
4920**
dane946c392009-08-22 11:39:46 +00004921** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004922**
4923**
4924** A pointer to the F pointer is used as the pAppData value for VFS
4925** objects. We have to do this instead of letting pAppData point
4926** directly at the finder-function since C90 rules prevent a void*
4927** from be cast into a function pointer.
4928**
drh6b9d6dd2008-12-03 19:34:47 +00004929**
drh7708e972008-11-29 00:56:52 +00004930** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004931**
drh7708e972008-11-29 00:56:52 +00004932** * A constant sqlite3_io_methods object call METHOD that has locking
4933** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4934**
4935** * An I/O method finder function called FINDER that returns a pointer
4936** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004937*/
drhd9e5c4f2010-05-12 18:01:39 +00004938#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004939static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004940 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004941 CLOSE, /* xClose */ \
4942 unixRead, /* xRead */ \
4943 unixWrite, /* xWrite */ \
4944 unixTruncate, /* xTruncate */ \
4945 unixSync, /* xSync */ \
4946 unixFileSize, /* xFileSize */ \
4947 LOCK, /* xLock */ \
4948 UNLOCK, /* xUnlock */ \
4949 CKLOCK, /* xCheckReservedLock */ \
4950 unixFileControl, /* xFileControl */ \
4951 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004952 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004953 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004954 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004955 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004956 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004957 unixFetch, /* xFetch */ \
4958 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004959}; \
drh0c2694b2009-09-03 16:23:44 +00004960static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4961 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004962 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004963} \
drh0c2694b2009-09-03 16:23:44 +00004964static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004965 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004966
4967/*
4968** Here are all of the sqlite3_io_methods objects for each of the
4969** locking strategies. Functions that return pointers to these methods
4970** are also created.
4971*/
4972IOMETHODS(
4973 posixIoFinder, /* Finder function name */
4974 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004975 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004976 unixClose, /* xClose method */
4977 unixLock, /* xLock method */
4978 unixUnlock, /* xUnlock method */
4979 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004980)
drh7708e972008-11-29 00:56:52 +00004981IOMETHODS(
4982 nolockIoFinder, /* Finder function name */
4983 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004984 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004985 nolockClose, /* xClose method */
4986 nolockLock, /* xLock method */
4987 nolockUnlock, /* xUnlock method */
4988 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004989)
drh7708e972008-11-29 00:56:52 +00004990IOMETHODS(
4991 dotlockIoFinder, /* Finder function name */
4992 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004993 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004994 dotlockClose, /* xClose method */
4995 dotlockLock, /* xLock method */
4996 dotlockUnlock, /* xUnlock method */
4997 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004998)
drh7708e972008-11-29 00:56:52 +00004999
chw78a13182009-04-07 05:35:03 +00005000#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005001IOMETHODS(
5002 flockIoFinder, /* Finder function name */
5003 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005004 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005005 flockClose, /* xClose method */
5006 flockLock, /* xLock method */
5007 flockUnlock, /* xUnlock method */
5008 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005009)
drh7708e972008-11-29 00:56:52 +00005010#endif
5011
drh6c7d5c52008-11-21 20:32:33 +00005012#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005013IOMETHODS(
5014 semIoFinder, /* Finder function name */
5015 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005016 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005017 semClose, /* xClose method */
5018 semLock, /* xLock method */
5019 semUnlock, /* xUnlock method */
5020 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005021)
aswiftaebf4132008-11-21 00:10:35 +00005022#endif
drh7708e972008-11-29 00:56:52 +00005023
drhd2cb50b2009-01-09 21:41:17 +00005024#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005025IOMETHODS(
5026 afpIoFinder, /* Finder function name */
5027 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005028 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005029 afpClose, /* xClose method */
5030 afpLock, /* xLock method */
5031 afpUnlock, /* xUnlock method */
5032 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005033)
drh715ff302008-12-03 22:32:44 +00005034#endif
5035
5036/*
5037** The proxy locking method is a "super-method" in the sense that it
5038** opens secondary file descriptors for the conch and lock files and
5039** it uses proxy, dot-file, AFP, and flock() locking methods on those
5040** secondary files. For this reason, the division that implements
5041** proxy locking is located much further down in the file. But we need
5042** to go ahead and define the sqlite3_io_methods and finder function
5043** for proxy locking here. So we forward declare the I/O methods.
5044*/
drhd2cb50b2009-01-09 21:41:17 +00005045#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005046static int proxyClose(sqlite3_file*);
5047static int proxyLock(sqlite3_file*, int);
5048static int proxyUnlock(sqlite3_file*, int);
5049static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005050IOMETHODS(
5051 proxyIoFinder, /* Finder function name */
5052 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005053 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005054 proxyClose, /* xClose method */
5055 proxyLock, /* xLock method */
5056 proxyUnlock, /* xUnlock method */
5057 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005058)
aswiftaebf4132008-11-21 00:10:35 +00005059#endif
drh7708e972008-11-29 00:56:52 +00005060
drh7ed97b92010-01-20 13:07:21 +00005061/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5062#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5063IOMETHODS(
5064 nfsIoFinder, /* Finder function name */
5065 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005066 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005067 unixClose, /* xClose method */
5068 unixLock, /* xLock method */
5069 nfsUnlock, /* xUnlock method */
5070 unixCheckReservedLock /* xCheckReservedLock method */
5071)
5072#endif
drh7708e972008-11-29 00:56:52 +00005073
drhd2cb50b2009-01-09 21:41:17 +00005074#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005075/*
drh6b9d6dd2008-12-03 19:34:47 +00005076** This "finder" function attempts to determine the best locking strategy
5077** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005078** object that implements that strategy.
5079**
5080** This is for MacOSX only.
5081*/
drh1875f7a2008-12-08 18:19:17 +00005082static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005083 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005084 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005085){
5086 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005087 const char *zFilesystem; /* Filesystem type name */
5088 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005089 } aMap[] = {
5090 { "hfs", &posixIoMethods },
5091 { "ufs", &posixIoMethods },
5092 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005093 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005094 { "webdav", &nolockIoMethods },
5095 { 0, 0 }
5096 };
5097 int i;
5098 struct statfs fsInfo;
5099 struct flock lockInfo;
5100
5101 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005102 /* If filePath==NULL that means we are dealing with a transient file
5103 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005104 return &nolockIoMethods;
5105 }
5106 if( statfs(filePath, &fsInfo) != -1 ){
5107 if( fsInfo.f_flags & MNT_RDONLY ){
5108 return &nolockIoMethods;
5109 }
5110 for(i=0; aMap[i].zFilesystem; i++){
5111 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5112 return aMap[i].pMethods;
5113 }
5114 }
5115 }
5116
5117 /* Default case. Handles, amongst others, "nfs".
5118 ** Test byte-range lock using fcntl(). If the call succeeds,
5119 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005120 */
drh7708e972008-11-29 00:56:52 +00005121 lockInfo.l_len = 1;
5122 lockInfo.l_start = 0;
5123 lockInfo.l_whence = SEEK_SET;
5124 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005125 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005126 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5127 return &nfsIoMethods;
5128 } else {
5129 return &posixIoMethods;
5130 }
drh7708e972008-11-29 00:56:52 +00005131 }else{
5132 return &dotlockIoMethods;
5133 }
5134}
drh0c2694b2009-09-03 16:23:44 +00005135static const sqlite3_io_methods
5136 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005137
drhd2cb50b2009-01-09 21:41:17 +00005138#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005139
chw78a13182009-04-07 05:35:03 +00005140#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5141/*
5142** This "finder" function attempts to determine the best locking strategy
5143** for the database file "filePath". It then returns the sqlite3_io_methods
5144** object that implements that strategy.
5145**
5146** This is for VXWorks only.
5147*/
5148static const sqlite3_io_methods *autolockIoFinderImpl(
5149 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005150 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005151){
5152 struct flock lockInfo;
5153
5154 if( !filePath ){
5155 /* If filePath==NULL that means we are dealing with a transient file
5156 ** that does not need to be locked. */
5157 return &nolockIoMethods;
5158 }
5159
5160 /* Test if fcntl() is supported and use POSIX style locks.
5161 ** Otherwise fall back to the named semaphore method.
5162 */
5163 lockInfo.l_len = 1;
5164 lockInfo.l_start = 0;
5165 lockInfo.l_whence = SEEK_SET;
5166 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005167 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005168 return &posixIoMethods;
5169 }else{
5170 return &semIoMethods;
5171 }
5172}
drh0c2694b2009-09-03 16:23:44 +00005173static const sqlite3_io_methods
5174 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005175
5176#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5177
drh7708e972008-11-29 00:56:52 +00005178/*
5179** An abstract type for a pointer to a IO method finder function:
5180*/
drh0c2694b2009-09-03 16:23:44 +00005181typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005182
aswiftaebf4132008-11-21 00:10:35 +00005183
drh734c9862008-11-28 15:37:20 +00005184/****************************************************************************
5185**************************** sqlite3_vfs methods ****************************
5186**
5187** This division contains the implementation of methods on the
5188** sqlite3_vfs object.
5189*/
5190
danielk1977a3d4c882007-03-23 10:08:38 +00005191/*
danielk1977e339d652008-06-28 11:23:00 +00005192** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005193*/
5194static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005195 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005196 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005197 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005198 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005199 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005200){
drh7708e972008-11-29 00:56:52 +00005201 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005202 unixFile *pNew = (unixFile *)pId;
5203 int rc = SQLITE_OK;
5204
drh8af6c222010-05-14 12:43:01 +00005205 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005206
dan00157392010-10-05 11:33:15 +00005207 /* Usually the path zFilename should not be a relative pathname. The
5208 ** exception is when opening the proxy "conch" file in builds that
5209 ** include the special Apple locking styles.
5210 */
dan00157392010-10-05 11:33:15 +00005211#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005212 assert( zFilename==0 || zFilename[0]=='/'
5213 || pVfs->pAppData==(void*)&autolockIoFinder );
5214#else
5215 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005216#endif
dan00157392010-10-05 11:33:15 +00005217
drhb07028f2011-10-14 21:49:18 +00005218 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005219 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005220
drh308c2a52010-05-14 11:30:18 +00005221 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005222 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005223 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005224 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005225 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005226#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005227 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005228#endif
drhc02a43a2012-01-10 23:18:38 +00005229 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5230 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005231 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005232 }
drh503a6862013-03-01 01:07:17 +00005233 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005234 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005235 }
drh339eb0b2008-03-07 15:34:11 +00005236
drh6c7d5c52008-11-21 20:32:33 +00005237#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005238 pNew->pId = vxworksFindFileId(zFilename);
5239 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005240 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005241 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005242 }
5243#endif
5244
drhc02a43a2012-01-10 23:18:38 +00005245 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005246 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005247 }else{
drh0c2694b2009-09-03 16:23:44 +00005248 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005249#if SQLITE_ENABLE_LOCKING_STYLE
5250 /* Cache zFilename in the locking context (AFP and dotlock override) for
5251 ** proxyLock activation is possible (remote proxy is based on db name)
5252 ** zFilename remains valid until file is closed, to support */
5253 pNew->lockingContext = (void*)zFilename;
5254#endif
drhda0e7682008-07-30 15:27:54 +00005255 }
danielk1977e339d652008-06-28 11:23:00 +00005256
drh7ed97b92010-01-20 13:07:21 +00005257 if( pLockingStyle == &posixIoMethods
5258#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5259 || pLockingStyle == &nfsIoMethods
5260#endif
5261 ){
drh7708e972008-11-29 00:56:52 +00005262 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005263 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005264 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005265 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005266 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005267 ** in two scenarios:
5268 **
5269 ** (a) A call to fstat() failed.
5270 ** (b) A malloc failed.
5271 **
5272 ** Scenario (b) may only occur if the process is holding no other
5273 ** file descriptors open on the same file. If there were other file
5274 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005275 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005276 ** handle h - as it is guaranteed that no posix locks will be released
5277 ** by doing so.
5278 **
5279 ** If scenario (a) caused the error then things are not so safe. The
5280 ** implicit assumption here is that if fstat() fails, things are in
5281 ** such bad shape that dropping a lock or two doesn't matter much.
5282 */
drh0e9365c2011-03-02 02:08:13 +00005283 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005284 h = -1;
5285 }
drh7708e972008-11-29 00:56:52 +00005286 unixLeaveMutex();
5287 }
danielk1977e339d652008-06-28 11:23:00 +00005288
drhd2cb50b2009-01-09 21:41:17 +00005289#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005290 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005291 /* AFP locking uses the file path so it needs to be included in
5292 ** the afpLockingContext.
5293 */
5294 afpLockingContext *pCtx;
5295 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5296 if( pCtx==0 ){
5297 rc = SQLITE_NOMEM;
5298 }else{
5299 /* NB: zFilename exists and remains valid until the file is closed
5300 ** according to requirement F11141. So we do not need to make a
5301 ** copy of the filename. */
5302 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005303 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005304 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005305 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005306 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005307 if( rc!=SQLITE_OK ){
5308 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005309 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005310 h = -1;
5311 }
drh7708e972008-11-29 00:56:52 +00005312 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005313 }
drh7708e972008-11-29 00:56:52 +00005314 }
5315#endif
danielk1977e339d652008-06-28 11:23:00 +00005316
drh7708e972008-11-29 00:56:52 +00005317 else if( pLockingStyle == &dotlockIoMethods ){
5318 /* Dotfile locking uses the file path so it needs to be included in
5319 ** the dotlockLockingContext
5320 */
5321 char *zLockFile;
5322 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005323 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005324 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005325 zLockFile = (char *)sqlite3_malloc(nFilename);
5326 if( zLockFile==0 ){
5327 rc = SQLITE_NOMEM;
5328 }else{
5329 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005330 }
drh7708e972008-11-29 00:56:52 +00005331 pNew->lockingContext = zLockFile;
5332 }
danielk1977e339d652008-06-28 11:23:00 +00005333
drh6c7d5c52008-11-21 20:32:33 +00005334#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005335 else if( pLockingStyle == &semIoMethods ){
5336 /* Named semaphore locking uses the file path so it needs to be
5337 ** included in the semLockingContext
5338 */
5339 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005340 rc = findInodeInfo(pNew, &pNew->pInode);
5341 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5342 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005343 int n;
drh2238dcc2009-08-27 17:56:20 +00005344 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005345 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005346 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005347 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005348 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5349 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005350 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005351 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005352 }
chw97185482008-11-17 08:05:31 +00005353 }
drh7708e972008-11-29 00:56:52 +00005354 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005355 }
drh7708e972008-11-29 00:56:52 +00005356#endif
aswift5b1a2562008-08-22 00:22:35 +00005357
5358 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005359#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005360 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005361 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005362 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005363 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005364 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005365 }
chw97185482008-11-17 08:05:31 +00005366#endif
danielk1977e339d652008-06-28 11:23:00 +00005367 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005368 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005369 }else{
drh7708e972008-11-29 00:56:52 +00005370 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005371 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005372 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005373 }
danielk1977e339d652008-06-28 11:23:00 +00005374 return rc;
drh054889e2005-11-30 03:20:31 +00005375}
drh9c06c952005-11-26 00:25:00 +00005376
danielk1977ad94b582007-08-20 06:44:22 +00005377/*
drh8b3cf822010-06-01 21:02:51 +00005378** Return the name of a directory in which to put temporary files.
5379** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005380*/
drh7234c6d2010-06-19 15:10:09 +00005381static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005382 static const char *azDirs[] = {
5383 0,
aswiftaebf4132008-11-21 00:10:35 +00005384 0,
mistachkind95a3d32013-08-30 21:52:38 +00005385 0,
danielk197717b90b52008-06-06 11:11:25 +00005386 "/var/tmp",
5387 "/usr/tmp",
5388 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005389 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005390 };
drh8b3cf822010-06-01 21:02:51 +00005391 unsigned int i;
5392 struct stat buf;
5393 const char *zDir = 0;
5394
5395 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005396 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5397 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005398 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005399 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005400 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005401 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005402 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005403 break;
5404 }
5405 return zDir;
5406}
5407
5408/*
5409** Create a temporary file name in zBuf. zBuf must be allocated
5410** by the calling process and must be big enough to hold at least
5411** pVfs->mxPathname bytes.
5412*/
5413static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005414 static const unsigned char zChars[] =
5415 "abcdefghijklmnopqrstuvwxyz"
5416 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5417 "0123456789";
drh41022642008-11-21 00:24:42 +00005418 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005419 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005420
5421 /* It's odd to simulate an io-error here, but really this is just
5422 ** using the io-error infrastructure to test that SQLite handles this
5423 ** function failing.
5424 */
5425 SimulateIOError( return SQLITE_IOERR );
5426
drh7234c6d2010-06-19 15:10:09 +00005427 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005428 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005429
5430 /* Check that the output buffer is large enough for the temporary file
5431 ** name. If it is not, return SQLITE_ERROR.
5432 */
drhc02a43a2012-01-10 23:18:38 +00005433 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005434 return SQLITE_ERROR;
5435 }
5436
5437 do{
drhc02a43a2012-01-10 23:18:38 +00005438 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005439 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005440 sqlite3_randomness(15, &zBuf[j]);
5441 for(i=0; i<15; i++, j++){
5442 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5443 }
5444 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005445 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005446 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005447 return SQLITE_OK;
5448}
5449
drhd2cb50b2009-01-09 21:41:17 +00005450#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005451/*
5452** Routine to transform a unixFile into a proxy-locking unixFile.
5453** Implementation in the proxy-lock division, but used by unixOpen()
5454** if SQLITE_PREFER_PROXY_LOCKING is defined.
5455*/
5456static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005457#endif
drhc66d5b62008-12-03 22:48:32 +00005458
dan08da86a2009-08-21 17:18:03 +00005459/*
5460** Search for an unused file descriptor that was opened on the database
5461** file (not a journal or master-journal file) identified by pathname
5462** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5463** argument to this function.
5464**
5465** Such a file descriptor may exist if a database connection was closed
5466** but the associated file descriptor could not be closed because some
5467** other file descriptor open on the same file is holding a file-lock.
5468** Refer to comments in the unixClose() function and the lengthy comment
5469** describing "Posix Advisory Locking" at the start of this file for
5470** further details. Also, ticket #4018.
5471**
5472** If a suitable file descriptor is found, then it is returned. If no
5473** such file descriptor is located, -1 is returned.
5474*/
dane946c392009-08-22 11:39:46 +00005475static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5476 UnixUnusedFd *pUnused = 0;
5477
5478 /* Do not search for an unused file descriptor on vxworks. Not because
5479 ** vxworks would not benefit from the change (it might, we're not sure),
5480 ** but because no way to test it is currently available. It is better
5481 ** not to risk breaking vxworks support for the sake of such an obscure
5482 ** feature. */
5483#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005484 struct stat sStat; /* Results of stat() call */
5485
5486 /* A stat() call may fail for various reasons. If this happens, it is
5487 ** almost certain that an open() call on the same path will also fail.
5488 ** For this reason, if an error occurs in the stat() call here, it is
5489 ** ignored and -1 is returned. The caller will try to open a new file
5490 ** descriptor on the same path, fail, and return an error to SQLite.
5491 **
5492 ** Even if a subsequent open() call does succeed, the consequences of
5493 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005494 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005495 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005496
5497 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005498 pInode = inodeList;
5499 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5500 || pInode->fileId.ino!=sStat.st_ino) ){
5501 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005502 }
drh8af6c222010-05-14 12:43:01 +00005503 if( pInode ){
dane946c392009-08-22 11:39:46 +00005504 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005505 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005506 pUnused = *pp;
5507 if( pUnused ){
5508 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005509 }
5510 }
5511 unixLeaveMutex();
5512 }
dane946c392009-08-22 11:39:46 +00005513#endif /* if !OS_VXWORKS */
5514 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005515}
danielk197717b90b52008-06-06 11:11:25 +00005516
5517/*
danddb0ac42010-07-14 14:48:58 +00005518** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005519** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005520** and a value suitable for passing as the third argument to open(2) is
5521** written to *pMode. If an IO error occurs, an SQLite error code is
5522** returned and the value of *pMode is not modified.
5523**
drh8c815d12012-02-13 20:16:37 +00005524** In most cases cases, this routine sets *pMode to 0, which will become
5525** an indication to robust_open() to create the file using
5526** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5527** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005528** this function queries the file-system for the permissions on the
5529** corresponding database file and sets *pMode to this value. Whenever
5530** possible, WAL and journal files are created using the same permissions
5531** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005532**
5533** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5534** original filename is unavailable. But 8_3_NAMES is only used for
5535** FAT filesystems and permissions do not matter there, so just use
5536** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005537*/
5538static int findCreateFileMode(
5539 const char *zPath, /* Path of file (possibly) being created */
5540 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005541 mode_t *pMode, /* OUT: Permissions to open file with */
5542 uid_t *pUid, /* OUT: uid to set on the file */
5543 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005544){
5545 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005546 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005547 *pUid = 0;
5548 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005549 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005550 char zDb[MAX_PATHNAME+1]; /* Database file path */
5551 int nDb; /* Number of valid bytes in zDb */
5552 struct stat sStat; /* Output of stat() on database file */
5553
dana0c989d2010-11-05 18:07:37 +00005554 /* zPath is a path to a WAL or journal file. The following block derives
5555 ** the path to the associated database file from zPath. This block handles
5556 ** the following naming conventions:
5557 **
5558 ** "<path to db>-journal"
5559 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005560 ** "<path to db>-journalNN"
5561 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005562 **
drhd337c5b2011-10-20 18:23:35 +00005563 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005564 ** used by the test_multiplex.c module.
5565 */
5566 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005567#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005568 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005569 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005570#else
5571 while( zPath[nDb]!='-' ){
5572 assert( nDb>0 );
5573 assert( zPath[nDb]!='\n' );
5574 nDb--;
5575 }
5576#endif
danddb0ac42010-07-14 14:48:58 +00005577 memcpy(zDb, zPath, nDb);
5578 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005579
drh58384f12011-07-28 00:14:45 +00005580 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005581 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005582 *pUid = sStat.st_uid;
5583 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005584 }else{
5585 rc = SQLITE_IOERR_FSTAT;
5586 }
5587 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5588 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005589 }
5590 return rc;
5591}
5592
5593/*
danielk1977ad94b582007-08-20 06:44:22 +00005594** Open the file zPath.
5595**
danielk1977b4b47412007-08-17 15:53:36 +00005596** Previously, the SQLite OS layer used three functions in place of this
5597** one:
5598**
5599** sqlite3OsOpenReadWrite();
5600** sqlite3OsOpenReadOnly();
5601** sqlite3OsOpenExclusive();
5602**
5603** These calls correspond to the following combinations of flags:
5604**
5605** ReadWrite() -> (READWRITE | CREATE)
5606** ReadOnly() -> (READONLY)
5607** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5608**
5609** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5610** true, the file was configured to be automatically deleted when the
5611** file handle closed. To achieve the same effect using this new
5612** interface, add the DELETEONCLOSE flag to those specified above for
5613** OpenExclusive().
5614*/
5615static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005616 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5617 const char *zPath, /* Pathname of file to be opened */
5618 sqlite3_file *pFile, /* The file descriptor to be filled in */
5619 int flags, /* Input flags to control the opening */
5620 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005621){
dan08da86a2009-08-21 17:18:03 +00005622 unixFile *p = (unixFile *)pFile;
5623 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005624 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005625 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005626 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005627 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005628 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005629
5630 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5631 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5632 int isCreate = (flags & SQLITE_OPEN_CREATE);
5633 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5634 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005635#if SQLITE_ENABLE_LOCKING_STYLE
5636 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5637#endif
drh3d4435b2011-08-26 20:55:50 +00005638#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5639 struct statfs fsInfo;
5640#endif
danielk1977b4b47412007-08-17 15:53:36 +00005641
danielk1977fee2d252007-08-18 10:59:19 +00005642 /* If creating a master or main-file journal, this function will open
5643 ** a file-descriptor on the directory too. The first time unixSync()
5644 ** is called the directory file descriptor will be fsync()ed and close()d.
5645 */
drh0059eae2011-08-08 23:48:40 +00005646 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005647 eType==SQLITE_OPEN_MASTER_JOURNAL
5648 || eType==SQLITE_OPEN_MAIN_JOURNAL
5649 || eType==SQLITE_OPEN_WAL
5650 ));
danielk1977fee2d252007-08-18 10:59:19 +00005651
danielk197717b90b52008-06-06 11:11:25 +00005652 /* If argument zPath is a NULL pointer, this function is required to open
5653 ** a temporary file. Use this buffer to store the file name in.
5654 */
drhc02a43a2012-01-10 23:18:38 +00005655 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005656 const char *zName = zPath;
5657
danielk1977fee2d252007-08-18 10:59:19 +00005658 /* Check the following statements are true:
5659 **
5660 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5661 ** (b) if CREATE is set, then READWRITE must also be set, and
5662 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005663 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005664 */
danielk1977b4b47412007-08-17 15:53:36 +00005665 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005666 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005667 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005668 assert(isDelete==0 || isCreate);
5669
danddb0ac42010-07-14 14:48:58 +00005670 /* The main DB, main journal, WAL file and master journal are never
5671 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005672 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5673 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5674 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005675 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005676
danielk1977fee2d252007-08-18 10:59:19 +00005677 /* Assert that the upper layer has set one of the "file-type" flags. */
5678 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5679 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5680 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005681 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005682 );
5683
drhb00d8622014-01-01 15:18:36 +00005684 /* Detect a pid change and reset the PRNG. There is a race condition
5685 ** here such that two or more threads all trying to open databases at
5686 ** the same instant might all reset the PRNG. But multiple resets
5687 ** are harmless.
5688 */
5689 if( randomnessPid!=getpid() ){
5690 randomnessPid = getpid();
5691 sqlite3_randomness(0,0);
5692 }
5693
dan08da86a2009-08-21 17:18:03 +00005694 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005695
dan08da86a2009-08-21 17:18:03 +00005696 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005697 UnixUnusedFd *pUnused;
5698 pUnused = findReusableFd(zName, flags);
5699 if( pUnused ){
5700 fd = pUnused->fd;
5701 }else{
dan6aa657f2009-08-24 18:57:58 +00005702 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005703 if( !pUnused ){
5704 return SQLITE_NOMEM;
5705 }
5706 }
5707 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005708
5709 /* Database filenames are double-zero terminated if they are not
5710 ** URIs with parameters. Hence, they can always be passed into
5711 ** sqlite3_uri_parameter(). */
5712 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5713
dan08da86a2009-08-21 17:18:03 +00005714 }else if( !zName ){
5715 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005716 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005717 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005718 if( rc!=SQLITE_OK ){
5719 return rc;
5720 }
5721 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005722
5723 /* Generated temporary filenames are always double-zero terminated
5724 ** for use by sqlite3_uri_parameter(). */
5725 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005726 }
5727
dan08da86a2009-08-21 17:18:03 +00005728 /* Determine the value of the flags parameter passed to POSIX function
5729 ** open(). These must be calculated even if open() is not called, as
5730 ** they may be stored as part of the file handle and used by the
5731 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005732 if( isReadonly ) openFlags |= O_RDONLY;
5733 if( isReadWrite ) openFlags |= O_RDWR;
5734 if( isCreate ) openFlags |= O_CREAT;
5735 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5736 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005737
danielk1977b4b47412007-08-17 15:53:36 +00005738 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005739 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005740 uid_t uid; /* Userid for the file */
5741 gid_t gid; /* Groupid for the file */
5742 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005743 if( rc!=SQLITE_OK ){
5744 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005745 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005746 return rc;
5747 }
drhad4f1e52011-03-04 15:43:57 +00005748 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005749 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005750 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5751 /* Failed to open the file for read/write access. Try read-only. */
5752 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005753 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005754 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005755 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005756 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005757 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005758 }
5759 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005760 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005761 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005762 }
drhac7c3ac2012-02-11 19:23:48 +00005763
5764 /* If this process is running as root and if creating a new rollback
5765 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005766 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005767 */
5768 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005769 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005770 }
danielk1977b4b47412007-08-17 15:53:36 +00005771 }
dan08da86a2009-08-21 17:18:03 +00005772 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005773 if( pOutFlags ){
5774 *pOutFlags = flags;
5775 }
5776
dane946c392009-08-22 11:39:46 +00005777 if( p->pUnused ){
5778 p->pUnused->fd = fd;
5779 p->pUnused->flags = flags;
5780 }
5781
danielk1977b4b47412007-08-17 15:53:36 +00005782 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005783#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005784 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005785#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5786 zPath = sqlite3_mprintf("%s", zName);
5787 if( zPath==0 ){
5788 robust_close(p, fd, __LINE__);
5789 return SQLITE_NOMEM;
5790 }
chw97185482008-11-17 08:05:31 +00005791#else
drh036ac7f2011-08-08 23:18:05 +00005792 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005793#endif
danielk1977b4b47412007-08-17 15:53:36 +00005794 }
drh41022642008-11-21 00:24:42 +00005795#if SQLITE_ENABLE_LOCKING_STYLE
5796 else{
dan08da86a2009-08-21 17:18:03 +00005797 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005798 }
5799#endif
5800
drhda0e7682008-07-30 15:27:54 +00005801 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005802
drh7ed97b92010-01-20 13:07:21 +00005803
5804#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005805 if( fstatfs(fd, &fsInfo) == -1 ){
5806 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005807 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005808 return SQLITE_IOERR_ACCESS;
5809 }
5810 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5811 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5812 }
5813#endif
drhc02a43a2012-01-10 23:18:38 +00005814
5815 /* Set up appropriate ctrlFlags */
5816 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5817 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5818 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5819 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5820 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5821
drh7ed97b92010-01-20 13:07:21 +00005822#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005823#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005824 isAutoProxy = 1;
5825#endif
5826 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005827 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5828 int useProxy = 0;
5829
dan08da86a2009-08-21 17:18:03 +00005830 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5831 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005832 if( envforce!=NULL ){
5833 useProxy = atoi(envforce)>0;
5834 }else{
aswiftaebf4132008-11-21 00:10:35 +00005835 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005836 /* In theory, the close(fd) call is sub-optimal. If the file opened
5837 ** with fd is a database file, and there are other connections open
5838 ** on that file that are currently holding advisory locks on it,
5839 ** then the call to close() will cancel those locks. In practice,
5840 ** we're assuming that statfs() doesn't fail very often. At least
5841 ** not while other file descriptors opened by the same process on
5842 ** the same file are working. */
5843 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005844 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005845 rc = SQLITE_IOERR_ACCESS;
5846 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005847 }
5848 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5849 }
5850 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005851 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005852 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005853 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005854 if( rc!=SQLITE_OK ){
5855 /* Use unixClose to clean up the resources added in fillInUnixFile
5856 ** and clear all the structure's references. Specifically,
5857 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5858 */
5859 unixClose(pFile);
5860 return rc;
5861 }
aswiftaebf4132008-11-21 00:10:35 +00005862 }
dane946c392009-08-22 11:39:46 +00005863 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005864 }
5865 }
5866#endif
5867
drhc02a43a2012-01-10 23:18:38 +00005868 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5869
dane946c392009-08-22 11:39:46 +00005870open_finished:
5871 if( rc!=SQLITE_OK ){
5872 sqlite3_free(p->pUnused);
5873 }
5874 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005875}
5876
dane946c392009-08-22 11:39:46 +00005877
danielk1977b4b47412007-08-17 15:53:36 +00005878/*
danielk1977fee2d252007-08-18 10:59:19 +00005879** Delete the file at zPath. If the dirSync argument is true, fsync()
5880** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005881*/
drh6b9d6dd2008-12-03 19:34:47 +00005882static int unixDelete(
5883 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5884 const char *zPath, /* Name of file to be deleted */
5885 int dirSync /* If true, fsync() directory after deleting file */
5886){
danielk1977fee2d252007-08-18 10:59:19 +00005887 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005888 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005889 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005890 if( osUnlink(zPath)==(-1) ){
5891 if( errno==ENOENT ){
5892 rc = SQLITE_IOERR_DELETE_NOENT;
5893 }else{
drhb4308162012-11-09 21:40:02 +00005894 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005895 }
drhb4308162012-11-09 21:40:02 +00005896 return rc;
drh5d4feff2010-07-14 01:45:22 +00005897 }
danielk1977d39fa702008-10-16 13:27:40 +00005898#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005899 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005900 int fd;
drh90315a22011-08-10 01:52:12 +00005901 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005902 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005903#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005904 if( fsync(fd)==-1 )
5905#else
5906 if( fsync(fd) )
5907#endif
5908 {
dane18d4952011-02-21 11:46:24 +00005909 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005910 }
drh0e9365c2011-03-02 02:08:13 +00005911 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005912 }else if( rc==SQLITE_CANTOPEN ){
5913 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005914 }
5915 }
danielk1977d138dd82008-10-15 16:02:48 +00005916#endif
danielk1977fee2d252007-08-18 10:59:19 +00005917 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005918}
5919
danielk197790949c22007-08-17 16:50:38 +00005920/*
mistachkin48864df2013-03-21 21:20:32 +00005921** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005922** test performed depends on the value of flags:
5923**
5924** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5925** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5926** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5927**
5928** Otherwise return 0.
5929*/
danielk1977861f7452008-06-05 11:39:11 +00005930static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005931 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5932 const char *zPath, /* Path of the file to examine */
5933 int flags, /* What do we want to learn about the zPath file? */
5934 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005935){
rse25c0d1a2007-09-20 08:38:14 +00005936 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005937 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005938 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005939 switch( flags ){
5940 case SQLITE_ACCESS_EXISTS:
5941 amode = F_OK;
5942 break;
5943 case SQLITE_ACCESS_READWRITE:
5944 amode = W_OK|R_OK;
5945 break;
drh50d3f902007-08-27 21:10:36 +00005946 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005947 amode = R_OK;
5948 break;
5949
5950 default:
5951 assert(!"Invalid flags argument");
5952 }
drh99ab3b12011-03-02 15:09:07 +00005953 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005954 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5955 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005956 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005957 *pResOut = 0;
5958 }
5959 }
danielk1977861f7452008-06-05 11:39:11 +00005960 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005961}
5962
danielk1977b4b47412007-08-17 15:53:36 +00005963
5964/*
5965** Turn a relative pathname into a full pathname. The relative path
5966** is stored as a nul-terminated string in the buffer pointed to by
5967** zPath.
5968**
5969** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5970** (in this case, MAX_PATHNAME bytes). The full-path is written to
5971** this buffer before returning.
5972*/
danielk1977adfb9b02007-09-17 07:02:56 +00005973static int unixFullPathname(
5974 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5975 const char *zPath, /* Possibly relative input path */
5976 int nOut, /* Size of output buffer in bytes */
5977 char *zOut /* Output buffer */
5978){
danielk1977843e65f2007-09-01 16:16:15 +00005979
5980 /* It's odd to simulate an io-error here, but really this is just
5981 ** using the io-error infrastructure to test that SQLite handles this
5982 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005983 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005984 */
5985 SimulateIOError( return SQLITE_ERROR );
5986
drh153c62c2007-08-24 03:51:33 +00005987 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005988 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005989
drh3c7f2dc2007-12-06 13:26:20 +00005990 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005991 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005992 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005993 }else{
5994 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005995 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005996 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005997 }
drhea678832008-12-10 19:26:22 +00005998 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005999 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006000 }
6001 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006002}
6003
drh0ccebe72005-06-07 22:22:50 +00006004
drh761df872006-12-21 01:29:22 +00006005#ifndef SQLITE_OMIT_LOAD_EXTENSION
6006/*
6007** Interfaces for opening a shared library, finding entry points
6008** within the shared library, and closing the shared library.
6009*/
6010#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006011static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6012 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006013 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6014}
danielk197795c8a542007-09-01 06:51:27 +00006015
6016/*
6017** SQLite calls this function immediately after a call to unixDlSym() or
6018** unixDlOpen() fails (returns a null pointer). If a more detailed error
6019** message is available, it is written to zBufOut. If no error message
6020** is available, zBufOut is left unmodified and SQLite uses a default
6021** error message.
6022*/
danielk1977397d65f2008-11-19 11:35:39 +00006023static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006024 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006025 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006026 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006027 zErr = dlerror();
6028 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006029 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006030 }
drh6c7d5c52008-11-21 20:32:33 +00006031 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006032}
drh1875f7a2008-12-08 18:19:17 +00006033static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6034 /*
6035 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6036 ** cast into a pointer to a function. And yet the library dlsym() routine
6037 ** returns a void* which is really a pointer to a function. So how do we
6038 ** use dlsym() with -pedantic-errors?
6039 **
6040 ** Variable x below is defined to be a pointer to a function taking
6041 ** parameters void* and const char* and returning a pointer to a function.
6042 ** We initialize x by assigning it a pointer to the dlsym() function.
6043 ** (That assignment requires a cast.) Then we call the function that
6044 ** x points to.
6045 **
6046 ** This work-around is unlikely to work correctly on any system where
6047 ** you really cannot cast a function pointer into void*. But then, on the
6048 ** other hand, dlsym() will not work on such a system either, so we have
6049 ** not really lost anything.
6050 */
6051 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006052 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006053 x = (void(*(*)(void*,const char*))(void))dlsym;
6054 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006055}
danielk1977397d65f2008-11-19 11:35:39 +00006056static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6057 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006058 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006059}
danielk1977b4b47412007-08-17 15:53:36 +00006060#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6061 #define unixDlOpen 0
6062 #define unixDlError 0
6063 #define unixDlSym 0
6064 #define unixDlClose 0
6065#endif
6066
6067/*
danielk197790949c22007-08-17 16:50:38 +00006068** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006069*/
danielk1977397d65f2008-11-19 11:35:39 +00006070static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6071 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006072 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006073
drhbbd42a62004-05-22 17:41:58 +00006074 /* We have to initialize zBuf to prevent valgrind from reporting
6075 ** errors. The reports issued by valgrind are incorrect - we would
6076 ** prefer that the randomness be increased by making use of the
6077 ** uninitialized space in zBuf - but valgrind errors tend to worry
6078 ** some users. Rather than argue, it seems easier just to initialize
6079 ** the whole array and silence valgrind, even if that means less randomness
6080 ** in the random seed.
6081 **
6082 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006083 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006084 ** tests repeatable.
6085 */
danielk1977b4b47412007-08-17 15:53:36 +00006086 memset(zBuf, 0, nBuf);
drhb00d8622014-01-01 15:18:36 +00006087 randomnessPid = getpid();
drhbbd42a62004-05-22 17:41:58 +00006088#if !defined(SQLITE_TEST)
6089 {
drhb00d8622014-01-01 15:18:36 +00006090 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006091 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006092 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006093 time_t t;
6094 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006095 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006096 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6097 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6098 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006099 }else{
drhc18b4042012-02-10 03:10:27 +00006100 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006101 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006102 }
drhbbd42a62004-05-22 17:41:58 +00006103 }
6104#endif
drh72cbd072008-10-14 17:58:38 +00006105 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006106}
6107
danielk1977b4b47412007-08-17 15:53:36 +00006108
drhbbd42a62004-05-22 17:41:58 +00006109/*
6110** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006111** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006112** The return value is the number of microseconds of sleep actually
6113** requested from the underlying operating system, a number which
6114** might be greater than or equal to the argument, but not less
6115** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006116*/
danielk1977397d65f2008-11-19 11:35:39 +00006117static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006118#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006119 struct timespec sp;
6120
6121 sp.tv_sec = microseconds / 1000000;
6122 sp.tv_nsec = (microseconds % 1000000) * 1000;
6123 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006124 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006125 return microseconds;
6126#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006127 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006128 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006129 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006130#else
danielk1977b4b47412007-08-17 15:53:36 +00006131 int seconds = (microseconds+999999)/1000000;
6132 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006133 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006134 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006135#endif
drh88f474a2006-01-02 20:00:12 +00006136}
6137
6138/*
drh6b9d6dd2008-12-03 19:34:47 +00006139** The following variable, if set to a non-zero value, is interpreted as
6140** the number of seconds since 1970 and is used to set the result of
6141** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006142*/
6143#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006144int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006145#endif
6146
6147/*
drhb7e8ea22010-05-03 14:32:30 +00006148** Find the current time (in Universal Coordinated Time). Write into *piNow
6149** the current time and date as a Julian Day number times 86_400_000. In
6150** other words, write into *piNow the number of milliseconds since the Julian
6151** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6152** proleptic Gregorian calendar.
6153**
drh31702252011-10-12 23:13:43 +00006154** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6155** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006156*/
6157static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6158 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006159 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006160#if defined(NO_GETTOD)
6161 time_t t;
6162 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006163 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006164#elif OS_VXWORKS
6165 struct timespec sNow;
6166 clock_gettime(CLOCK_REALTIME, &sNow);
6167 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6168#else
6169 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006170 if( gettimeofday(&sNow, 0)==0 ){
6171 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6172 }else{
6173 rc = SQLITE_ERROR;
6174 }
drhb7e8ea22010-05-03 14:32:30 +00006175#endif
6176
6177#ifdef SQLITE_TEST
6178 if( sqlite3_current_time ){
6179 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6180 }
6181#endif
6182 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006183 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006184}
6185
6186/*
drhbbd42a62004-05-22 17:41:58 +00006187** Find the current time (in Universal Coordinated Time). Write the
6188** current time and date as a Julian Day number into *prNow and
6189** return 0. Return 1 if the time and date cannot be found.
6190*/
danielk1977397d65f2008-11-19 11:35:39 +00006191static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006192 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006193 int rc;
drhff828942010-06-26 21:34:06 +00006194 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006195 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006196 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006197 return rc;
drhbbd42a62004-05-22 17:41:58 +00006198}
danielk1977b4b47412007-08-17 15:53:36 +00006199
drh6b9d6dd2008-12-03 19:34:47 +00006200/*
6201** We added the xGetLastError() method with the intention of providing
6202** better low-level error messages when operating-system problems come up
6203** during SQLite operation. But so far, none of that has been implemented
6204** in the core. So this routine is never called. For now, it is merely
6205** a place-holder.
6206*/
danielk1977397d65f2008-11-19 11:35:39 +00006207static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6208 UNUSED_PARAMETER(NotUsed);
6209 UNUSED_PARAMETER(NotUsed2);
6210 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006211 return 0;
6212}
6213
drhf2424c52010-04-26 00:04:55 +00006214
6215/*
drh734c9862008-11-28 15:37:20 +00006216************************ End of sqlite3_vfs methods ***************************
6217******************************************************************************/
6218
drh715ff302008-12-03 22:32:44 +00006219/******************************************************************************
6220************************** Begin Proxy Locking ********************************
6221**
6222** Proxy locking is a "uber-locking-method" in this sense: It uses the
6223** other locking methods on secondary lock files. Proxy locking is a
6224** meta-layer over top of the primitive locking implemented above. For
6225** this reason, the division that implements of proxy locking is deferred
6226** until late in the file (here) after all of the other I/O methods have
6227** been defined - so that the primitive locking methods are available
6228** as services to help with the implementation of proxy locking.
6229**
6230****
6231**
6232** The default locking schemes in SQLite use byte-range locks on the
6233** database file to coordinate safe, concurrent access by multiple readers
6234** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6235** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6236** as POSIX read & write locks over fixed set of locations (via fsctl),
6237** on AFP and SMB only exclusive byte-range locks are available via fsctl
6238** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6239** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6240** address in the shared range is taken for a SHARED lock, the entire
6241** shared range is taken for an EXCLUSIVE lock):
6242**
drhf2f105d2012-08-20 15:53:54 +00006243** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006244** RESERVED_BYTE 0x40000001
6245** SHARED_RANGE 0x40000002 -> 0x40000200
6246**
6247** This works well on the local file system, but shows a nearly 100x
6248** slowdown in read performance on AFP because the AFP client disables
6249** the read cache when byte-range locks are present. Enabling the read
6250** cache exposes a cache coherency problem that is present on all OS X
6251** supported network file systems. NFS and AFP both observe the
6252** close-to-open semantics for ensuring cache coherency
6253** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6254** address the requirements for concurrent database access by multiple
6255** readers and writers
6256** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6257**
6258** To address the performance and cache coherency issues, proxy file locking
6259** changes the way database access is controlled by limiting access to a
6260** single host at a time and moving file locks off of the database file
6261** and onto a proxy file on the local file system.
6262**
6263**
6264** Using proxy locks
6265** -----------------
6266**
6267** C APIs
6268**
6269** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6270** <proxy_path> | ":auto:");
6271** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6272**
6273**
6274** SQL pragmas
6275**
6276** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6277** PRAGMA [database.]lock_proxy_file
6278**
6279** Specifying ":auto:" means that if there is a conch file with a matching
6280** host ID in it, the proxy path in the conch file will be used, otherwise
6281** a proxy path based on the user's temp dir
6282** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6283** actual proxy file name is generated from the name and path of the
6284** database file. For example:
6285**
6286** For database path "/Users/me/foo.db"
6287** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6288**
6289** Once a lock proxy is configured for a database connection, it can not
6290** be removed, however it may be switched to a different proxy path via
6291** the above APIs (assuming the conch file is not being held by another
6292** connection or process).
6293**
6294**
6295** How proxy locking works
6296** -----------------------
6297**
6298** Proxy file locking relies primarily on two new supporting files:
6299**
6300** * conch file to limit access to the database file to a single host
6301** at a time
6302**
6303** * proxy file to act as a proxy for the advisory locks normally
6304** taken on the database
6305**
6306** The conch file - to use a proxy file, sqlite must first "hold the conch"
6307** by taking an sqlite-style shared lock on the conch file, reading the
6308** contents and comparing the host's unique host ID (see below) and lock
6309** proxy path against the values stored in the conch. The conch file is
6310** stored in the same directory as the database file and the file name
6311** is patterned after the database file name as ".<databasename>-conch".
6312** If the conch file does not exist, or it's contents do not match the
6313** host ID and/or proxy path, then the lock is escalated to an exclusive
6314** lock and the conch file contents is updated with the host ID and proxy
6315** path and the lock is downgraded to a shared lock again. If the conch
6316** is held by another process (with a shared lock), the exclusive lock
6317** will fail and SQLITE_BUSY is returned.
6318**
6319** The proxy file - a single-byte file used for all advisory file locks
6320** normally taken on the database file. This allows for safe sharing
6321** of the database file for multiple readers and writers on the same
6322** host (the conch ensures that they all use the same local lock file).
6323**
drh715ff302008-12-03 22:32:44 +00006324** Requesting the lock proxy does not immediately take the conch, it is
6325** only taken when the first request to lock database file is made.
6326** This matches the semantics of the traditional locking behavior, where
6327** opening a connection to a database file does not take a lock on it.
6328** The shared lock and an open file descriptor are maintained until
6329** the connection to the database is closed.
6330**
6331** The proxy file and the lock file are never deleted so they only need
6332** to be created the first time they are used.
6333**
6334** Configuration options
6335** ---------------------
6336**
6337** SQLITE_PREFER_PROXY_LOCKING
6338**
6339** Database files accessed on non-local file systems are
6340** automatically configured for proxy locking, lock files are
6341** named automatically using the same logic as
6342** PRAGMA lock_proxy_file=":auto:"
6343**
6344** SQLITE_PROXY_DEBUG
6345**
6346** Enables the logging of error messages during host id file
6347** retrieval and creation
6348**
drh715ff302008-12-03 22:32:44 +00006349** LOCKPROXYDIR
6350**
6351** Overrides the default directory used for lock proxy files that
6352** are named automatically via the ":auto:" setting
6353**
6354** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6355**
6356** Permissions to use when creating a directory for storing the
6357** lock proxy files, only used when LOCKPROXYDIR is not set.
6358**
6359**
6360** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6361** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6362** force proxy locking to be used for every database file opened, and 0
6363** will force automatic proxy locking to be disabled for all database
6364** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6365** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6366*/
6367
6368/*
6369** Proxy locking is only available on MacOSX
6370*/
drhd2cb50b2009-01-09 21:41:17 +00006371#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006372
drh715ff302008-12-03 22:32:44 +00006373/*
6374** The proxyLockingContext has the path and file structures for the remote
6375** and local proxy files in it
6376*/
6377typedef struct proxyLockingContext proxyLockingContext;
6378struct proxyLockingContext {
6379 unixFile *conchFile; /* Open conch file */
6380 char *conchFilePath; /* Name of the conch file */
6381 unixFile *lockProxy; /* Open proxy lock file */
6382 char *lockProxyPath; /* Name of the proxy lock file */
6383 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006384 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006385 void *oldLockingContext; /* Original lockingcontext to restore on close */
6386 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6387};
6388
drh7ed97b92010-01-20 13:07:21 +00006389/*
6390** The proxy lock file path for the database at dbPath is written into lPath,
6391** which must point to valid, writable memory large enough for a maxLen length
6392** file path.
drh715ff302008-12-03 22:32:44 +00006393*/
drh715ff302008-12-03 22:32:44 +00006394static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6395 int len;
6396 int dbLen;
6397 int i;
6398
6399#ifdef LOCKPROXYDIR
6400 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6401#else
6402# ifdef _CS_DARWIN_USER_TEMP_DIR
6403 {
drh7ed97b92010-01-20 13:07:21 +00006404 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006405 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6406 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006407 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006408 }
drh7ed97b92010-01-20 13:07:21 +00006409 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006410 }
6411# else
6412 len = strlcpy(lPath, "/tmp/", maxLen);
6413# endif
6414#endif
6415
6416 if( lPath[len-1]!='/' ){
6417 len = strlcat(lPath, "/", maxLen);
6418 }
6419
6420 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006421 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006422 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006423 char c = dbPath[i];
6424 lPath[i+len] = (c=='/')?'_':c;
6425 }
6426 lPath[i+len]='\0';
6427 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006428 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006429 return SQLITE_OK;
6430}
6431
drh7ed97b92010-01-20 13:07:21 +00006432/*
6433 ** Creates the lock file and any missing directories in lockPath
6434 */
6435static int proxyCreateLockPath(const char *lockPath){
6436 int i, len;
6437 char buf[MAXPATHLEN];
6438 int start = 0;
6439
6440 assert(lockPath!=NULL);
6441 /* try to create all the intermediate directories */
6442 len = (int)strlen(lockPath);
6443 buf[0] = lockPath[0];
6444 for( i=1; i<len; i++ ){
6445 if( lockPath[i] == '/' && (i - start > 0) ){
6446 /* only mkdir if leaf dir != "." or "/" or ".." */
6447 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6448 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6449 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006450 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006451 int err=errno;
6452 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006453 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006454 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006455 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006456 return err;
6457 }
6458 }
6459 }
6460 start=i+1;
6461 }
6462 buf[i] = lockPath[i];
6463 }
drh308c2a52010-05-14 11:30:18 +00006464 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006465 return 0;
6466}
6467
drh715ff302008-12-03 22:32:44 +00006468/*
6469** Create a new VFS file descriptor (stored in memory obtained from
6470** sqlite3_malloc) and open the file named "path" in the file descriptor.
6471**
6472** The caller is responsible not only for closing the file descriptor
6473** but also for freeing the memory associated with the file descriptor.
6474*/
drh7ed97b92010-01-20 13:07:21 +00006475static int proxyCreateUnixFile(
6476 const char *path, /* path for the new unixFile */
6477 unixFile **ppFile, /* unixFile created and returned by ref */
6478 int islockfile /* if non zero missing dirs will be created */
6479) {
6480 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006481 unixFile *pNew;
6482 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006483 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006484 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006485 int terrno = 0;
6486 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006487
drh7ed97b92010-01-20 13:07:21 +00006488 /* 1. first try to open/create the file
6489 ** 2. if that fails, and this is a lock file (not-conch), try creating
6490 ** the parent directories and then try again.
6491 ** 3. if that fails, try to open the file read-only
6492 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6493 */
6494 pUnused = findReusableFd(path, openFlags);
6495 if( pUnused ){
6496 fd = pUnused->fd;
6497 }else{
6498 pUnused = sqlite3_malloc(sizeof(*pUnused));
6499 if( !pUnused ){
6500 return SQLITE_NOMEM;
6501 }
6502 }
6503 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006504 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006505 terrno = errno;
6506 if( fd<0 && errno==ENOENT && islockfile ){
6507 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006508 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006509 }
6510 }
6511 }
6512 if( fd<0 ){
6513 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006514 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006515 terrno = errno;
6516 }
6517 if( fd<0 ){
6518 if( islockfile ){
6519 return SQLITE_BUSY;
6520 }
6521 switch (terrno) {
6522 case EACCES:
6523 return SQLITE_PERM;
6524 case EIO:
6525 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6526 default:
drh9978c972010-02-23 17:36:32 +00006527 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006528 }
6529 }
6530
6531 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6532 if( pNew==NULL ){
6533 rc = SQLITE_NOMEM;
6534 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006535 }
6536 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006537 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006538 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006539 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006540 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006541 pUnused->fd = fd;
6542 pUnused->flags = openFlags;
6543 pNew->pUnused = pUnused;
6544
drhc02a43a2012-01-10 23:18:38 +00006545 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006546 if( rc==SQLITE_OK ){
6547 *ppFile = pNew;
6548 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006549 }
drh7ed97b92010-01-20 13:07:21 +00006550end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006551 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006552 sqlite3_free(pNew);
6553 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006554 return rc;
6555}
6556
drh7ed97b92010-01-20 13:07:21 +00006557#ifdef SQLITE_TEST
6558/* simulate multiple hosts by creating unique hostid file paths */
6559int sqlite3_hostid_num = 0;
6560#endif
6561
6562#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6563
drh0ab216a2010-07-02 17:10:40 +00006564/* Not always defined in the headers as it ought to be */
6565extern int gethostuuid(uuid_t id, const struct timespec *wait);
6566
drh7ed97b92010-01-20 13:07:21 +00006567/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6568** bytes of writable memory.
6569*/
6570static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006571 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6572 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006573#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6574 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006575 {
6576 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6577 if( gethostuuid(pHostID, &timeout) ){
6578 int err = errno;
6579 if( pError ){
6580 *pError = err;
6581 }
6582 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006583 }
drh7ed97b92010-01-20 13:07:21 +00006584 }
drh3d4435b2011-08-26 20:55:50 +00006585#else
6586 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006587#endif
drh7ed97b92010-01-20 13:07:21 +00006588#ifdef SQLITE_TEST
6589 /* simulate multiple hosts by creating unique hostid file paths */
6590 if( sqlite3_hostid_num != 0){
6591 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6592 }
6593#endif
6594
6595 return SQLITE_OK;
6596}
6597
6598/* The conch file contains the header, host id and lock file path
6599 */
6600#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6601#define PROXY_HEADERLEN 1 /* conch file header length */
6602#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6603#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6604
6605/*
6606** Takes an open conch file, copies the contents to a new path and then moves
6607** it back. The newly created file's file descriptor is assigned to the
6608** conch file structure and finally the original conch file descriptor is
6609** closed. Returns zero if successful.
6610*/
6611static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6612 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6613 unixFile *conchFile = pCtx->conchFile;
6614 char tPath[MAXPATHLEN];
6615 char buf[PROXY_MAXCONCHLEN];
6616 char *cPath = pCtx->conchFilePath;
6617 size_t readLen = 0;
6618 size_t pathLen = 0;
6619 char errmsg[64] = "";
6620 int fd = -1;
6621 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006622 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006623
6624 /* create a new path by replace the trailing '-conch' with '-break' */
6625 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6626 if( pathLen>MAXPATHLEN || pathLen<6 ||
6627 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006628 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006629 goto end_breaklock;
6630 }
6631 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006632 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006633 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006634 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006635 goto end_breaklock;
6636 }
6637 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006638 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006639 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006640 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006641 goto end_breaklock;
6642 }
drhe562be52011-03-02 18:01:10 +00006643 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006644 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006645 goto end_breaklock;
6646 }
6647 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006648 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006649 goto end_breaklock;
6650 }
6651 rc = 0;
6652 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006653 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006654 conchFile->h = fd;
6655 conchFile->openFlags = O_RDWR | O_CREAT;
6656
6657end_breaklock:
6658 if( rc ){
6659 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006660 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006661 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006662 }
6663 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6664 }
6665 return rc;
6666}
6667
6668/* Take the requested lock on the conch file and break a stale lock if the
6669** host id matches.
6670*/
6671static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6672 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6673 unixFile *conchFile = pCtx->conchFile;
6674 int rc = SQLITE_OK;
6675 int nTries = 0;
6676 struct timespec conchModTime;
6677
drh3d4435b2011-08-26 20:55:50 +00006678 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006679 do {
6680 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6681 nTries ++;
6682 if( rc==SQLITE_BUSY ){
6683 /* If the lock failed (busy):
6684 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6685 * 2nd try: fail if the mod time changed or host id is different, wait
6686 * 10 sec and try again
6687 * 3rd try: break the lock unless the mod time has changed.
6688 */
6689 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006690 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006691 pFile->lastErrno = errno;
6692 return SQLITE_IOERR_LOCK;
6693 }
6694
6695 if( nTries==1 ){
6696 conchModTime = buf.st_mtimespec;
6697 usleep(500000); /* wait 0.5 sec and try the lock again*/
6698 continue;
6699 }
6700
6701 assert( nTries>1 );
6702 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6703 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6704 return SQLITE_BUSY;
6705 }
6706
6707 if( nTries==2 ){
6708 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006709 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006710 if( len<0 ){
6711 pFile->lastErrno = errno;
6712 return SQLITE_IOERR_LOCK;
6713 }
6714 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6715 /* don't break the lock if the host id doesn't match */
6716 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6717 return SQLITE_BUSY;
6718 }
6719 }else{
6720 /* don't break the lock on short read or a version mismatch */
6721 return SQLITE_BUSY;
6722 }
6723 usleep(10000000); /* wait 10 sec and try the lock again */
6724 continue;
6725 }
6726
6727 assert( nTries==3 );
6728 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6729 rc = SQLITE_OK;
6730 if( lockType==EXCLUSIVE_LOCK ){
6731 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6732 }
6733 if( !rc ){
6734 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6735 }
6736 }
6737 }
6738 } while( rc==SQLITE_BUSY && nTries<3 );
6739
6740 return rc;
6741}
6742
6743/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006744** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6745** lockPath means that the lockPath in the conch file will be used if the
6746** host IDs match, or a new lock path will be generated automatically
6747** and written to the conch file.
6748*/
6749static int proxyTakeConch(unixFile *pFile){
6750 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6751
drh7ed97b92010-01-20 13:07:21 +00006752 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006753 return SQLITE_OK;
6754 }else{
6755 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006756 uuid_t myHostID;
6757 int pError = 0;
6758 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006759 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006760 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006761 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006762 int createConch = 0;
6763 int hostIdMatch = 0;
6764 int readLen = 0;
6765 int tryOldLockPath = 0;
6766 int forceNewLockPath = 0;
6767
drh308c2a52010-05-14 11:30:18 +00006768 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6769 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006770
drh7ed97b92010-01-20 13:07:21 +00006771 rc = proxyGetHostID(myHostID, &pError);
6772 if( (rc&0xff)==SQLITE_IOERR ){
6773 pFile->lastErrno = pError;
6774 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006775 }
drh7ed97b92010-01-20 13:07:21 +00006776 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006777 if( rc!=SQLITE_OK ){
6778 goto end_takeconch;
6779 }
drh7ed97b92010-01-20 13:07:21 +00006780 /* read the existing conch file */
6781 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6782 if( readLen<0 ){
6783 /* I/O error: lastErrno set by seekAndRead */
6784 pFile->lastErrno = conchFile->lastErrno;
6785 rc = SQLITE_IOERR_READ;
6786 goto end_takeconch;
6787 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6788 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6789 /* a short read or version format mismatch means we need to create a new
6790 ** conch file.
6791 */
6792 createConch = 1;
6793 }
6794 /* if the host id matches and the lock path already exists in the conch
6795 ** we'll try to use the path there, if we can't open that path, we'll
6796 ** retry with a new auto-generated path
6797 */
6798 do { /* in case we need to try again for an :auto: named lock file */
6799
6800 if( !createConch && !forceNewLockPath ){
6801 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6802 PROXY_HOSTIDLEN);
6803 /* if the conch has data compare the contents */
6804 if( !pCtx->lockProxyPath ){
6805 /* for auto-named local lock file, just check the host ID and we'll
6806 ** use the local lock file path that's already in there
6807 */
6808 if( hostIdMatch ){
6809 size_t pathLen = (readLen - PROXY_PATHINDEX);
6810
6811 if( pathLen>=MAXPATHLEN ){
6812 pathLen=MAXPATHLEN-1;
6813 }
6814 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6815 lockPath[pathLen] = 0;
6816 tempLockPath = lockPath;
6817 tryOldLockPath = 1;
6818 /* create a copy of the lock path if the conch is taken */
6819 goto end_takeconch;
6820 }
6821 }else if( hostIdMatch
6822 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6823 readLen-PROXY_PATHINDEX)
6824 ){
6825 /* conch host and lock path match */
6826 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006827 }
drh7ed97b92010-01-20 13:07:21 +00006828 }
6829
6830 /* if the conch isn't writable and doesn't match, we can't take it */
6831 if( (conchFile->openFlags&O_RDWR) == 0 ){
6832 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006833 goto end_takeconch;
6834 }
drh7ed97b92010-01-20 13:07:21 +00006835
6836 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006837 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006838 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6839 tempLockPath = lockPath;
6840 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006841 }
drh7ed97b92010-01-20 13:07:21 +00006842
6843 /* update conch with host and path (this will fail if other process
6844 ** has a shared lock already), if the host id matches, use the big
6845 ** stick.
drh715ff302008-12-03 22:32:44 +00006846 */
drh7ed97b92010-01-20 13:07:21 +00006847 futimes(conchFile->h, NULL);
6848 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006849 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006850 /* We are trying for an exclusive lock but another thread in this
6851 ** same process is still holding a shared lock. */
6852 rc = SQLITE_BUSY;
6853 } else {
6854 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006855 }
drh715ff302008-12-03 22:32:44 +00006856 }else{
drh7ed97b92010-01-20 13:07:21 +00006857 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006858 }
drh7ed97b92010-01-20 13:07:21 +00006859 if( rc==SQLITE_OK ){
6860 char writeBuffer[PROXY_MAXCONCHLEN];
6861 int writeSize = 0;
6862
6863 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6864 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6865 if( pCtx->lockProxyPath!=NULL ){
6866 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6867 }else{
6868 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6869 }
6870 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006871 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006872 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6873 fsync(conchFile->h);
6874 /* If we created a new conch file (not just updated the contents of a
6875 ** valid conch file), try to match the permissions of the database
6876 */
6877 if( rc==SQLITE_OK && createConch ){
6878 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006879 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006880 if( err==0 ){
6881 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6882 S_IROTH|S_IWOTH);
6883 /* try to match the database file R/W permissions, ignore failure */
6884#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006885 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006886#else
drhff812312011-02-23 13:33:46 +00006887 do{
drhe562be52011-03-02 18:01:10 +00006888 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006889 }while( rc==(-1) && errno==EINTR );
6890 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006891 int code = errno;
6892 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6893 cmode, code, strerror(code));
6894 } else {
6895 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6896 }
6897 }else{
6898 int code = errno;
6899 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6900 err, code, strerror(code));
6901#endif
6902 }
drh715ff302008-12-03 22:32:44 +00006903 }
6904 }
drh7ed97b92010-01-20 13:07:21 +00006905 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6906
6907 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006908 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006909 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006910 int fd;
drh7ed97b92010-01-20 13:07:21 +00006911 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006912 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006913 }
6914 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006915 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006916 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006917 if( fd>=0 ){
6918 pFile->h = fd;
6919 }else{
drh9978c972010-02-23 17:36:32 +00006920 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006921 during locking */
6922 }
6923 }
6924 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6925 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6926 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6927 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6928 /* we couldn't create the proxy lock file with the old lock file path
6929 ** so try again via auto-naming
6930 */
6931 forceNewLockPath = 1;
6932 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006933 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006934 }
6935 }
6936 if( rc==SQLITE_OK ){
6937 /* Need to make a copy of path if we extracted the value
6938 ** from the conch file or the path was allocated on the stack
6939 */
6940 if( tempLockPath ){
6941 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6942 if( !pCtx->lockProxyPath ){
6943 rc = SQLITE_NOMEM;
6944 }
6945 }
6946 }
6947 if( rc==SQLITE_OK ){
6948 pCtx->conchHeld = 1;
6949
6950 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6951 afpLockingContext *afpCtx;
6952 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6953 afpCtx->dbPath = pCtx->lockProxyPath;
6954 }
6955 } else {
6956 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6957 }
drh308c2a52010-05-14 11:30:18 +00006958 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6959 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006960 return rc;
drh308c2a52010-05-14 11:30:18 +00006961 } while (1); /* in case we need to retry the :auto: lock file -
6962 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006963 }
6964}
6965
6966/*
6967** If pFile holds a lock on a conch file, then release that lock.
6968*/
6969static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006970 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006971 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6972 unixFile *conchFile; /* Name of the conch file */
6973
6974 pCtx = (proxyLockingContext *)pFile->lockingContext;
6975 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006976 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006977 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006978 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006979 if( pCtx->conchHeld>0 ){
6980 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6981 }
drh715ff302008-12-03 22:32:44 +00006982 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006983 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6984 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006985 return rc;
6986}
6987
6988/*
6989** Given the name of a database file, compute the name of its conch file.
6990** Store the conch filename in memory obtained from sqlite3_malloc().
6991** Make *pConchPath point to the new name. Return SQLITE_OK on success
6992** or SQLITE_NOMEM if unable to obtain memory.
6993**
6994** The caller is responsible for ensuring that the allocated memory
6995** space is eventually freed.
6996**
6997** *pConchPath is set to NULL if a memory allocation error occurs.
6998*/
6999static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7000 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007001 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007002 char *conchPath; /* buffer in which to construct conch name */
7003
7004 /* Allocate space for the conch filename and initialize the name to
7005 ** the name of the original database file. */
7006 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
7007 if( conchPath==0 ){
7008 return SQLITE_NOMEM;
7009 }
7010 memcpy(conchPath, dbPath, len+1);
7011
7012 /* now insert a "." before the last / character */
7013 for( i=(len-1); i>=0; i-- ){
7014 if( conchPath[i]=='/' ){
7015 i++;
7016 break;
7017 }
7018 }
7019 conchPath[i]='.';
7020 while ( i<len ){
7021 conchPath[i+1]=dbPath[i];
7022 i++;
7023 }
7024
7025 /* append the "-conch" suffix to the file */
7026 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007027 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007028
7029 return SQLITE_OK;
7030}
7031
7032
7033/* Takes a fully configured proxy locking-style unix file and switches
7034** the local lock file path
7035*/
7036static int switchLockProxyPath(unixFile *pFile, const char *path) {
7037 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7038 char *oldPath = pCtx->lockProxyPath;
7039 int rc = SQLITE_OK;
7040
drh308c2a52010-05-14 11:30:18 +00007041 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007042 return SQLITE_BUSY;
7043 }
7044
7045 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7046 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7047 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7048 return SQLITE_OK;
7049 }else{
7050 unixFile *lockProxy = pCtx->lockProxy;
7051 pCtx->lockProxy=NULL;
7052 pCtx->conchHeld = 0;
7053 if( lockProxy!=NULL ){
7054 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7055 if( rc ) return rc;
7056 sqlite3_free(lockProxy);
7057 }
7058 sqlite3_free(oldPath);
7059 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7060 }
7061
7062 return rc;
7063}
7064
7065/*
7066** pFile is a file that has been opened by a prior xOpen call. dbPath
7067** is a string buffer at least MAXPATHLEN+1 characters in size.
7068**
7069** This routine find the filename associated with pFile and writes it
7070** int dbPath.
7071*/
7072static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007073#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007074 if( pFile->pMethod == &afpIoMethods ){
7075 /* afp style keeps a reference to the db path in the filePath field
7076 ** of the struct */
drhea678832008-12-10 19:26:22 +00007077 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007078 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7079 } else
drh715ff302008-12-03 22:32:44 +00007080#endif
7081 if( pFile->pMethod == &dotlockIoMethods ){
7082 /* dot lock style uses the locking context to store the dot lock
7083 ** file path */
7084 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7085 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7086 }else{
7087 /* all other styles use the locking context to store the db file path */
7088 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007089 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007090 }
7091 return SQLITE_OK;
7092}
7093
7094/*
7095** Takes an already filled in unix file and alters it so all file locking
7096** will be performed on the local proxy lock file. The following fields
7097** are preserved in the locking context so that they can be restored and
7098** the unix structure properly cleaned up at close time:
7099** ->lockingContext
7100** ->pMethod
7101*/
7102static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7103 proxyLockingContext *pCtx;
7104 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7105 char *lockPath=NULL;
7106 int rc = SQLITE_OK;
7107
drh308c2a52010-05-14 11:30:18 +00007108 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007109 return SQLITE_BUSY;
7110 }
7111 proxyGetDbPathForUnixFile(pFile, dbPath);
7112 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7113 lockPath=NULL;
7114 }else{
7115 lockPath=(char *)path;
7116 }
7117
drh308c2a52010-05-14 11:30:18 +00007118 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7119 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007120
7121 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7122 if( pCtx==0 ){
7123 return SQLITE_NOMEM;
7124 }
7125 memset(pCtx, 0, sizeof(*pCtx));
7126
7127 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7128 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007129 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7130 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7131 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7132 ** (c) the file system is read-only, then enable no-locking access.
7133 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7134 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7135 */
7136 struct statfs fsInfo;
7137 struct stat conchInfo;
7138 int goLockless = 0;
7139
drh99ab3b12011-03-02 15:09:07 +00007140 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007141 int err = errno;
7142 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7143 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7144 }
7145 }
7146 if( goLockless ){
7147 pCtx->conchHeld = -1; /* read only FS/ lockless */
7148 rc = SQLITE_OK;
7149 }
7150 }
drh715ff302008-12-03 22:32:44 +00007151 }
7152 if( rc==SQLITE_OK && lockPath ){
7153 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7154 }
7155
7156 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007157 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7158 if( pCtx->dbPath==NULL ){
7159 rc = SQLITE_NOMEM;
7160 }
7161 }
7162 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007163 /* all memory is allocated, proxys are created and assigned,
7164 ** switch the locking context and pMethod then return.
7165 */
drh715ff302008-12-03 22:32:44 +00007166 pCtx->oldLockingContext = pFile->lockingContext;
7167 pFile->lockingContext = pCtx;
7168 pCtx->pOldMethod = pFile->pMethod;
7169 pFile->pMethod = &proxyIoMethods;
7170 }else{
7171 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007172 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007173 sqlite3_free(pCtx->conchFile);
7174 }
drhd56b1212010-08-11 06:14:15 +00007175 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007176 sqlite3_free(pCtx->conchFilePath);
7177 sqlite3_free(pCtx);
7178 }
drh308c2a52010-05-14 11:30:18 +00007179 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7180 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007181 return rc;
7182}
7183
7184
7185/*
7186** This routine handles sqlite3_file_control() calls that are specific
7187** to proxy locking.
7188*/
7189static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7190 switch( op ){
7191 case SQLITE_GET_LOCKPROXYFILE: {
7192 unixFile *pFile = (unixFile*)id;
7193 if( pFile->pMethod == &proxyIoMethods ){
7194 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7195 proxyTakeConch(pFile);
7196 if( pCtx->lockProxyPath ){
7197 *(const char **)pArg = pCtx->lockProxyPath;
7198 }else{
7199 *(const char **)pArg = ":auto: (not held)";
7200 }
7201 } else {
7202 *(const char **)pArg = NULL;
7203 }
7204 return SQLITE_OK;
7205 }
7206 case SQLITE_SET_LOCKPROXYFILE: {
7207 unixFile *pFile = (unixFile*)id;
7208 int rc = SQLITE_OK;
7209 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7210 if( pArg==NULL || (const char *)pArg==0 ){
7211 if( isProxyStyle ){
7212 /* turn off proxy locking - not supported */
7213 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7214 }else{
7215 /* turn off proxy locking - already off - NOOP */
7216 rc = SQLITE_OK;
7217 }
7218 }else{
7219 const char *proxyPath = (const char *)pArg;
7220 if( isProxyStyle ){
7221 proxyLockingContext *pCtx =
7222 (proxyLockingContext*)pFile->lockingContext;
7223 if( !strcmp(pArg, ":auto:")
7224 || (pCtx->lockProxyPath &&
7225 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7226 ){
7227 rc = SQLITE_OK;
7228 }else{
7229 rc = switchLockProxyPath(pFile, proxyPath);
7230 }
7231 }else{
7232 /* turn on proxy file locking */
7233 rc = proxyTransformUnixFile(pFile, proxyPath);
7234 }
7235 }
7236 return rc;
7237 }
7238 default: {
7239 assert( 0 ); /* The call assures that only valid opcodes are sent */
7240 }
7241 }
7242 /*NOTREACHED*/
7243 return SQLITE_ERROR;
7244}
7245
7246/*
7247** Within this division (the proxying locking implementation) the procedures
7248** above this point are all utilities. The lock-related methods of the
7249** proxy-locking sqlite3_io_method object follow.
7250*/
7251
7252
7253/*
7254** This routine checks if there is a RESERVED lock held on the specified
7255** file by this or any other process. If such a lock is held, set *pResOut
7256** to a non-zero value otherwise *pResOut is set to zero. The return value
7257** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7258*/
7259static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7260 unixFile *pFile = (unixFile*)id;
7261 int rc = proxyTakeConch(pFile);
7262 if( rc==SQLITE_OK ){
7263 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007264 if( pCtx->conchHeld>0 ){
7265 unixFile *proxy = pCtx->lockProxy;
7266 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7267 }else{ /* conchHeld < 0 is lockless */
7268 pResOut=0;
7269 }
drh715ff302008-12-03 22:32:44 +00007270 }
7271 return rc;
7272}
7273
7274/*
drh308c2a52010-05-14 11:30:18 +00007275** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007276** of the following:
7277**
7278** (1) SHARED_LOCK
7279** (2) RESERVED_LOCK
7280** (3) PENDING_LOCK
7281** (4) EXCLUSIVE_LOCK
7282**
7283** Sometimes when requesting one lock state, additional lock states
7284** are inserted in between. The locking might fail on one of the later
7285** transitions leaving the lock state different from what it started but
7286** still short of its goal. The following chart shows the allowed
7287** transitions and the inserted intermediate states:
7288**
7289** UNLOCKED -> SHARED
7290** SHARED -> RESERVED
7291** SHARED -> (PENDING) -> EXCLUSIVE
7292** RESERVED -> (PENDING) -> EXCLUSIVE
7293** PENDING -> EXCLUSIVE
7294**
7295** This routine will only increase a lock. Use the sqlite3OsUnlock()
7296** routine to lower a locking level.
7297*/
drh308c2a52010-05-14 11:30:18 +00007298static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007299 unixFile *pFile = (unixFile*)id;
7300 int rc = proxyTakeConch(pFile);
7301 if( rc==SQLITE_OK ){
7302 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007303 if( pCtx->conchHeld>0 ){
7304 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007305 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7306 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007307 }else{
7308 /* conchHeld < 0 is lockless */
7309 }
drh715ff302008-12-03 22:32:44 +00007310 }
7311 return rc;
7312}
7313
7314
7315/*
drh308c2a52010-05-14 11:30:18 +00007316** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007317** must be either NO_LOCK or SHARED_LOCK.
7318**
7319** If the locking level of the file descriptor is already at or below
7320** the requested locking level, this routine is a no-op.
7321*/
drh308c2a52010-05-14 11:30:18 +00007322static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007323 unixFile *pFile = (unixFile*)id;
7324 int rc = proxyTakeConch(pFile);
7325 if( rc==SQLITE_OK ){
7326 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007327 if( pCtx->conchHeld>0 ){
7328 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007329 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7330 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007331 }else{
7332 /* conchHeld < 0 is lockless */
7333 }
drh715ff302008-12-03 22:32:44 +00007334 }
7335 return rc;
7336}
7337
7338/*
7339** Close a file that uses proxy locks.
7340*/
7341static int proxyClose(sqlite3_file *id) {
7342 if( id ){
7343 unixFile *pFile = (unixFile*)id;
7344 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7345 unixFile *lockProxy = pCtx->lockProxy;
7346 unixFile *conchFile = pCtx->conchFile;
7347 int rc = SQLITE_OK;
7348
7349 if( lockProxy ){
7350 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7351 if( rc ) return rc;
7352 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7353 if( rc ) return rc;
7354 sqlite3_free(lockProxy);
7355 pCtx->lockProxy = 0;
7356 }
7357 if( conchFile ){
7358 if( pCtx->conchHeld ){
7359 rc = proxyReleaseConch(pFile);
7360 if( rc ) return rc;
7361 }
7362 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7363 if( rc ) return rc;
7364 sqlite3_free(conchFile);
7365 }
drhd56b1212010-08-11 06:14:15 +00007366 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007367 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007368 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007369 /* restore the original locking context and pMethod then close it */
7370 pFile->lockingContext = pCtx->oldLockingContext;
7371 pFile->pMethod = pCtx->pOldMethod;
7372 sqlite3_free(pCtx);
7373 return pFile->pMethod->xClose(id);
7374 }
7375 return SQLITE_OK;
7376}
7377
7378
7379
drhd2cb50b2009-01-09 21:41:17 +00007380#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007381/*
7382** The proxy locking style is intended for use with AFP filesystems.
7383** And since AFP is only supported on MacOSX, the proxy locking is also
7384** restricted to MacOSX.
7385**
7386**
7387******************* End of the proxy lock implementation **********************
7388******************************************************************************/
7389
drh734c9862008-11-28 15:37:20 +00007390/*
danielk1977e339d652008-06-28 11:23:00 +00007391** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007392**
7393** This routine registers all VFS implementations for unix-like operating
7394** systems. This routine, and the sqlite3_os_end() routine that follows,
7395** should be the only routines in this file that are visible from other
7396** files.
drh6b9d6dd2008-12-03 19:34:47 +00007397**
7398** This routine is called once during SQLite initialization and by a
7399** single thread. The memory allocation and mutex subsystems have not
7400** necessarily been initialized when this routine is called, and so they
7401** should not be used.
drh153c62c2007-08-24 03:51:33 +00007402*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007403int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007404 /*
7405 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007406 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7407 ** to the "finder" function. (pAppData is a pointer to a pointer because
7408 ** silly C90 rules prohibit a void* from being cast to a function pointer
7409 ** and so we have to go through the intermediate pointer to avoid problems
7410 ** when compiling with -pedantic-errors on GCC.)
7411 **
7412 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007413 ** finder-function. The finder-function returns a pointer to the
7414 ** sqlite_io_methods object that implements the desired locking
7415 ** behaviors. See the division above that contains the IOMETHODS
7416 ** macro for addition information on finder-functions.
7417 **
7418 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7419 ** object. But the "autolockIoFinder" available on MacOSX does a little
7420 ** more than that; it looks at the filesystem type that hosts the
7421 ** database file and tries to choose an locking method appropriate for
7422 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007423 */
drh7708e972008-11-29 00:56:52 +00007424 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007425 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007426 sizeof(unixFile), /* szOsFile */ \
7427 MAX_PATHNAME, /* mxPathname */ \
7428 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007429 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007430 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007431 unixOpen, /* xOpen */ \
7432 unixDelete, /* xDelete */ \
7433 unixAccess, /* xAccess */ \
7434 unixFullPathname, /* xFullPathname */ \
7435 unixDlOpen, /* xDlOpen */ \
7436 unixDlError, /* xDlError */ \
7437 unixDlSym, /* xDlSym */ \
7438 unixDlClose, /* xDlClose */ \
7439 unixRandomness, /* xRandomness */ \
7440 unixSleep, /* xSleep */ \
7441 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007442 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007443 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007444 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007445 unixGetSystemCall, /* xGetSystemCall */ \
7446 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007447 }
7448
drh6b9d6dd2008-12-03 19:34:47 +00007449 /*
7450 ** All default VFSes for unix are contained in the following array.
7451 **
7452 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7453 ** by the SQLite core when the VFS is registered. So the following
7454 ** array cannot be const.
7455 */
danielk1977e339d652008-06-28 11:23:00 +00007456 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007457#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007458 UNIXVFS("unix", autolockIoFinder ),
7459#else
7460 UNIXVFS("unix", posixIoFinder ),
7461#endif
7462 UNIXVFS("unix-none", nolockIoFinder ),
7463 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007464 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007465#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007466 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007467#endif
7468#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007469 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007470#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007471 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007472#endif
chw78a13182009-04-07 05:35:03 +00007473#endif
drhd2cb50b2009-01-09 21:41:17 +00007474#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007475 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007476 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007477 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007478#endif
drh153c62c2007-08-24 03:51:33 +00007479 };
drh6b9d6dd2008-12-03 19:34:47 +00007480 unsigned int i; /* Loop counter */
7481
drh2aa5a002011-04-13 13:42:25 +00007482 /* Double-check that the aSyscall[] array has been constructed
7483 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007484 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007485
drh6b9d6dd2008-12-03 19:34:47 +00007486 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007487 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007488 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007489 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007490 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007491}
danielk1977e339d652008-06-28 11:23:00 +00007492
7493/*
drh6b9d6dd2008-12-03 19:34:47 +00007494** Shutdown the operating system interface.
7495**
7496** Some operating systems might need to do some cleanup in this routine,
7497** to release dynamically allocated objects. But not on unix.
7498** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007499*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007500int sqlite3_os_end(void){
7501 return SQLITE_OK;
7502}
drhdce8bdb2007-08-16 13:01:44 +00007503
danielk197729bafea2008-06-26 10:41:19 +00007504#endif /* SQLITE_OS_UNIX */