blob: 151ed890ae4eaab10644cac3e6f9abdd2cf52420 [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*);
326
drh9a3baf12011-04-25 18:01:27 +0000327/*
drh99ab3b12011-03-02 15:09:07 +0000328** Many system calls are accessed through pointer-to-functions so that
329** they may be overridden at runtime to facilitate fault injection during
330** testing and sandboxing. The following array holds the names and pointers
331** to all overrideable system calls.
332*/
333static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000334 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000335 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
336 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000337} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000338 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
339#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000340
drh58ad5802011-03-23 22:02:23 +0000341 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000342#define osClose ((int(*)(int))aSyscall[1].pCurrent)
343
drh58ad5802011-03-23 22:02:23 +0000344 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
346
drh58ad5802011-03-23 22:02:23 +0000347 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
349
drh58ad5802011-03-23 22:02:23 +0000350 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
352
353/*
354** The DJGPP compiler environment looks mostly like Unix, but it
355** lacks the fcntl() system call. So redefine fcntl() to be something
356** that always succeeds. This means that locking does not occur under
357** DJGPP. But it is DOS - what did you expect?
358*/
359#ifdef __DJGPP__
360 { "fstat", 0, 0 },
361#define osFstat(a,b,c) 0
362#else
drh58ad5802011-03-23 22:02:23 +0000363 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000364#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
365#endif
366
drh58ad5802011-03-23 22:02:23 +0000367 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
369
drh58ad5802011-03-23 22:02:23 +0000370 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000372
drh58ad5802011-03-23 22:02:23 +0000373 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000374#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
375
drhd4a80312011-04-15 14:33:20 +0000376#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000377 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000378#else
drh58ad5802011-03-23 22:02:23 +0000379 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000380#endif
381#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
382
383#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000384 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000385#else
drh58ad5802011-03-23 22:02:23 +0000386 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000387#endif
388#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
389
drh58ad5802011-03-23 22:02:23 +0000390 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000391#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
392
drhd4a80312011-04-15 14:33:20 +0000393#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000394 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000395#else
drh58ad5802011-03-23 22:02:23 +0000396 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000397#endif
398#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
399 aSyscall[12].pCurrent)
400
401#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000402 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000403#else
drh58ad5802011-03-23 22:02:23 +0000404 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000405#endif
406#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
407 aSyscall[13].pCurrent)
408
drh58ad5802011-03-23 22:02:23 +0000409 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000410#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000411
412#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000413 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000414#else
drh58ad5802011-03-23 22:02:23 +0000415 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000416#endif
dan0fd7d862011-03-29 10:04:23 +0000417#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000418
drh036ac7f2011-08-08 23:18:05 +0000419 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
420#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
421
drh90315a22011-08-10 01:52:12 +0000422 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
423#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
424
drh9ef6bc42011-11-04 02:24:02 +0000425 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
426#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
427
428 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
429#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
430
drhed466822012-05-31 13:10:49 +0000431 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000432#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000433
dan4dd51442013-08-26 14:30:25 +0000434#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000435 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
436#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
437
drhd1ab8062013-03-25 20:50:25 +0000438 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
439#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
440
dane6ecd662013-04-01 17:56:59 +0000441#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000442 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
443#else
444 { "mremap", (sqlite3_syscall_ptr)0, 0 },
445#endif
446#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
dan4dd51442013-08-26 14:30:25 +0000447#endif
drhd1ab8062013-03-25 20:50:25 +0000448
drhe562be52011-03-02 18:01:10 +0000449}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000450
451/*
452** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000453** "unix" VFSes. Return SQLITE_OK opon successfully updating the
454** system call pointer, or SQLITE_NOTFOUND if there is no configurable
455** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000456*/
457static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000458 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
459 const char *zName, /* Name of system call to override */
460 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000461){
drh58ad5802011-03-23 22:02:23 +0000462 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000463 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000464
465 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000466 if( zName==0 ){
467 /* If no zName is given, restore all system calls to their default
468 ** settings and return NULL
469 */
dan51438a72011-04-02 17:00:47 +0000470 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000471 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
472 if( aSyscall[i].pDefault ){
473 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000474 }
475 }
476 }else{
477 /* If zName is specified, operate on only the one system call
478 ** specified.
479 */
480 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
481 if( strcmp(zName, aSyscall[i].zName)==0 ){
482 if( aSyscall[i].pDefault==0 ){
483 aSyscall[i].pDefault = aSyscall[i].pCurrent;
484 }
drh1df30962011-03-02 19:06:42 +0000485 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000486 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
487 aSyscall[i].pCurrent = pNewFunc;
488 break;
489 }
490 }
491 }
492 return rc;
493}
494
drh1df30962011-03-02 19:06:42 +0000495/*
496** Return the value of a system call. Return NULL if zName is not a
497** recognized system call name. NULL is also returned if the system call
498** is currently undefined.
499*/
drh58ad5802011-03-23 22:02:23 +0000500static sqlite3_syscall_ptr unixGetSystemCall(
501 sqlite3_vfs *pNotUsed,
502 const char *zName
503){
504 unsigned int i;
505
506 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000507 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
508 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
509 }
510 return 0;
511}
512
513/*
514** Return the name of the first system call after zName. If zName==NULL
515** then return the name of the first system call. Return NULL if zName
516** is the last system call or if zName is not the name of a valid
517** system call.
518*/
519static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000520 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000521
522 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000523 if( zName ){
524 for(i=0; i<ArraySize(aSyscall)-1; i++){
525 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000526 }
527 }
dan0fd7d862011-03-29 10:04:23 +0000528 for(i++; i<ArraySize(aSyscall); i++){
529 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000530 }
531 return 0;
532}
533
drhad4f1e52011-03-04 15:43:57 +0000534/*
drh77a3fdc2013-08-30 14:24:12 +0000535** Do not accept any file descriptor less than this value, in order to avoid
536** opening database file using file descriptors that are commonly used for
537** standard input, output, and error.
538*/
539#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
540# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
541#endif
542
543/*
drh8c815d12012-02-13 20:16:37 +0000544** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000545** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000546**
547** If the file creation mode "m" is 0 then set it to the default for
548** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
549** 0644) as modified by the system umask. If m is not 0, then
550** make the file creation mode be exactly m ignoring the umask.
551**
552** The m parameter will be non-zero only when creating -wal, -journal,
553** and -shm files. We want those files to have *exactly* the same
554** permissions as their original database, unadulterated by the umask.
555** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
556** transaction crashes and leaves behind hot journals, then any
557** process that is able to write to the database will also be able to
558** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000559*/
drh8c815d12012-02-13 20:16:37 +0000560static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000561 int fd;
drhe1186ab2013-01-04 20:45:13 +0000562 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000563 while(1){
drh5adc60b2012-04-14 13:25:11 +0000564#if defined(O_CLOEXEC)
565 fd = osOpen(z,f|O_CLOEXEC,m2);
566#else
567 fd = osOpen(z,f,m2);
568#endif
drh5128d002013-08-30 06:20:23 +0000569 if( fd<0 ){
570 if( errno==EINTR ) continue;
571 break;
572 }
drh77a3fdc2013-08-30 14:24:12 +0000573 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000574 osClose(fd);
575 sqlite3_log(SQLITE_WARNING,
576 "attempt to open \"%s\" as file descriptor %d", z, fd);
577 fd = -1;
578 if( osOpen("/dev/null", f, m)<0 ) break;
579 }
drhe1186ab2013-01-04 20:45:13 +0000580 if( fd>=0 ){
581 if( m!=0 ){
582 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000583 if( osFstat(fd, &statbuf)==0
584 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000585 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000586 ){
drhe1186ab2013-01-04 20:45:13 +0000587 osFchmod(fd, m);
588 }
589 }
drh5adc60b2012-04-14 13:25:11 +0000590#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000591 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000592#endif
drhe1186ab2013-01-04 20:45:13 +0000593 }
drh5adc60b2012-04-14 13:25:11 +0000594 return fd;
drhad4f1e52011-03-04 15:43:57 +0000595}
danielk197713adf8a2004-06-03 16:08:41 +0000596
drh107886a2008-11-21 22:21:50 +0000597/*
dan9359c7b2009-08-21 08:29:10 +0000598** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000599** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000600** vxworksFileId objects used by this file, all of which may be
601** shared by multiple threads.
602**
603** Function unixMutexHeld() is used to assert() that the global mutex
604** is held when required. This function is only used as part of assert()
605** statements. e.g.
606**
607** unixEnterMutex()
608** assert( unixMutexHeld() );
609** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000610*/
611static void unixEnterMutex(void){
612 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
613}
614static void unixLeaveMutex(void){
615 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
616}
dan9359c7b2009-08-21 08:29:10 +0000617#ifdef SQLITE_DEBUG
618static int unixMutexHeld(void) {
619 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
620}
621#endif
drh107886a2008-11-21 22:21:50 +0000622
drh734c9862008-11-28 15:37:20 +0000623
drh30ddce62011-10-15 00:16:30 +0000624#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000625/*
626** Helper function for printing out trace information from debugging
627** binaries. This returns the string represetation of the supplied
628** integer lock-type.
629*/
drh308c2a52010-05-14 11:30:18 +0000630static const char *azFileLock(int eFileLock){
631 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000632 case NO_LOCK: return "NONE";
633 case SHARED_LOCK: return "SHARED";
634 case RESERVED_LOCK: return "RESERVED";
635 case PENDING_LOCK: return "PENDING";
636 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000637 }
638 return "ERROR";
639}
640#endif
641
642#ifdef SQLITE_LOCK_TRACE
643/*
644** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000645**
drh734c9862008-11-28 15:37:20 +0000646** This routine is used for troubleshooting locks on multithreaded
647** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
648** command-line option on the compiler. This code is normally
649** turned off.
650*/
651static int lockTrace(int fd, int op, struct flock *p){
652 char *zOpName, *zType;
653 int s;
654 int savedErrno;
655 if( op==F_GETLK ){
656 zOpName = "GETLK";
657 }else if( op==F_SETLK ){
658 zOpName = "SETLK";
659 }else{
drh99ab3b12011-03-02 15:09:07 +0000660 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000661 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
662 return s;
663 }
664 if( p->l_type==F_RDLCK ){
665 zType = "RDLCK";
666 }else if( p->l_type==F_WRLCK ){
667 zType = "WRLCK";
668 }else if( p->l_type==F_UNLCK ){
669 zType = "UNLCK";
670 }else{
671 assert( 0 );
672 }
673 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000674 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000675 savedErrno = errno;
676 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
677 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
678 (int)p->l_pid, s);
679 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
680 struct flock l2;
681 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000682 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000683 if( l2.l_type==F_RDLCK ){
684 zType = "RDLCK";
685 }else if( l2.l_type==F_WRLCK ){
686 zType = "WRLCK";
687 }else if( l2.l_type==F_UNLCK ){
688 zType = "UNLCK";
689 }else{
690 assert( 0 );
691 }
692 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
693 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
694 }
695 errno = savedErrno;
696 return s;
697}
drh99ab3b12011-03-02 15:09:07 +0000698#undef osFcntl
699#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000700#endif /* SQLITE_LOCK_TRACE */
701
drhff812312011-02-23 13:33:46 +0000702/*
703** Retry ftruncate() calls that fail due to EINTR
704*/
drhff812312011-02-23 13:33:46 +0000705static int robust_ftruncate(int h, sqlite3_int64 sz){
706 int rc;
drh99ab3b12011-03-02 15:09:07 +0000707 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000708 return rc;
709}
drh734c9862008-11-28 15:37:20 +0000710
711/*
712** This routine translates a standard POSIX errno code into something
713** useful to the clients of the sqlite3 functions. Specifically, it is
714** intended to translate a variety of "try again" errors into SQLITE_BUSY
715** and a variety of "please close the file descriptor NOW" errors into
716** SQLITE_IOERR
717**
718** Errors during initialization of locks, or file system support for locks,
719** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
720*/
721static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
722 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000723#if 0
724 /* At one point this code was not commented out. In theory, this branch
725 ** should never be hit, as this function should only be called after
726 ** a locking-related function (i.e. fcntl()) has returned non-zero with
727 ** the value of errno as the first argument. Since a system call has failed,
728 ** errno should be non-zero.
729 **
730 ** Despite this, if errno really is zero, we still don't want to return
731 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
732 ** propagated back to the caller. Commenting this branch out means errno==0
733 ** will be handled by the "default:" case below.
734 */
drh734c9862008-11-28 15:37:20 +0000735 case 0:
736 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000737#endif
738
drh734c9862008-11-28 15:37:20 +0000739 case EAGAIN:
740 case ETIMEDOUT:
741 case EBUSY:
742 case EINTR:
743 case ENOLCK:
744 /* random NFS retry error, unless during file system support
745 * introspection, in which it actually means what it says */
746 return SQLITE_BUSY;
747
748 case EACCES:
749 /* EACCES is like EAGAIN during locking operations, but not any other time*/
750 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000751 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
752 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
753 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000754 return SQLITE_BUSY;
755 }
756 /* else fall through */
757 case EPERM:
758 return SQLITE_PERM;
759
danea83bc62011-04-01 11:56:32 +0000760 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
761 ** this module never makes such a call. And the code in SQLite itself
762 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
763 ** this case is also commented out. If the system does set errno to EDEADLK,
764 ** the default SQLITE_IOERR_XXX code will be returned. */
765#if 0
drh734c9862008-11-28 15:37:20 +0000766 case EDEADLK:
767 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000768#endif
drh734c9862008-11-28 15:37:20 +0000769
770#if EOPNOTSUPP!=ENOTSUP
771 case EOPNOTSUPP:
772 /* something went terribly awry, unless during file system support
773 * introspection, in which it actually means what it says */
774#endif
775#ifdef ENOTSUP
776 case ENOTSUP:
777 /* invalid fd, unless during file system support introspection, in which
778 * it actually means what it says */
779#endif
780 case EIO:
781 case EBADF:
782 case EINVAL:
783 case ENOTCONN:
784 case ENODEV:
785 case ENXIO:
786 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000787#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000788 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000789#endif
drh734c9862008-11-28 15:37:20 +0000790 case ENOSYS:
791 /* these should force the client to close the file and reconnect */
792
793 default:
794 return sqliteIOErr;
795 }
796}
797
798
drh734c9862008-11-28 15:37:20 +0000799/******************************************************************************
800****************** Begin Unique File ID Utility Used By VxWorks ***************
801**
802** On most versions of unix, we can get a unique ID for a file by concatenating
803** the device number and the inode number. But this does not work on VxWorks.
804** On VxWorks, a unique file id must be based on the canonical filename.
805**
806** A pointer to an instance of the following structure can be used as a
807** unique file ID in VxWorks. Each instance of this structure contains
808** a copy of the canonical filename. There is also a reference count.
809** The structure is reclaimed when the number of pointers to it drops to
810** zero.
811**
812** There are never very many files open at one time and lookups are not
813** a performance-critical path, so it is sufficient to put these
814** structures on a linked list.
815*/
816struct vxworksFileId {
817 struct vxworksFileId *pNext; /* Next in a list of them all */
818 int nRef; /* Number of references to this one */
819 int nName; /* Length of the zCanonicalName[] string */
820 char *zCanonicalName; /* Canonical filename */
821};
822
823#if OS_VXWORKS
824/*
drh9b35ea62008-11-29 02:20:26 +0000825** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000826** variable:
827*/
828static struct vxworksFileId *vxworksFileList = 0;
829
830/*
831** Simplify a filename into its canonical form
832** by making the following changes:
833**
834** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000835** * convert /./ into just /
836** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000837**
838** Changes are made in-place. Return the new name length.
839**
840** The original filename is in z[0..n-1]. Return the number of
841** characters in the simplified name.
842*/
843static int vxworksSimplifyName(char *z, int n){
844 int i, j;
845 while( n>1 && z[n-1]=='/' ){ n--; }
846 for(i=j=0; i<n; i++){
847 if( z[i]=='/' ){
848 if( z[i+1]=='/' ) continue;
849 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
850 i += 1;
851 continue;
852 }
853 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
854 while( j>0 && z[j-1]!='/' ){ j--; }
855 if( j>0 ){ j--; }
856 i += 2;
857 continue;
858 }
859 }
860 z[j++] = z[i];
861 }
862 z[j] = 0;
863 return j;
864}
865
866/*
867** Find a unique file ID for the given absolute pathname. Return
868** a pointer to the vxworksFileId object. This pointer is the unique
869** file ID.
870**
871** The nRef field of the vxworksFileId object is incremented before
872** the object is returned. A new vxworksFileId object is created
873** and added to the global list if necessary.
874**
875** If a memory allocation error occurs, return NULL.
876*/
877static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
878 struct vxworksFileId *pNew; /* search key and new file ID */
879 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
880 int n; /* Length of zAbsoluteName string */
881
882 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000883 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000884 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
885 if( pNew==0 ) return 0;
886 pNew->zCanonicalName = (char*)&pNew[1];
887 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
888 n = vxworksSimplifyName(pNew->zCanonicalName, n);
889
890 /* Search for an existing entry that matching the canonical name.
891 ** If found, increment the reference count and return a pointer to
892 ** the existing file ID.
893 */
894 unixEnterMutex();
895 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
896 if( pCandidate->nName==n
897 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
898 ){
899 sqlite3_free(pNew);
900 pCandidate->nRef++;
901 unixLeaveMutex();
902 return pCandidate;
903 }
904 }
905
906 /* No match was found. We will make a new file ID */
907 pNew->nRef = 1;
908 pNew->nName = n;
909 pNew->pNext = vxworksFileList;
910 vxworksFileList = pNew;
911 unixLeaveMutex();
912 return pNew;
913}
914
915/*
916** Decrement the reference count on a vxworksFileId object. Free
917** the object when the reference count reaches zero.
918*/
919static void vxworksReleaseFileId(struct vxworksFileId *pId){
920 unixEnterMutex();
921 assert( pId->nRef>0 );
922 pId->nRef--;
923 if( pId->nRef==0 ){
924 struct vxworksFileId **pp;
925 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
926 assert( *pp==pId );
927 *pp = pId->pNext;
928 sqlite3_free(pId);
929 }
930 unixLeaveMutex();
931}
932#endif /* OS_VXWORKS */
933/*************** End of Unique File ID Utility Used By VxWorks ****************
934******************************************************************************/
935
936
937/******************************************************************************
938*************************** Posix Advisory Locking ****************************
939**
drh9b35ea62008-11-29 02:20:26 +0000940** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000941** section 6.5.2.2 lines 483 through 490 specify that when a process
942** sets or clears a lock, that operation overrides any prior locks set
943** by the same process. It does not explicitly say so, but this implies
944** that it overrides locks set by the same process using a different
945** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000946**
947** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000948** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
949**
950** Suppose ./file1 and ./file2 are really the same file (because
951** one is a hard or symbolic link to the other) then if you set
952** an exclusive lock on fd1, then try to get an exclusive lock
953** on fd2, it works. I would have expected the second lock to
954** fail since there was already a lock on the file due to fd1.
955** But not so. Since both locks came from the same process, the
956** second overrides the first, even though they were on different
957** file descriptors opened on different file names.
958**
drh734c9862008-11-28 15:37:20 +0000959** This means that we cannot use POSIX locks to synchronize file access
960** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000961** to synchronize access for threads in separate processes, but not
962** threads within the same process.
963**
964** To work around the problem, SQLite has to manage file locks internally
965** on its own. Whenever a new database is opened, we have to find the
966** specific inode of the database file (the inode is determined by the
967** st_dev and st_ino fields of the stat structure that fstat() fills in)
968** and check for locks already existing on that inode. When locks are
969** created or removed, we have to look at our own internal record of the
970** locks to see if another thread has previously set a lock on that same
971** inode.
972**
drh9b35ea62008-11-29 02:20:26 +0000973** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
974** For VxWorks, we have to use the alternative unique ID system based on
975** canonical filename and implemented in the previous division.)
976**
danielk1977ad94b582007-08-20 06:44:22 +0000977** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000978** descriptor. It is now a structure that holds the integer file
979** descriptor and a pointer to a structure that describes the internal
980** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000981** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000982** point to the same locking structure. The locking structure keeps
983** a reference count (so we will know when to delete it) and a "cnt"
984** field that tells us its internal lock status. cnt==0 means the
985** file is unlocked. cnt==-1 means the file has an exclusive lock.
986** cnt>0 means there are cnt shared locks on the file.
987**
988** Any attempt to lock or unlock a file first checks the locking
989** structure. The fcntl() system call is only invoked to set a
990** POSIX lock if the internal lock structure transitions between
991** a locked and an unlocked state.
992**
drh734c9862008-11-28 15:37:20 +0000993** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000994**
995** If you close a file descriptor that points to a file that has locks,
996** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000997** released. To work around this problem, each unixInodeInfo object
998** maintains a count of the number of pending locks on tha inode.
999** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001000** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001001** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001002** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001003** be closed and that list is walked (and cleared) when the last lock
1004** clears.
1005**
drh9b35ea62008-11-29 02:20:26 +00001006** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001007**
drh9b35ea62008-11-29 02:20:26 +00001008** Many older versions of linux use the LinuxThreads library which is
1009** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001010** A cannot be modified or overridden by a different thread B.
1011** Only thread A can modify the lock. Locking behavior is correct
1012** if the appliation uses the newer Native Posix Thread Library (NPTL)
1013** on linux - with NPTL a lock created by thread A can override locks
1014** in thread B. But there is no way to know at compile-time which
1015** threading library is being used. So there is no way to know at
1016** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001017** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001018** current process.
drh5fdae772004-06-29 03:29:00 +00001019**
drh8af6c222010-05-14 12:43:01 +00001020** SQLite used to support LinuxThreads. But support for LinuxThreads
1021** was dropped beginning with version 3.7.0. SQLite will still work with
1022** LinuxThreads provided that (1) there is no more than one connection
1023** per database file in the same process and (2) database connections
1024** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001025*/
1026
1027/*
1028** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001029** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001030*/
1031struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001032 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001033#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001034 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001035#else
drh107886a2008-11-21 22:21:50 +00001036 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001037#endif
1038};
1039
1040/*
drhbbd42a62004-05-22 17:41:58 +00001041** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001042** inode. Or, on LinuxThreads, there is one of these structures for
1043** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001044**
danielk1977ad94b582007-08-20 06:44:22 +00001045** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001046** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001047** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001048*/
drh8af6c222010-05-14 12:43:01 +00001049struct unixInodeInfo {
1050 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001051 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001052 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1053 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001054 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001055 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1056 int nLock; /* Number of outstanding file locks */
1057 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1058 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1059 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001060#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001061 unsigned long long sharedByte; /* for AFP simulated shared lock */
1062#endif
drh6c7d5c52008-11-21 20:32:33 +00001063#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001064 sem_t *pSem; /* Named POSIX semaphore */
1065 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001066#endif
drhbbd42a62004-05-22 17:41:58 +00001067};
1068
drhda0e7682008-07-30 15:27:54 +00001069/*
drh8af6c222010-05-14 12:43:01 +00001070** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001071*/
drhd91c68f2010-05-14 14:52:25 +00001072static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001073
drh5fdae772004-06-29 03:29:00 +00001074/*
dane18d4952011-02-21 11:46:24 +00001075**
1076** This function - unixLogError_x(), is only ever called via the macro
1077** unixLogError().
1078**
1079** It is invoked after an error occurs in an OS function and errno has been
1080** set. It logs a message using sqlite3_log() containing the current value of
1081** errno and, if possible, the human-readable equivalent from strerror() or
1082** strerror_r().
1083**
1084** The first argument passed to the macro should be the error code that
1085** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1086** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001087** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001088** if any.
1089*/
drh0e9365c2011-03-02 02:08:13 +00001090#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1091static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001092 int errcode, /* SQLite error code */
1093 const char *zFunc, /* Name of OS function that failed */
1094 const char *zPath, /* File path associated with error */
1095 int iLine /* Source line number where error occurred */
1096){
1097 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001098 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001099
1100 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1101 ** the strerror() function to obtain the human-readable error message
1102 ** equivalent to errno. Otherwise, use strerror_r().
1103 */
1104#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1105 char aErr[80];
1106 memset(aErr, 0, sizeof(aErr));
1107 zErr = aErr;
1108
1109 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001110 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001111 ** returns a pointer to a buffer containing the error message. That pointer
1112 ** may point to aErr[], or it may point to some static storage somewhere.
1113 ** Otherwise, assume that the system provides the POSIX version of
1114 ** strerror_r(), which always writes an error message into aErr[].
1115 **
1116 ** If the code incorrectly assumes that it is the POSIX version that is
1117 ** available, the error message will often be an empty string. Not a
1118 ** huge problem. Incorrectly concluding that the GNU version is available
1119 ** could lead to a segfault though.
1120 */
1121#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1122 zErr =
1123# endif
drh0e9365c2011-03-02 02:08:13 +00001124 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001125
1126#elif SQLITE_THREADSAFE
1127 /* This is a threadsafe build, but strerror_r() is not available. */
1128 zErr = "";
1129#else
1130 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001131 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001132#endif
1133
drh0e9365c2011-03-02 02:08:13 +00001134 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001135 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001136 "os_unix.c:%d: (%d) %s(%s) - %s",
1137 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001138 );
1139
1140 return errcode;
1141}
1142
drh0e9365c2011-03-02 02:08:13 +00001143/*
1144** Close a file descriptor.
1145**
1146** We assume that close() almost always works, since it is only in a
1147** very sick application or on a very sick platform that it might fail.
1148** If it does fail, simply leak the file descriptor, but do log the
1149** error.
1150**
1151** Note that it is not safe to retry close() after EINTR since the
1152** file descriptor might have already been reused by another thread.
1153** So we don't even try to recover from an EINTR. Just log the error
1154** and move on.
1155*/
1156static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001157 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001158 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1159 pFile ? pFile->zPath : 0, lineno);
1160 }
1161}
dane18d4952011-02-21 11:46:24 +00001162
1163/*
danb0ac3e32010-06-16 10:55:42 +00001164** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001165*/
drh0e9365c2011-03-02 02:08:13 +00001166static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001167 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001168 UnixUnusedFd *p;
1169 UnixUnusedFd *pNext;
1170 for(p=pInode->pUnused; p; p=pNext){
1171 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001172 robust_close(pFile, p->fd, __LINE__);
1173 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001174 }
drh0e9365c2011-03-02 02:08:13 +00001175 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001176}
1177
1178/*
drh8af6c222010-05-14 12:43:01 +00001179** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001180**
1181** The mutex entered using the unixEnterMutex() function must be held
1182** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001183*/
danb0ac3e32010-06-16 10:55:42 +00001184static void releaseInodeInfo(unixFile *pFile){
1185 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001186 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001187 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001188 pInode->nRef--;
1189 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001190 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001191 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001192 if( pInode->pPrev ){
1193 assert( pInode->pPrev->pNext==pInode );
1194 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001195 }else{
drh8af6c222010-05-14 12:43:01 +00001196 assert( inodeList==pInode );
1197 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001198 }
drh8af6c222010-05-14 12:43:01 +00001199 if( pInode->pNext ){
1200 assert( pInode->pNext->pPrev==pInode );
1201 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001202 }
drh8af6c222010-05-14 12:43:01 +00001203 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001204 }
drhbbd42a62004-05-22 17:41:58 +00001205 }
1206}
1207
1208/*
drh8af6c222010-05-14 12:43:01 +00001209** Given a file descriptor, locate the unixInodeInfo object that
1210** describes that file descriptor. Create a new one if necessary. The
1211** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001212**
dan9359c7b2009-08-21 08:29:10 +00001213** The mutex entered using the unixEnterMutex() function must be held
1214** when this function is called.
1215**
drh6c7d5c52008-11-21 20:32:33 +00001216** Return an appropriate error code.
1217*/
drh8af6c222010-05-14 12:43:01 +00001218static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001219 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001220 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001221){
1222 int rc; /* System call return code */
1223 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001224 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1225 struct stat statbuf; /* Low-level file information */
1226 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001227
dan9359c7b2009-08-21 08:29:10 +00001228 assert( unixMutexHeld() );
1229
drh6c7d5c52008-11-21 20:32:33 +00001230 /* Get low-level information about the file that we can used to
1231 ** create a unique name for the file.
1232 */
1233 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001234 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001235 if( rc!=0 ){
1236 pFile->lastErrno = errno;
1237#ifdef EOVERFLOW
1238 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1239#endif
1240 return SQLITE_IOERR;
1241 }
1242
drheb0d74f2009-02-03 15:27:02 +00001243#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001244 /* On OS X on an msdos filesystem, the inode number is reported
1245 ** incorrectly for zero-size files. See ticket #3260. To work
1246 ** around this problem (we consider it a bug in OS X, not SQLite)
1247 ** we always increase the file size to 1 by writing a single byte
1248 ** prior to accessing the inode number. The one byte written is
1249 ** an ASCII 'S' character which also happens to be the first byte
1250 ** in the header of every SQLite database. In this way, if there
1251 ** is a race condition such that another thread has already populated
1252 ** the first page of the database, no damage is done.
1253 */
drh7ed97b92010-01-20 13:07:21 +00001254 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001255 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001256 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001257 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001258 return SQLITE_IOERR;
1259 }
drh99ab3b12011-03-02 15:09:07 +00001260 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001261 if( rc!=0 ){
1262 pFile->lastErrno = errno;
1263 return SQLITE_IOERR;
1264 }
1265 }
drheb0d74f2009-02-03 15:27:02 +00001266#endif
drh6c7d5c52008-11-21 20:32:33 +00001267
drh8af6c222010-05-14 12:43:01 +00001268 memset(&fileId, 0, sizeof(fileId));
1269 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001270#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001271 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001272#else
drh8af6c222010-05-14 12:43:01 +00001273 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001274#endif
drh8af6c222010-05-14 12:43:01 +00001275 pInode = inodeList;
1276 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1277 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001278 }
drh8af6c222010-05-14 12:43:01 +00001279 if( pInode==0 ){
1280 pInode = sqlite3_malloc( sizeof(*pInode) );
1281 if( pInode==0 ){
1282 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001283 }
drh8af6c222010-05-14 12:43:01 +00001284 memset(pInode, 0, sizeof(*pInode));
1285 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1286 pInode->nRef = 1;
1287 pInode->pNext = inodeList;
1288 pInode->pPrev = 0;
1289 if( inodeList ) inodeList->pPrev = pInode;
1290 inodeList = pInode;
1291 }else{
1292 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001293 }
drh8af6c222010-05-14 12:43:01 +00001294 *ppInode = pInode;
1295 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001296}
drh6c7d5c52008-11-21 20:32:33 +00001297
drhb959a012013-12-07 12:29:22 +00001298/*
1299** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1300*/
1301static int fileHasMoved(unixFile *pFile){
1302 struct stat buf;
1303 return pFile->pInode!=0 &&
1304 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
1305}
1306
aswift5b1a2562008-08-22 00:22:35 +00001307
1308/*
drhfbc7e882013-04-11 01:16:15 +00001309** Check a unixFile that is a database. Verify the following:
1310**
1311** (1) There is exactly one hard link on the file
1312** (2) The file is not a symbolic link
1313** (3) The file has not been renamed or unlinked
1314**
1315** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1316*/
1317static void verifyDbFile(unixFile *pFile){
1318 struct stat buf;
1319 int rc;
1320 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1321 /* One or more of the following warnings have already been issued. Do not
1322 ** repeat them so as not to clutter the error log */
1323 return;
1324 }
1325 rc = osFstat(pFile->h, &buf);
1326 if( rc!=0 ){
1327 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1328 pFile->ctrlFlags |= UNIXFILE_WARNED;
1329 return;
1330 }
1331 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
1332 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1333 pFile->ctrlFlags |= UNIXFILE_WARNED;
1334 return;
1335 }
1336 if( buf.st_nlink>1 ){
1337 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1338 pFile->ctrlFlags |= UNIXFILE_WARNED;
1339 return;
1340 }
drhb959a012013-12-07 12:29:22 +00001341 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001342 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1343 pFile->ctrlFlags |= UNIXFILE_WARNED;
1344 return;
1345 }
1346}
1347
1348
1349/*
danielk197713adf8a2004-06-03 16:08:41 +00001350** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001351** file by this or any other process. If such a lock is held, set *pResOut
1352** to a non-zero value otherwise *pResOut is set to zero. The return value
1353** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001354*/
danielk1977861f7452008-06-05 11:39:11 +00001355static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001356 int rc = SQLITE_OK;
1357 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001358 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001359
danielk1977861f7452008-06-05 11:39:11 +00001360 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1361
drh054889e2005-11-30 03:20:31 +00001362 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001363 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001364
1365 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001366 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001367 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001368 }
1369
drh2ac3ee92004-06-07 16:27:46 +00001370 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001371 */
danielk197709480a92009-02-09 05:32:32 +00001372#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001373 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001374 struct flock lock;
1375 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001376 lock.l_start = RESERVED_BYTE;
1377 lock.l_len = 1;
1378 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001379 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1380 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1381 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001382 } else if( lock.l_type!=F_UNLCK ){
1383 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001384 }
1385 }
danielk197709480a92009-02-09 05:32:32 +00001386#endif
danielk197713adf8a2004-06-03 16:08:41 +00001387
drh6c7d5c52008-11-21 20:32:33 +00001388 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001389 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001390
aswift5b1a2562008-08-22 00:22:35 +00001391 *pResOut = reserved;
1392 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001393}
1394
1395/*
drha7e61d82011-03-12 17:02:57 +00001396** Attempt to set a system-lock on the file pFile. The lock is
1397** described by pLock.
1398**
drh77197112011-03-15 19:08:48 +00001399** If the pFile was opened read/write from unix-excl, then the only lock
1400** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001401** the first time any lock is attempted. All subsequent system locking
1402** operations become no-ops. Locking operations still happen internally,
1403** in order to coordinate access between separate database connections
1404** within this process, but all of that is handled in memory and the
1405** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001406**
1407** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1408** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1409** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001410**
1411** Zero is returned if the call completes successfully, or -1 if a call
1412** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001413*/
1414static int unixFileLock(unixFile *pFile, struct flock *pLock){
1415 int rc;
drh3cb93392011-03-12 18:10:44 +00001416 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001417 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001418 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001419 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1420 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1421 ){
drh3cb93392011-03-12 18:10:44 +00001422 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001423 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001424 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001425 lock.l_whence = SEEK_SET;
1426 lock.l_start = SHARED_FIRST;
1427 lock.l_len = SHARED_SIZE;
1428 lock.l_type = F_WRLCK;
1429 rc = osFcntl(pFile->h, F_SETLK, &lock);
1430 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001431 pInode->bProcessLock = 1;
1432 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001433 }else{
1434 rc = 0;
1435 }
1436 }else{
1437 rc = osFcntl(pFile->h, F_SETLK, pLock);
1438 }
1439 return rc;
1440}
1441
1442/*
drh308c2a52010-05-14 11:30:18 +00001443** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001444** of the following:
1445**
drh2ac3ee92004-06-07 16:27:46 +00001446** (1) SHARED_LOCK
1447** (2) RESERVED_LOCK
1448** (3) PENDING_LOCK
1449** (4) EXCLUSIVE_LOCK
1450**
drhb3e04342004-06-08 00:47:47 +00001451** Sometimes when requesting one lock state, additional lock states
1452** are inserted in between. The locking might fail on one of the later
1453** transitions leaving the lock state different from what it started but
1454** still short of its goal. The following chart shows the allowed
1455** transitions and the inserted intermediate states:
1456**
1457** UNLOCKED -> SHARED
1458** SHARED -> RESERVED
1459** SHARED -> (PENDING) -> EXCLUSIVE
1460** RESERVED -> (PENDING) -> EXCLUSIVE
1461** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001462**
drha6abd042004-06-09 17:37:22 +00001463** This routine will only increase a lock. Use the sqlite3OsUnlock()
1464** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001465*/
drh308c2a52010-05-14 11:30:18 +00001466static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001467 /* The following describes the implementation of the various locks and
1468 ** lock transitions in terms of the POSIX advisory shared and exclusive
1469 ** lock primitives (called read-locks and write-locks below, to avoid
1470 ** confusion with SQLite lock names). The algorithms are complicated
1471 ** slightly in order to be compatible with windows systems simultaneously
1472 ** accessing the same database file, in case that is ever required.
1473 **
1474 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1475 ** byte', each single bytes at well known offsets, and the 'shared byte
1476 ** range', a range of 510 bytes at a well known offset.
1477 **
1478 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1479 ** byte'. If this is successful, a random byte from the 'shared byte
1480 ** range' is read-locked and the lock on the 'pending byte' released.
1481 **
danielk197790ba3bd2004-06-25 08:32:25 +00001482 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1483 ** A RESERVED lock is implemented by grabbing a write-lock on the
1484 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001485 **
1486 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001487 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1488 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1489 ** obtained, but existing SHARED locks are allowed to persist. A process
1490 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1491 ** This property is used by the algorithm for rolling back a journal file
1492 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001493 **
danielk197790ba3bd2004-06-25 08:32:25 +00001494 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1495 ** implemented by obtaining a write-lock on the entire 'shared byte
1496 ** range'. Since all other locks require a read-lock on one of the bytes
1497 ** within this range, this ensures that no other locks are held on the
1498 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001499 **
1500 ** The reason a single byte cannot be used instead of the 'shared byte
1501 ** range' is that some versions of windows do not support read-locks. By
1502 ** locking a random byte from a range, concurrent SHARED locks may exist
1503 ** even if the locking primitive used is always a write-lock.
1504 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001505 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001506 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001507 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001508 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001509 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001510
drh054889e2005-11-30 03:20:31 +00001511 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001512 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1513 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001514 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001515
1516 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001517 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001518 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001519 */
drh308c2a52010-05-14 11:30:18 +00001520 if( pFile->eFileLock>=eFileLock ){
1521 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1522 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001523 return SQLITE_OK;
1524 }
1525
drh0c2694b2009-09-03 16:23:44 +00001526 /* Make sure the locking sequence is correct.
1527 ** (1) We never move from unlocked to anything higher than shared lock.
1528 ** (2) SQLite never explicitly requests a pendig lock.
1529 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001530 */
drh308c2a52010-05-14 11:30:18 +00001531 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1532 assert( eFileLock!=PENDING_LOCK );
1533 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001534
drh8af6c222010-05-14 12:43:01 +00001535 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001536 */
drh6c7d5c52008-11-21 20:32:33 +00001537 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001538 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001539
danielk1977ad94b582007-08-20 06:44:22 +00001540 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001541 ** handle that precludes the requested lock, return BUSY.
1542 */
drh8af6c222010-05-14 12:43:01 +00001543 if( (pFile->eFileLock!=pInode->eFileLock &&
1544 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001545 ){
1546 rc = SQLITE_BUSY;
1547 goto end_lock;
1548 }
1549
1550 /* If a SHARED lock is requested, and some thread using this PID already
1551 ** has a SHARED or RESERVED lock, then increment reference counts and
1552 ** return SQLITE_OK.
1553 */
drh308c2a52010-05-14 11:30:18 +00001554 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001555 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001556 assert( eFileLock==SHARED_LOCK );
1557 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001558 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001559 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001560 pInode->nShared++;
1561 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001562 goto end_lock;
1563 }
1564
danielk19779a1d0ab2004-06-01 14:09:28 +00001565
drh3cde3bb2004-06-12 02:17:14 +00001566 /* A PENDING lock is needed before acquiring a SHARED lock and before
1567 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1568 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001569 */
drh0c2694b2009-09-03 16:23:44 +00001570 lock.l_len = 1L;
1571 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001572 if( eFileLock==SHARED_LOCK
1573 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001574 ){
drh308c2a52010-05-14 11:30:18 +00001575 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001576 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001577 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001578 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001579 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001580 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001581 pFile->lastErrno = tErrno;
1582 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001583 goto end_lock;
1584 }
drh3cde3bb2004-06-12 02:17:14 +00001585 }
1586
1587
1588 /* If control gets to this point, then actually go ahead and make
1589 ** operating system calls for the specified lock.
1590 */
drh308c2a52010-05-14 11:30:18 +00001591 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001592 assert( pInode->nShared==0 );
1593 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001594 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001595
drh2ac3ee92004-06-07 16:27:46 +00001596 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001597 lock.l_start = SHARED_FIRST;
1598 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001599 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001600 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001601 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001602 }
dan661d71a2011-03-30 19:08:03 +00001603
drh2ac3ee92004-06-07 16:27:46 +00001604 /* Drop the temporary PENDING lock */
1605 lock.l_start = PENDING_BYTE;
1606 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001607 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001608 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1609 /* This could happen with a network mount */
1610 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001611 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001612 }
dan661d71a2011-03-30 19:08:03 +00001613
1614 if( rc ){
1615 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001616 pFile->lastErrno = tErrno;
1617 }
dan661d71a2011-03-30 19:08:03 +00001618 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001619 }else{
drh308c2a52010-05-14 11:30:18 +00001620 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001621 pInode->nLock++;
1622 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001623 }
drh8af6c222010-05-14 12:43:01 +00001624 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001625 /* We are trying for an exclusive lock but another thread in this
1626 ** same process is still holding a shared lock. */
1627 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001628 }else{
drh3cde3bb2004-06-12 02:17:14 +00001629 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001630 ** assumed that there is a SHARED or greater lock on the file
1631 ** already.
1632 */
drh308c2a52010-05-14 11:30:18 +00001633 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001634 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001635
1636 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1637 if( eFileLock==RESERVED_LOCK ){
1638 lock.l_start = RESERVED_BYTE;
1639 lock.l_len = 1L;
1640 }else{
1641 lock.l_start = SHARED_FIRST;
1642 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001643 }
dan661d71a2011-03-30 19:08:03 +00001644
1645 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001646 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001647 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001648 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001649 pFile->lastErrno = tErrno;
1650 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001651 }
drhbbd42a62004-05-22 17:41:58 +00001652 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001653
drh8f941bc2009-01-14 23:03:40 +00001654
drhd3d8c042012-05-29 17:02:40 +00001655#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001656 /* Set up the transaction-counter change checking flags when
1657 ** transitioning from a SHARED to a RESERVED lock. The change
1658 ** from SHARED to RESERVED marks the beginning of a normal
1659 ** write operation (not a hot journal rollback).
1660 */
1661 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001662 && pFile->eFileLock<=SHARED_LOCK
1663 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001664 ){
1665 pFile->transCntrChng = 0;
1666 pFile->dbUpdate = 0;
1667 pFile->inNormalWrite = 1;
1668 }
1669#endif
1670
1671
danielk1977ecb2a962004-06-02 06:30:16 +00001672 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001673 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001674 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001675 }else if( eFileLock==EXCLUSIVE_LOCK ){
1676 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001677 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001678 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001679
1680end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001681 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001682 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1683 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001684 return rc;
1685}
1686
1687/*
dan08da86a2009-08-21 17:18:03 +00001688** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001689** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001690*/
1691static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001692 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001693 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001694 p->pNext = pInode->pUnused;
1695 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001696 pFile->h = -1;
1697 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001698}
1699
1700/*
drh308c2a52010-05-14 11:30:18 +00001701** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001702** must be either NO_LOCK or SHARED_LOCK.
1703**
1704** If the locking level of the file descriptor is already at or below
1705** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001706**
1707** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1708** the byte range is divided into 2 parts and the first part is unlocked then
1709** set to a read lock, then the other part is simply unlocked. This works
1710** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1711** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001712*/
drha7e61d82011-03-12 17:02:57 +00001713static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001714 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001715 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001716 struct flock lock;
1717 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001718
drh054889e2005-11-30 03:20:31 +00001719 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001720 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001721 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001722 getpid()));
drha6abd042004-06-09 17:37:22 +00001723
drh308c2a52010-05-14 11:30:18 +00001724 assert( eFileLock<=SHARED_LOCK );
1725 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001726 return SQLITE_OK;
1727 }
drh6c7d5c52008-11-21 20:32:33 +00001728 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001729 pInode = pFile->pInode;
1730 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001731 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001732 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001733
drhd3d8c042012-05-29 17:02:40 +00001734#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001735 /* When reducing a lock such that other processes can start
1736 ** reading the database file again, make sure that the
1737 ** transaction counter was updated if any part of the database
1738 ** file changed. If the transaction counter is not updated,
1739 ** other connections to the same file might not realize that
1740 ** the file has changed and hence might not know to flush their
1741 ** cache. The use of a stale cache can lead to database corruption.
1742 */
drh8f941bc2009-01-14 23:03:40 +00001743 pFile->inNormalWrite = 0;
1744#endif
1745
drh7ed97b92010-01-20 13:07:21 +00001746 /* downgrading to a shared lock on NFS involves clearing the write lock
1747 ** before establishing the readlock - to avoid a race condition we downgrade
1748 ** the lock in 2 blocks, so that part of the range will be covered by a
1749 ** write lock until the rest is covered by a read lock:
1750 ** 1: [WWWWW]
1751 ** 2: [....W]
1752 ** 3: [RRRRW]
1753 ** 4: [RRRR.]
1754 */
drh308c2a52010-05-14 11:30:18 +00001755 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001756
1757#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001758 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001759 assert( handleNFSUnlock==0 );
1760#endif
1761#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001762 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001763 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001764 off_t divSize = SHARED_SIZE - 1;
1765
1766 lock.l_type = F_UNLCK;
1767 lock.l_whence = SEEK_SET;
1768 lock.l_start = SHARED_FIRST;
1769 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001770 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001771 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001772 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001773 if( IS_LOCK_ERROR(rc) ){
1774 pFile->lastErrno = tErrno;
1775 }
1776 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001777 }
drh7ed97b92010-01-20 13:07:21 +00001778 lock.l_type = F_RDLCK;
1779 lock.l_whence = SEEK_SET;
1780 lock.l_start = SHARED_FIRST;
1781 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001782 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001783 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001784 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1785 if( IS_LOCK_ERROR(rc) ){
1786 pFile->lastErrno = tErrno;
1787 }
1788 goto end_unlock;
1789 }
1790 lock.l_type = F_UNLCK;
1791 lock.l_whence = SEEK_SET;
1792 lock.l_start = SHARED_FIRST+divSize;
1793 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001794 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001795 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001796 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001797 if( IS_LOCK_ERROR(rc) ){
1798 pFile->lastErrno = tErrno;
1799 }
1800 goto end_unlock;
1801 }
drh30f776f2011-02-25 03:25:07 +00001802 }else
1803#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1804 {
drh7ed97b92010-01-20 13:07:21 +00001805 lock.l_type = F_RDLCK;
1806 lock.l_whence = SEEK_SET;
1807 lock.l_start = SHARED_FIRST;
1808 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001809 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001810 /* In theory, the call to unixFileLock() cannot fail because another
1811 ** process is holding an incompatible lock. If it does, this
1812 ** indicates that the other process is not following the locking
1813 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1814 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1815 ** an assert to fail). */
1816 rc = SQLITE_IOERR_RDLOCK;
1817 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001818 goto end_unlock;
1819 }
drh9c105bb2004-10-02 20:38:28 +00001820 }
1821 }
drhbbd42a62004-05-22 17:41:58 +00001822 lock.l_type = F_UNLCK;
1823 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001824 lock.l_start = PENDING_BYTE;
1825 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001826 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001827 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001828 }else{
danea83bc62011-04-01 11:56:32 +00001829 rc = SQLITE_IOERR_UNLOCK;
1830 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001831 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001832 }
drhbbd42a62004-05-22 17:41:58 +00001833 }
drh308c2a52010-05-14 11:30:18 +00001834 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001835 /* Decrement the shared lock counter. Release the lock using an
1836 ** OS call only when all threads in this same process have released
1837 ** the lock.
1838 */
drh8af6c222010-05-14 12:43:01 +00001839 pInode->nShared--;
1840 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001841 lock.l_type = F_UNLCK;
1842 lock.l_whence = SEEK_SET;
1843 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001844 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001845 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001846 }else{
danea83bc62011-04-01 11:56:32 +00001847 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001848 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001849 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001850 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001851 }
drha6abd042004-06-09 17:37:22 +00001852 }
1853
drhbbd42a62004-05-22 17:41:58 +00001854 /* Decrement the count of locks against this same file. When the
1855 ** count reaches zero, close any other file descriptors whose close
1856 ** was deferred because of outstanding locks.
1857 */
drh8af6c222010-05-14 12:43:01 +00001858 pInode->nLock--;
1859 assert( pInode->nLock>=0 );
1860 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001861 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001862 }
1863 }
drhf2f105d2012-08-20 15:53:54 +00001864
aswift5b1a2562008-08-22 00:22:35 +00001865end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001866 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001867 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001868 return rc;
drhbbd42a62004-05-22 17:41:58 +00001869}
1870
1871/*
drh308c2a52010-05-14 11:30:18 +00001872** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001873** must be either NO_LOCK or SHARED_LOCK.
1874**
1875** If the locking level of the file descriptor is already at or below
1876** the requested locking level, this routine is a no-op.
1877*/
drh308c2a52010-05-14 11:30:18 +00001878static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001879#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001880 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001881#endif
drha7e61d82011-03-12 17:02:57 +00001882 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001883}
1884
mistachkine98844f2013-08-24 00:59:24 +00001885#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001886static int unixMapfile(unixFile *pFd, i64 nByte);
1887static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001888#endif
danf23da962013-03-23 21:00:41 +00001889
drh7ed97b92010-01-20 13:07:21 +00001890/*
danielk1977e339d652008-06-28 11:23:00 +00001891** This function performs the parts of the "close file" operation
1892** common to all locking schemes. It closes the directory and file
1893** handles, if they are valid, and sets all fields of the unixFile
1894** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001895**
1896** It is *not* necessary to hold the mutex when this routine is called,
1897** even on VxWorks. A mutex will be acquired on VxWorks by the
1898** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001899*/
1900static int closeUnixFile(sqlite3_file *id){
1901 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001902#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001903 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001904#endif
dan661d71a2011-03-30 19:08:03 +00001905 if( pFile->h>=0 ){
1906 robust_close(pFile, pFile->h, __LINE__);
1907 pFile->h = -1;
1908 }
1909#if OS_VXWORKS
1910 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001911 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001912 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001913 }
1914 vxworksReleaseFileId(pFile->pId);
1915 pFile->pId = 0;
1916 }
1917#endif
1918 OSTRACE(("CLOSE %-3d\n", pFile->h));
1919 OpenCounter(-1);
1920 sqlite3_free(pFile->pUnused);
1921 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001922 return SQLITE_OK;
1923}
1924
1925/*
danielk1977e3026632004-06-22 11:29:02 +00001926** Close a file.
1927*/
danielk197762079062007-08-15 17:08:46 +00001928static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001929 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001930 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001931 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001932 unixUnlock(id, NO_LOCK);
1933 unixEnterMutex();
1934
1935 /* unixFile.pInode is always valid here. Otherwise, a different close
1936 ** routine (e.g. nolockClose()) would be called instead.
1937 */
1938 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1939 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1940 /* If there are outstanding locks, do not actually close the file just
1941 ** yet because that would clear those locks. Instead, add the file
1942 ** descriptor to pInode->pUnused list. It will be automatically closed
1943 ** when the last lock is cleared.
1944 */
1945 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001946 }
dan661d71a2011-03-30 19:08:03 +00001947 releaseInodeInfo(pFile);
1948 rc = closeUnixFile(id);
1949 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001950 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001951}
1952
drh734c9862008-11-28 15:37:20 +00001953/************** End of the posix advisory lock implementation *****************
1954******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001955
drh734c9862008-11-28 15:37:20 +00001956/******************************************************************************
1957****************************** No-op Locking **********************************
1958**
1959** Of the various locking implementations available, this is by far the
1960** simplest: locking is ignored. No attempt is made to lock the database
1961** file for reading or writing.
1962**
1963** This locking mode is appropriate for use on read-only databases
1964** (ex: databases that are burned into CD-ROM, for example.) It can
1965** also be used if the application employs some external mechanism to
1966** prevent simultaneous access of the same database by two or more
1967** database connections. But there is a serious risk of database
1968** corruption if this locking mode is used in situations where multiple
1969** database connections are accessing the same database file at the same
1970** time and one or more of those connections are writing.
1971*/
drhbfe66312006-10-03 17:40:40 +00001972
drh734c9862008-11-28 15:37:20 +00001973static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1974 UNUSED_PARAMETER(NotUsed);
1975 *pResOut = 0;
1976 return SQLITE_OK;
1977}
drh734c9862008-11-28 15:37:20 +00001978static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1979 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1980 return SQLITE_OK;
1981}
drh734c9862008-11-28 15:37:20 +00001982static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1983 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1984 return SQLITE_OK;
1985}
1986
1987/*
drh9b35ea62008-11-29 02:20:26 +00001988** Close the file.
drh734c9862008-11-28 15:37:20 +00001989*/
1990static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001991 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001992}
1993
1994/******************* End of the no-op lock implementation *********************
1995******************************************************************************/
1996
1997/******************************************************************************
1998************************* Begin dot-file Locking ******************************
1999**
mistachkin48864df2013-03-21 21:20:32 +00002000** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002001** files (really a directory) to control access to the database. This works
2002** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002003**
2004** (1) There is zero concurrency. A single reader blocks all other
2005** connections from reading or writing the database.
2006**
2007** (2) An application crash or power loss can leave stale lock files
2008** sitting around that need to be cleared manually.
2009**
2010** Nevertheless, a dotlock is an appropriate locking mode for use if no
2011** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002012**
drh9ef6bc42011-11-04 02:24:02 +00002013** Dotfile locking works by creating a subdirectory in the same directory as
2014** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002015** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002016** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002017*/
2018
2019/*
2020** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002021** lock directory.
drh734c9862008-11-28 15:37:20 +00002022*/
2023#define DOTLOCK_SUFFIX ".lock"
2024
drh7708e972008-11-29 00:56:52 +00002025/*
2026** This routine checks if there is a RESERVED lock held on the specified
2027** file by this or any other process. If such a lock is held, set *pResOut
2028** to a non-zero value otherwise *pResOut is set to zero. The return value
2029** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2030**
2031** In dotfile locking, either a lock exists or it does not. So in this
2032** variation of CheckReservedLock(), *pResOut is set to true if any lock
2033** is held on the file and false if the file is unlocked.
2034*/
drh734c9862008-11-28 15:37:20 +00002035static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2036 int rc = SQLITE_OK;
2037 int reserved = 0;
2038 unixFile *pFile = (unixFile*)id;
2039
2040 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2041
2042 assert( pFile );
2043
2044 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002045 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002046 /* Either this connection or some other connection in the same process
2047 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002048 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002049 }else{
2050 /* The lock is held if and only if the lockfile exists */
2051 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002052 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002053 }
drh308c2a52010-05-14 11:30:18 +00002054 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002055 *pResOut = reserved;
2056 return rc;
2057}
2058
drh7708e972008-11-29 00:56:52 +00002059/*
drh308c2a52010-05-14 11:30:18 +00002060** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002061** of the following:
2062**
2063** (1) SHARED_LOCK
2064** (2) RESERVED_LOCK
2065** (3) PENDING_LOCK
2066** (4) EXCLUSIVE_LOCK
2067**
2068** Sometimes when requesting one lock state, additional lock states
2069** are inserted in between. The locking might fail on one of the later
2070** transitions leaving the lock state different from what it started but
2071** still short of its goal. The following chart shows the allowed
2072** transitions and the inserted intermediate states:
2073**
2074** UNLOCKED -> SHARED
2075** SHARED -> RESERVED
2076** SHARED -> (PENDING) -> EXCLUSIVE
2077** RESERVED -> (PENDING) -> EXCLUSIVE
2078** PENDING -> EXCLUSIVE
2079**
2080** This routine will only increase a lock. Use the sqlite3OsUnlock()
2081** routine to lower a locking level.
2082**
2083** With dotfile locking, we really only support state (4): EXCLUSIVE.
2084** But we track the other locking levels internally.
2085*/
drh308c2a52010-05-14 11:30:18 +00002086static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002087 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002088 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002089 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002090
drh7708e972008-11-29 00:56:52 +00002091
2092 /* If we have any lock, then the lock file already exists. All we have
2093 ** to do is adjust our internal record of the lock level.
2094 */
drh308c2a52010-05-14 11:30:18 +00002095 if( pFile->eFileLock > NO_LOCK ){
2096 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002097 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002098#ifdef HAVE_UTIME
2099 utime(zLockFile, NULL);
2100#else
drh734c9862008-11-28 15:37:20 +00002101 utimes(zLockFile, NULL);
2102#endif
drh7708e972008-11-29 00:56:52 +00002103 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002104 }
2105
2106 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002107 rc = osMkdir(zLockFile, 0777);
2108 if( rc<0 ){
2109 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002110 int tErrno = errno;
2111 if( EEXIST == tErrno ){
2112 rc = SQLITE_BUSY;
2113 } else {
2114 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2115 if( IS_LOCK_ERROR(rc) ){
2116 pFile->lastErrno = tErrno;
2117 }
2118 }
drh7708e972008-11-29 00:56:52 +00002119 return rc;
drh734c9862008-11-28 15:37:20 +00002120 }
drh734c9862008-11-28 15:37:20 +00002121
2122 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002123 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002124 return rc;
2125}
2126
drh7708e972008-11-29 00:56:52 +00002127/*
drh308c2a52010-05-14 11:30:18 +00002128** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002129** must be either NO_LOCK or SHARED_LOCK.
2130**
2131** If the locking level of the file descriptor is already at or below
2132** the requested locking level, this routine is a no-op.
2133**
2134** When the locking level reaches NO_LOCK, delete the lock file.
2135*/
drh308c2a52010-05-14 11:30:18 +00002136static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002137 unixFile *pFile = (unixFile*)id;
2138 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002139 int rc;
drh734c9862008-11-28 15:37:20 +00002140
2141 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002142 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002143 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002144 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002145
2146 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002147 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002148 return SQLITE_OK;
2149 }
drh7708e972008-11-29 00:56:52 +00002150
2151 /* To downgrade to shared, simply update our internal notion of the
2152 ** lock state. No need to mess with the file on disk.
2153 */
drh308c2a52010-05-14 11:30:18 +00002154 if( eFileLock==SHARED_LOCK ){
2155 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002156 return SQLITE_OK;
2157 }
2158
drh7708e972008-11-29 00:56:52 +00002159 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002160 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002161 rc = osRmdir(zLockFile);
2162 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2163 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002164 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002165 rc = 0;
drh734c9862008-11-28 15:37:20 +00002166 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002167 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002168 }
2169 if( IS_LOCK_ERROR(rc) ){
2170 pFile->lastErrno = tErrno;
2171 }
2172 return rc;
2173 }
drh308c2a52010-05-14 11:30:18 +00002174 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002175 return SQLITE_OK;
2176}
2177
2178/*
drh9b35ea62008-11-29 02:20:26 +00002179** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002180*/
2181static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002182 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002183 if( id ){
2184 unixFile *pFile = (unixFile*)id;
2185 dotlockUnlock(id, NO_LOCK);
2186 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002187 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002188 }
drh734c9862008-11-28 15:37:20 +00002189 return rc;
2190}
2191/****************** End of the dot-file lock implementation *******************
2192******************************************************************************/
2193
2194/******************************************************************************
2195************************** Begin flock Locking ********************************
2196**
2197** Use the flock() system call to do file locking.
2198**
drh6b9d6dd2008-12-03 19:34:47 +00002199** flock() locking is like dot-file locking in that the various
2200** fine-grain locking levels supported by SQLite are collapsed into
2201** a single exclusive lock. In other words, SHARED, RESERVED, and
2202** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2203** still works when you do this, but concurrency is reduced since
2204** only a single process can be reading the database at a time.
2205**
drh734c9862008-11-28 15:37:20 +00002206** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2207** compiling for VXWORKS.
2208*/
2209#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002210
drh6b9d6dd2008-12-03 19:34:47 +00002211/*
drhff812312011-02-23 13:33:46 +00002212** Retry flock() calls that fail with EINTR
2213*/
2214#ifdef EINTR
2215static int robust_flock(int fd, int op){
2216 int rc;
2217 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2218 return rc;
2219}
2220#else
drh5c819272011-02-23 14:00:12 +00002221# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002222#endif
2223
2224
2225/*
drh6b9d6dd2008-12-03 19:34:47 +00002226** This routine checks if there is a RESERVED lock held on the specified
2227** file by this or any other process. If such a lock is held, set *pResOut
2228** to a non-zero value otherwise *pResOut is set to zero. The return value
2229** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2230*/
drh734c9862008-11-28 15:37:20 +00002231static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2232 int rc = SQLITE_OK;
2233 int reserved = 0;
2234 unixFile *pFile = (unixFile*)id;
2235
2236 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2237
2238 assert( pFile );
2239
2240 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002241 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002242 reserved = 1;
2243 }
2244
2245 /* Otherwise see if some other process holds it. */
2246 if( !reserved ){
2247 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002248 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002249 if( !lrc ){
2250 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002251 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002252 if ( lrc ) {
2253 int tErrno = errno;
2254 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002255 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002256 if( IS_LOCK_ERROR(lrc) ){
2257 pFile->lastErrno = tErrno;
2258 rc = lrc;
2259 }
2260 }
2261 } else {
2262 int tErrno = errno;
2263 reserved = 1;
2264 /* someone else might have it reserved */
2265 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2266 if( IS_LOCK_ERROR(lrc) ){
2267 pFile->lastErrno = tErrno;
2268 rc = lrc;
2269 }
2270 }
2271 }
drh308c2a52010-05-14 11:30:18 +00002272 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002273
2274#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2275 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2276 rc = SQLITE_OK;
2277 reserved=1;
2278 }
2279#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2280 *pResOut = reserved;
2281 return rc;
2282}
2283
drh6b9d6dd2008-12-03 19:34:47 +00002284/*
drh308c2a52010-05-14 11:30:18 +00002285** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002286** of the following:
2287**
2288** (1) SHARED_LOCK
2289** (2) RESERVED_LOCK
2290** (3) PENDING_LOCK
2291** (4) EXCLUSIVE_LOCK
2292**
2293** Sometimes when requesting one lock state, additional lock states
2294** are inserted in between. The locking might fail on one of the later
2295** transitions leaving the lock state different from what it started but
2296** still short of its goal. The following chart shows the allowed
2297** transitions and the inserted intermediate states:
2298**
2299** UNLOCKED -> SHARED
2300** SHARED -> RESERVED
2301** SHARED -> (PENDING) -> EXCLUSIVE
2302** RESERVED -> (PENDING) -> EXCLUSIVE
2303** PENDING -> EXCLUSIVE
2304**
2305** flock() only really support EXCLUSIVE locks. We track intermediate
2306** lock states in the sqlite3_file structure, but all locks SHARED or
2307** above are really EXCLUSIVE locks and exclude all other processes from
2308** access the file.
2309**
2310** This routine will only increase a lock. Use the sqlite3OsUnlock()
2311** routine to lower a locking level.
2312*/
drh308c2a52010-05-14 11:30:18 +00002313static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002314 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002315 unixFile *pFile = (unixFile*)id;
2316
2317 assert( pFile );
2318
2319 /* if we already have a lock, it is exclusive.
2320 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002321 if (pFile->eFileLock > NO_LOCK) {
2322 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002323 return SQLITE_OK;
2324 }
2325
2326 /* grab an exclusive lock */
2327
drhff812312011-02-23 13:33:46 +00002328 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002329 int tErrno = errno;
2330 /* didn't get, must be busy */
2331 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2332 if( IS_LOCK_ERROR(rc) ){
2333 pFile->lastErrno = tErrno;
2334 }
2335 } else {
2336 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002337 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002338 }
drh308c2a52010-05-14 11:30:18 +00002339 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2340 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002341#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2342 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2343 rc = SQLITE_BUSY;
2344 }
2345#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2346 return rc;
2347}
2348
drh6b9d6dd2008-12-03 19:34:47 +00002349
2350/*
drh308c2a52010-05-14 11:30:18 +00002351** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002352** must be either NO_LOCK or SHARED_LOCK.
2353**
2354** If the locking level of the file descriptor is already at or below
2355** the requested locking level, this routine is a no-op.
2356*/
drh308c2a52010-05-14 11:30:18 +00002357static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002358 unixFile *pFile = (unixFile*)id;
2359
2360 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002361 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2362 pFile->eFileLock, getpid()));
2363 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002364
2365 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002366 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002367 return SQLITE_OK;
2368 }
2369
2370 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002371 if (eFileLock==SHARED_LOCK) {
2372 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002373 return SQLITE_OK;
2374 }
2375
2376 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002377 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002378#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002379 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002380#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002381 return SQLITE_IOERR_UNLOCK;
2382 }else{
drh308c2a52010-05-14 11:30:18 +00002383 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002384 return SQLITE_OK;
2385 }
2386}
2387
2388/*
2389** Close a file.
2390*/
2391static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002392 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002393 if( id ){
2394 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002395 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002396 }
drh5a05be12012-10-09 18:51:44 +00002397 return rc;
drh734c9862008-11-28 15:37:20 +00002398}
2399
2400#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2401
2402/******************* End of the flock lock implementation *********************
2403******************************************************************************/
2404
2405/******************************************************************************
2406************************ Begin Named Semaphore Locking ************************
2407**
2408** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002409**
2410** Semaphore locking is like dot-lock and flock in that it really only
2411** supports EXCLUSIVE locking. Only a single process can read or write
2412** the database file at a time. This reduces potential concurrency, but
2413** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002414*/
2415#if OS_VXWORKS
2416
drh6b9d6dd2008-12-03 19:34:47 +00002417/*
2418** This routine checks if there is a RESERVED lock held on the specified
2419** file by this or any other process. If such a lock is held, set *pResOut
2420** to a non-zero value otherwise *pResOut is set to zero. The return value
2421** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2422*/
drh734c9862008-11-28 15:37:20 +00002423static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2424 int rc = SQLITE_OK;
2425 int reserved = 0;
2426 unixFile *pFile = (unixFile*)id;
2427
2428 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2429
2430 assert( pFile );
2431
2432 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002433 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002434 reserved = 1;
2435 }
2436
2437 /* Otherwise see if some other process holds it. */
2438 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002439 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002440 struct stat statBuf;
2441
2442 if( sem_trywait(pSem)==-1 ){
2443 int tErrno = errno;
2444 if( EAGAIN != tErrno ){
2445 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2446 pFile->lastErrno = tErrno;
2447 } else {
2448 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002449 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002450 }
2451 }else{
2452 /* we could have it if we want it */
2453 sem_post(pSem);
2454 }
2455 }
drh308c2a52010-05-14 11:30:18 +00002456 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002457
2458 *pResOut = reserved;
2459 return rc;
2460}
2461
drh6b9d6dd2008-12-03 19:34:47 +00002462/*
drh308c2a52010-05-14 11:30:18 +00002463** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002464** of the following:
2465**
2466** (1) SHARED_LOCK
2467** (2) RESERVED_LOCK
2468** (3) PENDING_LOCK
2469** (4) EXCLUSIVE_LOCK
2470**
2471** Sometimes when requesting one lock state, additional lock states
2472** are inserted in between. The locking might fail on one of the later
2473** transitions leaving the lock state different from what it started but
2474** still short of its goal. The following chart shows the allowed
2475** transitions and the inserted intermediate states:
2476**
2477** UNLOCKED -> SHARED
2478** SHARED -> RESERVED
2479** SHARED -> (PENDING) -> EXCLUSIVE
2480** RESERVED -> (PENDING) -> EXCLUSIVE
2481** PENDING -> EXCLUSIVE
2482**
2483** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2484** lock states in the sqlite3_file structure, but all locks SHARED or
2485** above are really EXCLUSIVE locks and exclude all other processes from
2486** access the file.
2487**
2488** This routine will only increase a lock. Use the sqlite3OsUnlock()
2489** routine to lower a locking level.
2490*/
drh308c2a52010-05-14 11:30:18 +00002491static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002492 unixFile *pFile = (unixFile*)id;
2493 int fd;
drh8af6c222010-05-14 12:43:01 +00002494 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002495 int rc = SQLITE_OK;
2496
2497 /* if we already have a lock, it is exclusive.
2498 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002499 if (pFile->eFileLock > NO_LOCK) {
2500 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002501 rc = SQLITE_OK;
2502 goto sem_end_lock;
2503 }
2504
2505 /* lock semaphore now but bail out when already locked. */
2506 if( sem_trywait(pSem)==-1 ){
2507 rc = SQLITE_BUSY;
2508 goto sem_end_lock;
2509 }
2510
2511 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002512 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002513
2514 sem_end_lock:
2515 return rc;
2516}
2517
drh6b9d6dd2008-12-03 19:34:47 +00002518/*
drh308c2a52010-05-14 11:30:18 +00002519** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002520** must be either NO_LOCK or SHARED_LOCK.
2521**
2522** If the locking level of the file descriptor is already at or below
2523** the requested locking level, this routine is a no-op.
2524*/
drh308c2a52010-05-14 11:30:18 +00002525static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002526 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002527 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002528
2529 assert( pFile );
2530 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002531 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002532 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002533 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002534
2535 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002536 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002537 return SQLITE_OK;
2538 }
2539
2540 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002541 if (eFileLock==SHARED_LOCK) {
2542 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002543 return SQLITE_OK;
2544 }
2545
2546 /* no, really unlock. */
2547 if ( sem_post(pSem)==-1 ) {
2548 int rc, tErrno = errno;
2549 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2550 if( IS_LOCK_ERROR(rc) ){
2551 pFile->lastErrno = tErrno;
2552 }
2553 return rc;
2554 }
drh308c2a52010-05-14 11:30:18 +00002555 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002556 return SQLITE_OK;
2557}
2558
2559/*
2560 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002561 */
drh734c9862008-11-28 15:37:20 +00002562static int semClose(sqlite3_file *id) {
2563 if( id ){
2564 unixFile *pFile = (unixFile*)id;
2565 semUnlock(id, NO_LOCK);
2566 assert( pFile );
2567 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002568 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002569 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002570 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002571 }
2572 return SQLITE_OK;
2573}
2574
2575#endif /* OS_VXWORKS */
2576/*
2577** Named semaphore locking is only available on VxWorks.
2578**
2579*************** End of the named semaphore lock implementation ****************
2580******************************************************************************/
2581
2582
2583/******************************************************************************
2584*************************** Begin AFP Locking *********************************
2585**
2586** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2587** on Apple Macintosh computers - both OS9 and OSX.
2588**
2589** Third-party implementations of AFP are available. But this code here
2590** only works on OSX.
2591*/
2592
drhd2cb50b2009-01-09 21:41:17 +00002593#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002594/*
2595** The afpLockingContext structure contains all afp lock specific state
2596*/
drhbfe66312006-10-03 17:40:40 +00002597typedef struct afpLockingContext afpLockingContext;
2598struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002599 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002600 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002601};
2602
2603struct ByteRangeLockPB2
2604{
2605 unsigned long long offset; /* offset to first byte to lock */
2606 unsigned long long length; /* nbr of bytes to lock */
2607 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2608 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2609 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2610 int fd; /* file desc to assoc this lock with */
2611};
2612
drhfd131da2007-08-07 17:13:03 +00002613#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002614
drh6b9d6dd2008-12-03 19:34:47 +00002615/*
2616** This is a utility for setting or clearing a bit-range lock on an
2617** AFP filesystem.
2618**
2619** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2620*/
2621static int afpSetLock(
2622 const char *path, /* Name of the file to be locked or unlocked */
2623 unixFile *pFile, /* Open file descriptor on path */
2624 unsigned long long offset, /* First byte to be locked */
2625 unsigned long long length, /* Number of bytes to lock */
2626 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002627){
drh6b9d6dd2008-12-03 19:34:47 +00002628 struct ByteRangeLockPB2 pb;
2629 int err;
drhbfe66312006-10-03 17:40:40 +00002630
2631 pb.unLockFlag = setLockFlag ? 0 : 1;
2632 pb.startEndFlag = 0;
2633 pb.offset = offset;
2634 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002635 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002636
drh308c2a52010-05-14 11:30:18 +00002637 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002638 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002639 offset, length));
drhbfe66312006-10-03 17:40:40 +00002640 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2641 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002642 int rc;
2643 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002644 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2645 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002646#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2647 rc = SQLITE_BUSY;
2648#else
drh734c9862008-11-28 15:37:20 +00002649 rc = sqliteErrorFromPosixError(tErrno,
2650 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002651#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002652 if( IS_LOCK_ERROR(rc) ){
2653 pFile->lastErrno = tErrno;
2654 }
2655 return rc;
drhbfe66312006-10-03 17:40:40 +00002656 } else {
aswift5b1a2562008-08-22 00:22:35 +00002657 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002658 }
2659}
2660
drh6b9d6dd2008-12-03 19:34:47 +00002661/*
2662** This routine checks if there is a RESERVED lock held on the specified
2663** file by this or any other process. If such a lock is held, set *pResOut
2664** to a non-zero value otherwise *pResOut is set to zero. The return value
2665** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2666*/
danielk1977e339d652008-06-28 11:23:00 +00002667static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002668 int rc = SQLITE_OK;
2669 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002670 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002671 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002672
aswift5b1a2562008-08-22 00:22:35 +00002673 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2674
2675 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002676 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002677 if( context->reserved ){
2678 *pResOut = 1;
2679 return SQLITE_OK;
2680 }
drh8af6c222010-05-14 12:43:01 +00002681 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002682
2683 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002684 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002685 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002686 }
2687
2688 /* Otherwise see if some other process holds it.
2689 */
aswift5b1a2562008-08-22 00:22:35 +00002690 if( !reserved ){
2691 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002692 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002693 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002694 /* if we succeeded in taking the reserved lock, unlock it to restore
2695 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002696 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002697 } else {
2698 /* if we failed to get the lock then someone else must have it */
2699 reserved = 1;
2700 }
2701 if( IS_LOCK_ERROR(lrc) ){
2702 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002703 }
2704 }
drhbfe66312006-10-03 17:40:40 +00002705
drh7ed97b92010-01-20 13:07:21 +00002706 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002707 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002708
2709 *pResOut = reserved;
2710 return rc;
drhbfe66312006-10-03 17:40:40 +00002711}
2712
drh6b9d6dd2008-12-03 19:34:47 +00002713/*
drh308c2a52010-05-14 11:30:18 +00002714** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002715** of the following:
2716**
2717** (1) SHARED_LOCK
2718** (2) RESERVED_LOCK
2719** (3) PENDING_LOCK
2720** (4) EXCLUSIVE_LOCK
2721**
2722** Sometimes when requesting one lock state, additional lock states
2723** are inserted in between. The locking might fail on one of the later
2724** transitions leaving the lock state different from what it started but
2725** still short of its goal. The following chart shows the allowed
2726** transitions and the inserted intermediate states:
2727**
2728** UNLOCKED -> SHARED
2729** SHARED -> RESERVED
2730** SHARED -> (PENDING) -> EXCLUSIVE
2731** RESERVED -> (PENDING) -> EXCLUSIVE
2732** PENDING -> EXCLUSIVE
2733**
2734** This routine will only increase a lock. Use the sqlite3OsUnlock()
2735** routine to lower a locking level.
2736*/
drh308c2a52010-05-14 11:30:18 +00002737static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002738 int rc = SQLITE_OK;
2739 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002740 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002741 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002742
2743 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002744 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2745 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002746 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002747
drhbfe66312006-10-03 17:40:40 +00002748 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002749 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002750 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002751 */
drh308c2a52010-05-14 11:30:18 +00002752 if( pFile->eFileLock>=eFileLock ){
2753 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2754 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002755 return SQLITE_OK;
2756 }
2757
2758 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002759 ** (1) We never move from unlocked to anything higher than shared lock.
2760 ** (2) SQLite never explicitly requests a pendig lock.
2761 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002762 */
drh308c2a52010-05-14 11:30:18 +00002763 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2764 assert( eFileLock!=PENDING_LOCK );
2765 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002766
drh8af6c222010-05-14 12:43:01 +00002767 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002768 */
drh6c7d5c52008-11-21 20:32:33 +00002769 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002770 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002771
2772 /* If some thread using this PID has a lock via a different unixFile*
2773 ** handle that precludes the requested lock, return BUSY.
2774 */
drh8af6c222010-05-14 12:43:01 +00002775 if( (pFile->eFileLock!=pInode->eFileLock &&
2776 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002777 ){
2778 rc = SQLITE_BUSY;
2779 goto afp_end_lock;
2780 }
2781
2782 /* If a SHARED lock is requested, and some thread using this PID already
2783 ** has a SHARED or RESERVED lock, then increment reference counts and
2784 ** return SQLITE_OK.
2785 */
drh308c2a52010-05-14 11:30:18 +00002786 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002787 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002788 assert( eFileLock==SHARED_LOCK );
2789 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002790 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002791 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002792 pInode->nShared++;
2793 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002794 goto afp_end_lock;
2795 }
drhbfe66312006-10-03 17:40:40 +00002796
2797 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002798 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2799 ** be released.
2800 */
drh308c2a52010-05-14 11:30:18 +00002801 if( eFileLock==SHARED_LOCK
2802 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002803 ){
2804 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002805 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002806 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002807 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002808 goto afp_end_lock;
2809 }
2810 }
2811
2812 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002813 ** operating system calls for the specified lock.
2814 */
drh308c2a52010-05-14 11:30:18 +00002815 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002816 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002817 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002818
drh8af6c222010-05-14 12:43:01 +00002819 assert( pInode->nShared==0 );
2820 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002821
2822 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002823 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002824 /* note that the quality of the randomness doesn't matter that much */
2825 lk = random();
drh8af6c222010-05-14 12:43:01 +00002826 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002827 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002828 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002829 if( IS_LOCK_ERROR(lrc1) ){
2830 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002831 }
aswift5b1a2562008-08-22 00:22:35 +00002832 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002833 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002834
aswift5b1a2562008-08-22 00:22:35 +00002835 if( IS_LOCK_ERROR(lrc1) ) {
2836 pFile->lastErrno = lrc1Errno;
2837 rc = lrc1;
2838 goto afp_end_lock;
2839 } else if( IS_LOCK_ERROR(lrc2) ){
2840 rc = lrc2;
2841 goto afp_end_lock;
2842 } else if( lrc1 != SQLITE_OK ) {
2843 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002844 } else {
drh308c2a52010-05-14 11:30:18 +00002845 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002846 pInode->nLock++;
2847 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002848 }
drh8af6c222010-05-14 12:43:01 +00002849 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002850 /* We are trying for an exclusive lock but another thread in this
2851 ** same process is still holding a shared lock. */
2852 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002853 }else{
2854 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2855 ** assumed that there is a SHARED or greater lock on the file
2856 ** already.
2857 */
2858 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002859 assert( 0!=pFile->eFileLock );
2860 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002861 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002862 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002863 if( !failed ){
2864 context->reserved = 1;
2865 }
drhbfe66312006-10-03 17:40:40 +00002866 }
drh308c2a52010-05-14 11:30:18 +00002867 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002868 /* Acquire an EXCLUSIVE lock */
2869
2870 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002871 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002872 */
drh6b9d6dd2008-12-03 19:34:47 +00002873 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002874 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002875 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002876 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002877 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002878 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002879 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002880 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002881 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2882 ** a critical I/O error
2883 */
2884 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2885 SQLITE_IOERR_LOCK;
2886 goto afp_end_lock;
2887 }
2888 }else{
aswift5b1a2562008-08-22 00:22:35 +00002889 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002890 }
2891 }
aswift5b1a2562008-08-22 00:22:35 +00002892 if( failed ){
2893 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002894 }
2895 }
2896
2897 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002898 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002899 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002900 }else if( eFileLock==EXCLUSIVE_LOCK ){
2901 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002902 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002903 }
2904
2905afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002906 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002907 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2908 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002909 return rc;
2910}
2911
2912/*
drh308c2a52010-05-14 11:30:18 +00002913** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002914** must be either NO_LOCK or SHARED_LOCK.
2915**
2916** If the locking level of the file descriptor is already at or below
2917** the requested locking level, this routine is a no-op.
2918*/
drh308c2a52010-05-14 11:30:18 +00002919static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002920 int rc = SQLITE_OK;
2921 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002922 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002923 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2924 int skipShared = 0;
2925#ifdef SQLITE_TEST
2926 int h = pFile->h;
2927#endif
drhbfe66312006-10-03 17:40:40 +00002928
2929 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002930 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002931 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002932 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002933
drh308c2a52010-05-14 11:30:18 +00002934 assert( eFileLock<=SHARED_LOCK );
2935 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002936 return SQLITE_OK;
2937 }
drh6c7d5c52008-11-21 20:32:33 +00002938 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002939 pInode = pFile->pInode;
2940 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002941 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002942 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002943 SimulateIOErrorBenign(1);
2944 SimulateIOError( h=(-1) )
2945 SimulateIOErrorBenign(0);
2946
drhd3d8c042012-05-29 17:02:40 +00002947#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002948 /* When reducing a lock such that other processes can start
2949 ** reading the database file again, make sure that the
2950 ** transaction counter was updated if any part of the database
2951 ** file changed. If the transaction counter is not updated,
2952 ** other connections to the same file might not realize that
2953 ** the file has changed and hence might not know to flush their
2954 ** cache. The use of a stale cache can lead to database corruption.
2955 */
2956 assert( pFile->inNormalWrite==0
2957 || pFile->dbUpdate==0
2958 || pFile->transCntrChng==1 );
2959 pFile->inNormalWrite = 0;
2960#endif
aswiftaebf4132008-11-21 00:10:35 +00002961
drh308c2a52010-05-14 11:30:18 +00002962 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002963 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002964 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002965 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002966 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002967 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2968 } else {
2969 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002970 }
2971 }
drh308c2a52010-05-14 11:30:18 +00002972 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002973 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002974 }
drh308c2a52010-05-14 11:30:18 +00002975 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002976 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2977 if( !rc ){
2978 context->reserved = 0;
2979 }
aswiftaebf4132008-11-21 00:10:35 +00002980 }
drh8af6c222010-05-14 12:43:01 +00002981 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2982 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002983 }
aswiftaebf4132008-11-21 00:10:35 +00002984 }
drh308c2a52010-05-14 11:30:18 +00002985 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002986
drh7ed97b92010-01-20 13:07:21 +00002987 /* Decrement the shared lock counter. Release the lock using an
2988 ** OS call only when all threads in this same process have released
2989 ** the lock.
2990 */
drh8af6c222010-05-14 12:43:01 +00002991 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2992 pInode->nShared--;
2993 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002994 SimulateIOErrorBenign(1);
2995 SimulateIOError( h=(-1) )
2996 SimulateIOErrorBenign(0);
2997 if( !skipShared ){
2998 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2999 }
3000 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003001 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003002 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003003 }
3004 }
3005 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003006 pInode->nLock--;
3007 assert( pInode->nLock>=0 );
3008 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003009 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003010 }
3011 }
drhbfe66312006-10-03 17:40:40 +00003012 }
drh7ed97b92010-01-20 13:07:21 +00003013
drh6c7d5c52008-11-21 20:32:33 +00003014 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003015 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003016 return rc;
3017}
3018
3019/*
drh339eb0b2008-03-07 15:34:11 +00003020** Close a file & cleanup AFP specific locking context
3021*/
danielk1977e339d652008-06-28 11:23:00 +00003022static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003023 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003024 if( id ){
3025 unixFile *pFile = (unixFile*)id;
3026 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003027 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003028 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003029 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003030 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003031 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003032 ** the last lock is cleared.
3033 */
dan08da86a2009-08-21 17:18:03 +00003034 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003035 }
danb0ac3e32010-06-16 10:55:42 +00003036 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003037 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003038 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003039 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003040 }
drh7ed97b92010-01-20 13:07:21 +00003041 return rc;
drhbfe66312006-10-03 17:40:40 +00003042}
3043
drhd2cb50b2009-01-09 21:41:17 +00003044#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003045/*
3046** The code above is the AFP lock implementation. The code is specific
3047** to MacOSX and does not work on other unix platforms. No alternative
3048** is available. If you don't compile for a mac, then the "unix-afp"
3049** VFS is not available.
3050**
3051********************* End of the AFP lock implementation **********************
3052******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003053
drh7ed97b92010-01-20 13:07:21 +00003054/******************************************************************************
3055*************************** Begin NFS Locking ********************************/
3056
3057#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3058/*
drh308c2a52010-05-14 11:30:18 +00003059 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003060 ** must be either NO_LOCK or SHARED_LOCK.
3061 **
3062 ** If the locking level of the file descriptor is already at or below
3063 ** the requested locking level, this routine is a no-op.
3064 */
drh308c2a52010-05-14 11:30:18 +00003065static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003066 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003067}
3068
3069#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3070/*
3071** The code above is the NFS lock implementation. The code is specific
3072** to MacOSX and does not work on other unix platforms. No alternative
3073** is available.
3074**
3075********************* End of the NFS lock implementation **********************
3076******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003077
3078/******************************************************************************
3079**************** Non-locking sqlite3_file methods *****************************
3080**
3081** The next division contains implementations for all methods of the
3082** sqlite3_file object other than the locking methods. The locking
3083** methods were defined in divisions above (one locking method per
3084** division). Those methods that are common to all locking modes
3085** are gather together into this division.
3086*/
drhbfe66312006-10-03 17:40:40 +00003087
3088/*
drh734c9862008-11-28 15:37:20 +00003089** Seek to the offset passed as the second argument, then read cnt
3090** bytes into pBuf. Return the number of bytes actually read.
3091**
3092** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3093** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3094** one system to another. Since SQLite does not define USE_PREAD
3095** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3096** See tickets #2741 and #2681.
3097**
3098** To avoid stomping the errno value on a failed read the lastErrno value
3099** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003100*/
drh734c9862008-11-28 15:37:20 +00003101static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3102 int got;
drh58024642011-11-07 18:16:00 +00003103 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003104#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003105 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003106#endif
drh734c9862008-11-28 15:37:20 +00003107 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003108 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003109 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003110 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003111 do{
drh734c9862008-11-28 15:37:20 +00003112#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003113 got = osPread(id->h, pBuf, cnt, offset);
3114 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003115#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003116 got = osPread64(id->h, pBuf, cnt, offset);
3117 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003118#else
drh58024642011-11-07 18:16:00 +00003119 newOffset = lseek(id->h, offset, SEEK_SET);
3120 SimulateIOError( newOffset-- );
3121 if( newOffset!=offset ){
3122 if( newOffset == -1 ){
3123 ((unixFile*)id)->lastErrno = errno;
3124 }else{
drhf2f105d2012-08-20 15:53:54 +00003125 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003126 }
3127 return -1;
drh734c9862008-11-28 15:37:20 +00003128 }
drh58024642011-11-07 18:16:00 +00003129 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003130#endif
drh58024642011-11-07 18:16:00 +00003131 if( got==cnt ) break;
3132 if( got<0 ){
3133 if( errno==EINTR ){ got = 1; continue; }
3134 prior = 0;
3135 ((unixFile*)id)->lastErrno = errno;
3136 break;
3137 }else if( got>0 ){
3138 cnt -= got;
3139 offset += got;
3140 prior += got;
3141 pBuf = (void*)(got + (char*)pBuf);
3142 }
3143 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003144 TIMER_END;
drh58024642011-11-07 18:16:00 +00003145 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3146 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3147 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003148}
3149
3150/*
drh734c9862008-11-28 15:37:20 +00003151** Read data from a file into a buffer. Return SQLITE_OK if all
3152** bytes were read successfully and SQLITE_IOERR if anything goes
3153** wrong.
drh339eb0b2008-03-07 15:34:11 +00003154*/
drh734c9862008-11-28 15:37:20 +00003155static int unixRead(
3156 sqlite3_file *id,
3157 void *pBuf,
3158 int amt,
3159 sqlite3_int64 offset
3160){
dan08da86a2009-08-21 17:18:03 +00003161 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003162 int got;
3163 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003164 assert( offset>=0 );
3165 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003166
dan08da86a2009-08-21 17:18:03 +00003167 /* If this is a database file (not a journal, master-journal or temp
3168 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003169#if 0
dane946c392009-08-22 11:39:46 +00003170 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003171 || offset>=PENDING_BYTE+512
3172 || offset+amt<=PENDING_BYTE
3173 );
dan7c246102010-04-12 19:00:29 +00003174#endif
drh08c6d442009-02-09 17:34:07 +00003175
drh9b4c59f2013-04-15 17:03:42 +00003176#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003177 /* Deal with as much of this read request as possible by transfering
3178 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003179 if( offset<pFile->mmapSize ){
3180 if( offset+amt <= pFile->mmapSize ){
3181 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3182 return SQLITE_OK;
3183 }else{
3184 int nCopy = pFile->mmapSize - offset;
3185 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3186 pBuf = &((u8 *)pBuf)[nCopy];
3187 amt -= nCopy;
3188 offset += nCopy;
3189 }
3190 }
drh6e0b6d52013-04-09 16:19:20 +00003191#endif
danf23da962013-03-23 21:00:41 +00003192
dan08da86a2009-08-21 17:18:03 +00003193 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003194 if( got==amt ){
3195 return SQLITE_OK;
3196 }else if( got<0 ){
3197 /* lastErrno set by seekAndRead */
3198 return SQLITE_IOERR_READ;
3199 }else{
dan08da86a2009-08-21 17:18:03 +00003200 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003201 /* Unread parts of the buffer must be zero-filled */
3202 memset(&((char*)pBuf)[got], 0, amt-got);
3203 return SQLITE_IOERR_SHORT_READ;
3204 }
3205}
3206
3207/*
dan47a2b4a2013-04-26 16:09:29 +00003208** Attempt to seek the file-descriptor passed as the first argument to
3209** absolute offset iOff, then attempt to write nBuf bytes of data from
3210** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3211** return the actual number of bytes written (which may be less than
3212** nBuf).
3213*/
3214static int seekAndWriteFd(
3215 int fd, /* File descriptor to write to */
3216 i64 iOff, /* File offset to begin writing at */
3217 const void *pBuf, /* Copy data from this buffer to the file */
3218 int nBuf, /* Size of buffer pBuf in bytes */
3219 int *piErrno /* OUT: Error number if error occurs */
3220){
3221 int rc = 0; /* Value returned by system call */
3222
3223 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003224 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003225 nBuf &= 0x1ffff;
3226 TIMER_START;
3227
3228#if defined(USE_PREAD)
3229 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3230#elif defined(USE_PREAD64)
3231 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3232#else
3233 do{
3234 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3235 SimulateIOError( iSeek-- );
3236
3237 if( iSeek!=iOff ){
3238 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3239 return -1;
3240 }
3241 rc = osWrite(fd, pBuf, nBuf);
3242 }while( rc<0 && errno==EINTR );
3243#endif
3244
3245 TIMER_END;
3246 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3247
3248 if( rc<0 && piErrno ) *piErrno = errno;
3249 return rc;
3250}
3251
3252
3253/*
drh734c9862008-11-28 15:37:20 +00003254** Seek to the offset in id->offset then read cnt bytes into pBuf.
3255** Return the number of bytes actually read. Update the offset.
3256**
3257** To avoid stomping the errno value on a failed write the lastErrno value
3258** is set before returning.
3259*/
3260static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003261 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003262}
3263
3264
3265/*
3266** Write data from a buffer into a file. Return SQLITE_OK on success
3267** or some other error code on failure.
3268*/
3269static int unixWrite(
3270 sqlite3_file *id,
3271 const void *pBuf,
3272 int amt,
3273 sqlite3_int64 offset
3274){
dan08da86a2009-08-21 17:18:03 +00003275 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003276 int wrote = 0;
3277 assert( id );
3278 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003279
dan08da86a2009-08-21 17:18:03 +00003280 /* If this is a database file (not a journal, master-journal or temp
3281 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003282#if 0
dane946c392009-08-22 11:39:46 +00003283 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003284 || offset>=PENDING_BYTE+512
3285 || offset+amt<=PENDING_BYTE
3286 );
dan7c246102010-04-12 19:00:29 +00003287#endif
drh08c6d442009-02-09 17:34:07 +00003288
drhd3d8c042012-05-29 17:02:40 +00003289#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003290 /* If we are doing a normal write to a database file (as opposed to
3291 ** doing a hot-journal rollback or a write to some file other than a
3292 ** normal database file) then record the fact that the database
3293 ** has changed. If the transaction counter is modified, record that
3294 ** fact too.
3295 */
dan08da86a2009-08-21 17:18:03 +00003296 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003297 pFile->dbUpdate = 1; /* The database has been modified */
3298 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003299 int rc;
drh8f941bc2009-01-14 23:03:40 +00003300 char oldCntr[4];
3301 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003302 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003303 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003304 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003305 pFile->transCntrChng = 1; /* The transaction counter has changed */
3306 }
3307 }
3308 }
3309#endif
3310
drh9b4c59f2013-04-15 17:03:42 +00003311#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003312 /* Deal with as much of this write request as possible by transfering
3313 ** data from the memory mapping using memcpy(). */
3314 if( offset<pFile->mmapSize ){
3315 if( offset+amt <= pFile->mmapSize ){
3316 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3317 return SQLITE_OK;
3318 }else{
3319 int nCopy = pFile->mmapSize - offset;
3320 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3321 pBuf = &((u8 *)pBuf)[nCopy];
3322 amt -= nCopy;
3323 offset += nCopy;
3324 }
3325 }
drh6e0b6d52013-04-09 16:19:20 +00003326#endif
danf23da962013-03-23 21:00:41 +00003327
dan08da86a2009-08-21 17:18:03 +00003328 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003329 amt -= wrote;
3330 offset += wrote;
3331 pBuf = &((char*)pBuf)[wrote];
3332 }
3333 SimulateIOError(( wrote=(-1), amt=1 ));
3334 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003335
drh734c9862008-11-28 15:37:20 +00003336 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003337 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003338 /* lastErrno set by seekAndWrite */
3339 return SQLITE_IOERR_WRITE;
3340 }else{
dan08da86a2009-08-21 17:18:03 +00003341 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003342 return SQLITE_FULL;
3343 }
3344 }
dan6e09d692010-07-27 18:34:15 +00003345
drh734c9862008-11-28 15:37:20 +00003346 return SQLITE_OK;
3347}
3348
3349#ifdef SQLITE_TEST
3350/*
3351** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003352** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003353*/
3354int sqlite3_sync_count = 0;
3355int sqlite3_fullsync_count = 0;
3356#endif
3357
3358/*
drh89240432009-03-25 01:06:01 +00003359** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003360** Others do no. To be safe, we will stick with the (slightly slower)
3361** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003362** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003363*/
drh20f8e132011-08-31 21:01:55 +00003364#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003365# define fdatasync fsync
3366#endif
3367
3368/*
3369** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3370** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3371** only available on Mac OS X. But that could change.
3372*/
3373#ifdef F_FULLFSYNC
3374# define HAVE_FULLFSYNC 1
3375#else
3376# define HAVE_FULLFSYNC 0
3377#endif
3378
3379
3380/*
3381** The fsync() system call does not work as advertised on many
3382** unix systems. The following procedure is an attempt to make
3383** it work better.
3384**
3385** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3386** for testing when we want to run through the test suite quickly.
3387** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3388** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3389** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003390**
3391** SQLite sets the dataOnly flag if the size of the file is unchanged.
3392** The idea behind dataOnly is that it should only write the file content
3393** to disk, not the inode. We only set dataOnly if the file size is
3394** unchanged since the file size is part of the inode. However,
3395** Ted Ts'o tells us that fdatasync() will also write the inode if the
3396** file size has changed. The only real difference between fdatasync()
3397** and fsync(), Ted tells us, is that fdatasync() will not flush the
3398** inode if the mtime or owner or other inode attributes have changed.
3399** We only care about the file size, not the other file attributes, so
3400** as far as SQLite is concerned, an fdatasync() is always adequate.
3401** So, we always use fdatasync() if it is available, regardless of
3402** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003403*/
3404static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003405 int rc;
drh734c9862008-11-28 15:37:20 +00003406
3407 /* The following "ifdef/elif/else/" block has the same structure as
3408 ** the one below. It is replicated here solely to avoid cluttering
3409 ** up the real code with the UNUSED_PARAMETER() macros.
3410 */
3411#ifdef SQLITE_NO_SYNC
3412 UNUSED_PARAMETER(fd);
3413 UNUSED_PARAMETER(fullSync);
3414 UNUSED_PARAMETER(dataOnly);
3415#elif HAVE_FULLFSYNC
3416 UNUSED_PARAMETER(dataOnly);
3417#else
3418 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003419 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003420#endif
3421
3422 /* Record the number of times that we do a normal fsync() and
3423 ** FULLSYNC. This is used during testing to verify that this procedure
3424 ** gets called with the correct arguments.
3425 */
3426#ifdef SQLITE_TEST
3427 if( fullSync ) sqlite3_fullsync_count++;
3428 sqlite3_sync_count++;
3429#endif
3430
3431 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3432 ** no-op
3433 */
3434#ifdef SQLITE_NO_SYNC
3435 rc = SQLITE_OK;
3436#elif HAVE_FULLFSYNC
3437 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003438 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003439 }else{
3440 rc = 1;
3441 }
3442 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003443 ** It shouldn't be possible for fullfsync to fail on the local
3444 ** file system (on OSX), so failure indicates that FULLFSYNC
3445 ** isn't supported for this file system. So, attempt an fsync
3446 ** and (for now) ignore the overhead of a superfluous fcntl call.
3447 ** It'd be better to detect fullfsync support once and avoid
3448 ** the fcntl call every time sync is called.
3449 */
drh734c9862008-11-28 15:37:20 +00003450 if( rc ) rc = fsync(fd);
3451
drh7ed97b92010-01-20 13:07:21 +00003452#elif defined(__APPLE__)
3453 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3454 ** so currently we default to the macro that redefines fdatasync to fsync
3455 */
3456 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003457#else
drh0b647ff2009-03-21 14:41:04 +00003458 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003459#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003460 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003461 rc = fsync(fd);
3462 }
drh0b647ff2009-03-21 14:41:04 +00003463#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003464#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3465
3466 if( OS_VXWORKS && rc!= -1 ){
3467 rc = 0;
3468 }
chw97185482008-11-17 08:05:31 +00003469 return rc;
drhbfe66312006-10-03 17:40:40 +00003470}
3471
drh734c9862008-11-28 15:37:20 +00003472/*
drh0059eae2011-08-08 23:48:40 +00003473** Open a file descriptor to the directory containing file zFilename.
3474** If successful, *pFd is set to the opened file descriptor and
3475** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3476** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3477** value.
3478**
drh90315a22011-08-10 01:52:12 +00003479** The directory file descriptor is used for only one thing - to
3480** fsync() a directory to make sure file creation and deletion events
3481** are flushed to disk. Such fsyncs are not needed on newer
3482** journaling filesystems, but are required on older filesystems.
3483**
3484** This routine can be overridden using the xSetSysCall interface.
3485** The ability to override this routine was added in support of the
3486** chromium sandbox. Opening a directory is a security risk (we are
3487** told) so making it overrideable allows the chromium sandbox to
3488** replace this routine with a harmless no-op. To make this routine
3489** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3490** *pFd set to a negative number.
3491**
drh0059eae2011-08-08 23:48:40 +00003492** If SQLITE_OK is returned, the caller is responsible for closing
3493** the file descriptor *pFd using close().
3494*/
3495static int openDirectory(const char *zFilename, int *pFd){
3496 int ii;
3497 int fd = -1;
3498 char zDirname[MAX_PATHNAME+1];
3499
3500 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3501 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3502 if( ii>0 ){
3503 zDirname[ii] = '\0';
3504 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3505 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003506 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3507 }
3508 }
3509 *pFd = fd;
3510 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3511}
3512
3513/*
drh734c9862008-11-28 15:37:20 +00003514** Make sure all writes to a particular file are committed to disk.
3515**
3516** If dataOnly==0 then both the file itself and its metadata (file
3517** size, access time, etc) are synced. If dataOnly!=0 then only the
3518** file data is synced.
3519**
3520** Under Unix, also make sure that the directory entry for the file
3521** has been created by fsync-ing the directory that contains the file.
3522** If we do not do this and we encounter a power failure, the directory
3523** entry for the journal might not exist after we reboot. The next
3524** SQLite to access the file will not know that the journal exists (because
3525** the directory entry for the journal was never created) and the transaction
3526** will not roll back - possibly leading to database corruption.
3527*/
3528static int unixSync(sqlite3_file *id, int flags){
3529 int rc;
3530 unixFile *pFile = (unixFile*)id;
3531
3532 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3533 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3534
3535 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3536 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3537 || (flags&0x0F)==SQLITE_SYNC_FULL
3538 );
3539
3540 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3541 ** line is to test that doing so does not cause any problems.
3542 */
3543 SimulateDiskfullError( return SQLITE_FULL );
3544
3545 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003546 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003547 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3548 SimulateIOError( rc=1 );
3549 if( rc ){
3550 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003551 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003552 }
drh0059eae2011-08-08 23:48:40 +00003553
3554 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003555 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003556 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003557 */
3558 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3559 int dirfd;
3560 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003561 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003562 rc = osOpenDirectory(pFile->zPath, &dirfd);
3563 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003564 full_fsync(dirfd, 0, 0);
3565 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003566 }else if( rc==SQLITE_CANTOPEN ){
3567 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003568 }
drh0059eae2011-08-08 23:48:40 +00003569 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003570 }
3571 return rc;
3572}
3573
3574/*
3575** Truncate an open file to a specified size
3576*/
3577static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003578 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003579 int rc;
dan6e09d692010-07-27 18:34:15 +00003580 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003581 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003582
3583 /* If the user has configured a chunk-size for this file, truncate the
3584 ** file so that it consists of an integer number of chunks (i.e. the
3585 ** actual file size after the operation may be larger than the requested
3586 ** size).
3587 */
drhb8af4b72012-04-05 20:04:39 +00003588 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003589 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3590 }
3591
drhff812312011-02-23 13:33:46 +00003592 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003593 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003594 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003595 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003596 }else{
drhd3d8c042012-05-29 17:02:40 +00003597#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003598 /* If we are doing a normal write to a database file (as opposed to
3599 ** doing a hot-journal rollback or a write to some file other than a
3600 ** normal database file) and we truncate the file to zero length,
3601 ** that effectively updates the change counter. This might happen
3602 ** when restoring a database using the backup API from a zero-length
3603 ** source.
3604 */
dan6e09d692010-07-27 18:34:15 +00003605 if( pFile->inNormalWrite && nByte==0 ){
3606 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003607 }
danf23da962013-03-23 21:00:41 +00003608#endif
danc0003312013-03-22 17:46:11 +00003609
mistachkine98844f2013-08-24 00:59:24 +00003610#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003611 /* If the file was just truncated to a size smaller than the currently
3612 ** mapped region, reduce the effective mapping size as well. SQLite will
3613 ** use read() and write() to access data beyond this point from now on.
3614 */
3615 if( nByte<pFile->mmapSize ){
3616 pFile->mmapSize = nByte;
3617 }
mistachkine98844f2013-08-24 00:59:24 +00003618#endif
drh3313b142009-11-06 04:13:18 +00003619
drh734c9862008-11-28 15:37:20 +00003620 return SQLITE_OK;
3621 }
3622}
3623
3624/*
3625** Determine the current size of a file in bytes
3626*/
3627static int unixFileSize(sqlite3_file *id, i64 *pSize){
3628 int rc;
3629 struct stat buf;
3630 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003631 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003632 SimulateIOError( rc=1 );
3633 if( rc!=0 ){
3634 ((unixFile*)id)->lastErrno = errno;
3635 return SQLITE_IOERR_FSTAT;
3636 }
3637 *pSize = buf.st_size;
3638
drh8af6c222010-05-14 12:43:01 +00003639 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003640 ** writes a single byte into that file in order to work around a bug
3641 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3642 ** layers, we need to report this file size as zero even though it is
3643 ** really 1. Ticket #3260.
3644 */
3645 if( *pSize==1 ) *pSize = 0;
3646
3647
3648 return SQLITE_OK;
3649}
3650
drhd2cb50b2009-01-09 21:41:17 +00003651#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003652/*
3653** Handler for proxy-locking file-control verbs. Defined below in the
3654** proxying locking division.
3655*/
3656static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003657#endif
drh715ff302008-12-03 22:32:44 +00003658
dan502019c2010-07-28 14:26:17 +00003659/*
3660** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003661** file-control operation. Enlarge the database to nBytes in size
3662** (rounded up to the next chunk-size). If the database is already
3663** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003664*/
3665static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003666 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003667 i64 nSize; /* Required file size */
3668 struct stat buf; /* Used to hold return values of fstat() */
3669
drh99ab3b12011-03-02 15:09:07 +00003670 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003671
3672 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3673 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003674
dan502019c2010-07-28 14:26:17 +00003675#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003676 /* The code below is handling the return value of osFallocate()
3677 ** correctly. posix_fallocate() is defined to "returns zero on success,
3678 ** or an error number on failure". See the manpage for details. */
3679 int err;
drhff812312011-02-23 13:33:46 +00003680 do{
dan661d71a2011-03-30 19:08:03 +00003681 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3682 }while( err==EINTR );
3683 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003684#else
3685 /* If the OS does not have posix_fallocate(), fake it. First use
3686 ** ftruncate() to set the file size, then write a single byte to
3687 ** the last byte in each block within the extended region. This
3688 ** is the same technique used by glibc to implement posix_fallocate()
3689 ** on systems that do not have a real fallocate() system call.
3690 */
3691 int nBlk = buf.st_blksize; /* File-system block size */
3692 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003693
drhff812312011-02-23 13:33:46 +00003694 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003695 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003696 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003697 }
3698 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003699 while( iWrite<nSize ){
3700 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3701 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003702 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003703 }
dan502019c2010-07-28 14:26:17 +00003704#endif
3705 }
3706 }
3707
mistachkine98844f2013-08-24 00:59:24 +00003708#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003709 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003710 int rc;
3711 if( pFile->szChunk<=0 ){
3712 if( robust_ftruncate(pFile->h, nByte) ){
3713 pFile->lastErrno = errno;
3714 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3715 }
3716 }
3717
3718 rc = unixMapfile(pFile, nByte);
3719 return rc;
3720 }
mistachkine98844f2013-08-24 00:59:24 +00003721#endif
danf23da962013-03-23 21:00:41 +00003722
dan502019c2010-07-28 14:26:17 +00003723 return SQLITE_OK;
3724}
danielk1977ad94b582007-08-20 06:44:22 +00003725
danielk1977e3026632004-06-22 11:29:02 +00003726/*
drhf12b3f62011-12-21 14:42:29 +00003727** If *pArg is inititially negative then this is a query. Set *pArg to
3728** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3729**
3730** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3731*/
3732static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3733 if( *pArg<0 ){
3734 *pArg = (pFile->ctrlFlags & mask)!=0;
3735 }else if( (*pArg)==0 ){
3736 pFile->ctrlFlags &= ~mask;
3737 }else{
3738 pFile->ctrlFlags |= mask;
3739 }
3740}
3741
drh696b33e2012-12-06 19:01:42 +00003742/* Forward declaration */
3743static int unixGetTempname(int nBuf, char *zBuf);
3744
drhf12b3f62011-12-21 14:42:29 +00003745/*
drh9e33c2c2007-08-31 18:34:59 +00003746** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003747*/
drhcc6bb3e2007-08-31 16:11:35 +00003748static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003749 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003750 switch( op ){
3751 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003752 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003753 return SQLITE_OK;
3754 }
drh7708e972008-11-29 00:56:52 +00003755 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003756 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003757 return SQLITE_OK;
3758 }
dan6e09d692010-07-27 18:34:15 +00003759 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003760 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003761 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003762 }
drh9ff27ec2010-05-19 19:26:05 +00003763 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003764 int rc;
3765 SimulateIOErrorBenign(1);
3766 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3767 SimulateIOErrorBenign(0);
3768 return rc;
drhf0b190d2011-07-26 16:03:07 +00003769 }
3770 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003771 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3772 return SQLITE_OK;
3773 }
drhcb15f352011-12-23 01:04:17 +00003774 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3775 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003776 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003777 }
drhde60fc22011-12-14 17:53:36 +00003778 case SQLITE_FCNTL_VFSNAME: {
3779 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3780 return SQLITE_OK;
3781 }
drh696b33e2012-12-06 19:01:42 +00003782 case SQLITE_FCNTL_TEMPFILENAME: {
3783 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3784 if( zTFile ){
3785 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3786 *(char**)pArg = zTFile;
3787 }
3788 return SQLITE_OK;
3789 }
drhb959a012013-12-07 12:29:22 +00003790 case SQLITE_FCNTL_HAS_MOVED: {
3791 *(int*)pArg = fileHasMoved(pFile);
3792 return SQLITE_OK;
3793 }
mistachkine98844f2013-08-24 00:59:24 +00003794#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003795 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003796 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003797 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003798 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3799 newLimit = sqlite3GlobalConfig.mxMmap;
3800 }
3801 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003802 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003803 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003804 if( pFile->mmapSize>0 ){
3805 unixUnmapfile(pFile);
3806 rc = unixMapfile(pFile, -1);
3807 }
danbcb8a862013-04-08 15:30:41 +00003808 }
drh34e258c2013-05-23 01:40:53 +00003809 return rc;
danb2d3de32013-03-14 18:34:37 +00003810 }
mistachkine98844f2013-08-24 00:59:24 +00003811#endif
drhd3d8c042012-05-29 17:02:40 +00003812#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003813 /* The pager calls this method to signal that it has done
3814 ** a rollback and that the database is therefore unchanged and
3815 ** it hence it is OK for the transaction change counter to be
3816 ** unchanged.
3817 */
3818 case SQLITE_FCNTL_DB_UNCHANGED: {
3819 ((unixFile*)id)->dbUpdate = 0;
3820 return SQLITE_OK;
3821 }
3822#endif
drhd2cb50b2009-01-09 21:41:17 +00003823#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003824 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003825 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003826 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003827 }
drhd2cb50b2009-01-09 21:41:17 +00003828#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003829 }
drh0b52b7d2011-01-26 19:46:22 +00003830 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003831}
3832
3833/*
danielk1977a3d4c882007-03-23 10:08:38 +00003834** Return the sector size in bytes of the underlying block device for
3835** the specified file. This is almost always 512 bytes, but may be
3836** larger for some devices.
3837**
3838** SQLite code assumes this function cannot fail. It also assumes that
3839** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003840** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003841** same for both.
3842*/
drh537dddf2012-10-26 13:46:24 +00003843#ifndef __QNXNTO__
3844static int unixSectorSize(sqlite3_file *NotUsed){
3845 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003846 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003847}
drh537dddf2012-10-26 13:46:24 +00003848#endif
3849
3850/*
3851** The following version of unixSectorSize() is optimized for QNX.
3852*/
3853#ifdef __QNXNTO__
3854#include <sys/dcmd_blk.h>
3855#include <sys/statvfs.h>
3856static int unixSectorSize(sqlite3_file *id){
3857 unixFile *pFile = (unixFile*)id;
3858 if( pFile->sectorSize == 0 ){
3859 struct statvfs fsInfo;
3860
3861 /* Set defaults for non-supported filesystems */
3862 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3863 pFile->deviceCharacteristics = 0;
3864 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3865 return pFile->sectorSize;
3866 }
3867
3868 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3869 pFile->sectorSize = fsInfo.f_bsize;
3870 pFile->deviceCharacteristics =
3871 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3872 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3873 ** the write succeeds */
3874 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3875 ** so it is ordered */
3876 0;
3877 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3878 pFile->sectorSize = fsInfo.f_bsize;
3879 pFile->deviceCharacteristics =
3880 /* etfs cluster size writes are atomic */
3881 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3882 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3883 ** the write succeeds */
3884 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3885 ** so it is ordered */
3886 0;
3887 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3888 pFile->sectorSize = fsInfo.f_bsize;
3889 pFile->deviceCharacteristics =
3890 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3891 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3892 ** the write succeeds */
3893 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3894 ** so it is ordered */
3895 0;
3896 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3897 pFile->sectorSize = fsInfo.f_bsize;
3898 pFile->deviceCharacteristics =
3899 /* full bitset of atomics from max sector size and smaller */
3900 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3901 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3902 ** so it is ordered */
3903 0;
3904 }else if( strstr(fsInfo.f_basetype, "dos") ){
3905 pFile->sectorSize = fsInfo.f_bsize;
3906 pFile->deviceCharacteristics =
3907 /* full bitset of atomics from max sector size and smaller */
3908 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3909 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3910 ** so it is ordered */
3911 0;
3912 }else{
3913 pFile->deviceCharacteristics =
3914 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3915 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3916 ** the write succeeds */
3917 0;
3918 }
3919 }
3920 /* Last chance verification. If the sector size isn't a multiple of 512
3921 ** then it isn't valid.*/
3922 if( pFile->sectorSize % 512 != 0 ){
3923 pFile->deviceCharacteristics = 0;
3924 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3925 }
3926 return pFile->sectorSize;
3927}
3928#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003929
danielk197790949c22007-08-17 16:50:38 +00003930/*
drhf12b3f62011-12-21 14:42:29 +00003931** Return the device characteristics for the file.
3932**
drhcb15f352011-12-23 01:04:17 +00003933** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3934** However, that choice is contraversial since technically the underlying
3935** file system does not always provide powersafe overwrites. (In other
3936** words, after a power-loss event, parts of the file that were never
3937** written might end up being altered.) However, non-PSOW behavior is very,
3938** very rare. And asserting PSOW makes a large reduction in the amount
3939** of required I/O for journaling, since a lot of padding is eliminated.
3940** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3941** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003942*/
drhf12b3f62011-12-21 14:42:29 +00003943static int unixDeviceCharacteristics(sqlite3_file *id){
3944 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003945 int rc = 0;
3946#ifdef __QNXNTO__
3947 if( p->sectorSize==0 ) unixSectorSize(id);
3948 rc = p->deviceCharacteristics;
3949#endif
drhcb15f352011-12-23 01:04:17 +00003950 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003951 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003952 }
drh537dddf2012-10-26 13:46:24 +00003953 return rc;
danielk197762079062007-08-15 17:08:46 +00003954}
3955
drhd9e5c4f2010-05-12 18:01:39 +00003956#ifndef SQLITE_OMIT_WAL
3957
3958
3959/*
drhd91c68f2010-05-14 14:52:25 +00003960** Object used to represent an shared memory buffer.
3961**
3962** When multiple threads all reference the same wal-index, each thread
3963** has its own unixShm object, but they all point to a single instance
3964** of this unixShmNode object. In other words, each wal-index is opened
3965** only once per process.
3966**
3967** Each unixShmNode object is connected to a single unixInodeInfo object.
3968** We could coalesce this object into unixInodeInfo, but that would mean
3969** every open file that does not use shared memory (in other words, most
3970** open files) would have to carry around this extra information. So
3971** the unixInodeInfo object contains a pointer to this unixShmNode object
3972** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003973**
3974** unixMutexHeld() must be true when creating or destroying
3975** this object or while reading or writing the following fields:
3976**
3977** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003978**
3979** The following fields are read-only after the object is created:
3980**
3981** fid
3982** zFilename
3983**
drhd91c68f2010-05-14 14:52:25 +00003984** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003985** unixMutexHeld() is true when reading or writing any other field
3986** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003987*/
drhd91c68f2010-05-14 14:52:25 +00003988struct unixShmNode {
3989 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003990 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003991 char *zFilename; /* Name of the mmapped file */
3992 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003993 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003994 u16 nRegion; /* Size of array apRegion */
3995 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003996 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003997 int nRef; /* Number of unixShm objects pointing to this */
3998 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003999#ifdef SQLITE_DEBUG
4000 u8 exclMask; /* Mask of exclusive locks held */
4001 u8 sharedMask; /* Mask of shared locks held */
4002 u8 nextShmId; /* Next available unixShm.id value */
4003#endif
4004};
4005
4006/*
drhd9e5c4f2010-05-12 18:01:39 +00004007** Structure used internally by this VFS to record the state of an
4008** open shared memory connection.
4009**
drhd91c68f2010-05-14 14:52:25 +00004010** The following fields are initialized when this object is created and
4011** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004012**
drhd91c68f2010-05-14 14:52:25 +00004013** unixShm.pFile
4014** unixShm.id
4015**
4016** All other fields are read/write. The unixShm.pFile->mutex must be held
4017** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004018*/
4019struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004020 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4021 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004022 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004023 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004024 u16 sharedMask; /* Mask of shared locks held */
4025 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004026};
4027
4028/*
drhd9e5c4f2010-05-12 18:01:39 +00004029** Constants used for locking
4030*/
drhbd9676c2010-06-23 17:58:38 +00004031#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004032#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004033
drhd9e5c4f2010-05-12 18:01:39 +00004034/*
drh73b64e42010-05-30 19:55:15 +00004035** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004036**
4037** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4038** otherwise.
4039*/
4040static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004041 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4042 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004043 int ofst, /* First byte of the locking range */
4044 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004045){
4046 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004047 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004048
drhd91c68f2010-05-14 14:52:25 +00004049 /* Access to the unixShmNode object is serialized by the caller */
4050 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004051
drh73b64e42010-05-30 19:55:15 +00004052 /* Shared locks never span more than one byte */
4053 assert( n==1 || lockType!=F_RDLCK );
4054
4055 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004056 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004057
drh3cb93392011-03-12 18:10:44 +00004058 if( pShmNode->h>=0 ){
4059 /* Initialize the locking parameters */
4060 memset(&f, 0, sizeof(f));
4061 f.l_type = lockType;
4062 f.l_whence = SEEK_SET;
4063 f.l_start = ofst;
4064 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004065
drh3cb93392011-03-12 18:10:44 +00004066 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4067 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4068 }
drhd9e5c4f2010-05-12 18:01:39 +00004069
4070 /* Update the global lock state and do debug tracing */
4071#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004072 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004073 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004074 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004075 if( rc==SQLITE_OK ){
4076 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004077 OSTRACE(("unlock %d ok", ofst));
4078 pShmNode->exclMask &= ~mask;
4079 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004080 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004081 OSTRACE(("read-lock %d ok", ofst));
4082 pShmNode->exclMask &= ~mask;
4083 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004084 }else{
4085 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004086 OSTRACE(("write-lock %d ok", ofst));
4087 pShmNode->exclMask |= mask;
4088 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004089 }
4090 }else{
4091 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004092 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004093 }else if( lockType==F_RDLCK ){
4094 OSTRACE(("read-lock failed"));
4095 }else{
4096 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004097 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004098 }
4099 }
drh20e1f082010-05-31 16:10:12 +00004100 OSTRACE((" - afterwards %03x,%03x\n",
4101 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004102 }
drhd9e5c4f2010-05-12 18:01:39 +00004103#endif
4104
4105 return rc;
4106}
4107
dan781e34c2014-03-20 08:59:47 +00004108/*
4109** Return the system page size.
4110*/
4111static int unixGetPagesize(void){
4112#if defined(_BSD_SOURCE)
4113 return getpagesize();
4114#else
4115 return (int)sysconf(_SC_PAGESIZE);
4116#endif
4117}
4118
4119/*
4120** Return the minimum number of 32KB shm regions that should be mapped at
4121** a time, assuming that each mapping must be an integer multiple of the
4122** current system page-size.
4123**
4124** Usually, this is 1. The exception seems to be systems that are configured
4125** to use 64KB pages - in this case each mapping must cover at least two
4126** shm regions.
4127*/
4128static int unixShmRegionPerMap(void){
4129 int shmsz = 32*1024; /* SHM region size */
4130 int pgsz = unixGetPagesize(); /* System page size */
4131 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4132 if( pgsz<shmsz ) return 1;
4133 return pgsz/shmsz;
4134}
drhd9e5c4f2010-05-12 18:01:39 +00004135
4136/*
drhd91c68f2010-05-14 14:52:25 +00004137** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004138**
4139** This is not a VFS shared-memory method; it is a utility function called
4140** by VFS shared-memory methods.
4141*/
drhd91c68f2010-05-14 14:52:25 +00004142static void unixShmPurge(unixFile *pFd){
4143 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004144 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004145 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004146 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004147 int i;
drhd91c68f2010-05-14 14:52:25 +00004148 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004149 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004150 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004151 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004152 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004153 }else{
4154 sqlite3_free(p->apRegion[i]);
4155 }
dan13a3cb82010-06-11 19:04:21 +00004156 }
dan18801912010-06-14 14:07:50 +00004157 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004158 if( p->h>=0 ){
4159 robust_close(pFd, p->h, __LINE__);
4160 p->h = -1;
4161 }
drhd91c68f2010-05-14 14:52:25 +00004162 p->pInode->pShmNode = 0;
4163 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004164 }
4165}
4166
4167/*
danda9fe0c2010-07-13 18:44:03 +00004168** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004169** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004170**
drh7234c6d2010-06-19 15:10:09 +00004171** The file used to implement shared-memory is in the same directory
4172** as the open database file and has the same name as the open database
4173** file with the "-shm" suffix added. For example, if the database file
4174** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004175** for shared memory will be called "/home/user1/config.db-shm".
4176**
4177** Another approach to is to use files in /dev/shm or /dev/tmp or an
4178** some other tmpfs mount. But if a file in a different directory
4179** from the database file is used, then differing access permissions
4180** or a chroot() might cause two different processes on the same
4181** database to end up using different files for shared memory -
4182** meaning that their memory would not really be shared - resulting
4183** in database corruption. Nevertheless, this tmpfs file usage
4184** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4185** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4186** option results in an incompatible build of SQLite; builds of SQLite
4187** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4188** same database file at the same time, database corruption will likely
4189** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4190** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004191**
4192** When opening a new shared-memory file, if no other instances of that
4193** file are currently open, in this process or in other processes, then
4194** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004195**
4196** If the original database file (pDbFd) is using the "unix-excl" VFS
4197** that means that an exclusive lock is held on the database file and
4198** that no other processes are able to read or write the database. In
4199** that case, we do not really need shared memory. No shared memory
4200** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004201*/
danda9fe0c2010-07-13 18:44:03 +00004202static int unixOpenSharedMemory(unixFile *pDbFd){
4203 struct unixShm *p = 0; /* The connection to be opened */
4204 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4205 int rc; /* Result code */
4206 unixInodeInfo *pInode; /* The inode of fd */
4207 char *zShmFilename; /* Name of the file used for SHM */
4208 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004209
danda9fe0c2010-07-13 18:44:03 +00004210 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004211 p = sqlite3_malloc( sizeof(*p) );
4212 if( p==0 ) return SQLITE_NOMEM;
4213 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004214 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004215
danda9fe0c2010-07-13 18:44:03 +00004216 /* Check to see if a unixShmNode object already exists. Reuse an existing
4217 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004218 */
4219 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004220 pInode = pDbFd->pInode;
4221 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004222 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004223 struct stat sStat; /* fstat() info for database file */
4224
4225 /* Call fstat() to figure out the permissions on the database file. If
4226 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004227 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004228 */
drh3cb93392011-03-12 18:10:44 +00004229 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004230 rc = SQLITE_IOERR_FSTAT;
4231 goto shm_open_err;
4232 }
4233
drha4ced192010-07-15 18:32:40 +00004234#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004235 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004236#else
drh52bcde02012-01-03 14:50:45 +00004237 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004238#endif
drh7234c6d2010-06-19 15:10:09 +00004239 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004240 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004241 rc = SQLITE_NOMEM;
4242 goto shm_open_err;
4243 }
drh9cb5a0d2012-01-05 21:19:54 +00004244 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004245 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004246#ifdef SQLITE_SHM_DIRECTORY
4247 sqlite3_snprintf(nShmFilename, zShmFilename,
4248 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4249 (u32)sStat.st_ino, (u32)sStat.st_dev);
4250#else
drh7234c6d2010-06-19 15:10:09 +00004251 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004252 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004253#endif
drhd91c68f2010-05-14 14:52:25 +00004254 pShmNode->h = -1;
4255 pDbFd->pInode->pShmNode = pShmNode;
4256 pShmNode->pInode = pDbFd->pInode;
4257 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4258 if( pShmNode->mutex==0 ){
4259 rc = SQLITE_NOMEM;
4260 goto shm_open_err;
4261 }
drhd9e5c4f2010-05-12 18:01:39 +00004262
drh3cb93392011-03-12 18:10:44 +00004263 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004264 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004265 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004266 openFlags = O_RDONLY;
4267 pShmNode->isReadonly = 1;
4268 }
4269 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004270 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004271 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4272 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004273 }
drhac7c3ac2012-02-11 19:23:48 +00004274
4275 /* If this process is running as root, make sure that the SHM file
4276 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004277 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004278 */
drhed466822012-05-31 13:10:49 +00004279 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004280
4281 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004282 ** If not, truncate the file to zero length.
4283 */
4284 rc = SQLITE_OK;
4285 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4286 if( robust_ftruncate(pShmNode->h, 0) ){
4287 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004288 }
4289 }
drh66dfec8b2011-06-01 20:01:49 +00004290 if( rc==SQLITE_OK ){
4291 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4292 }
4293 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004294 }
drhd9e5c4f2010-05-12 18:01:39 +00004295 }
4296
drhd91c68f2010-05-14 14:52:25 +00004297 /* Make the new connection a child of the unixShmNode */
4298 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004299#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004300 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004301#endif
drhd91c68f2010-05-14 14:52:25 +00004302 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004303 pDbFd->pShm = p;
4304 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004305
4306 /* The reference count on pShmNode has already been incremented under
4307 ** the cover of the unixEnterMutex() mutex and the pointer from the
4308 ** new (struct unixShm) object to the pShmNode has been set. All that is
4309 ** left to do is to link the new object into the linked list starting
4310 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4311 ** mutex.
4312 */
4313 sqlite3_mutex_enter(pShmNode->mutex);
4314 p->pNext = pShmNode->pFirst;
4315 pShmNode->pFirst = p;
4316 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004317 return SQLITE_OK;
4318
4319 /* Jump here on any error */
4320shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004321 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004322 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004323 unixLeaveMutex();
4324 return rc;
4325}
4326
4327/*
danda9fe0c2010-07-13 18:44:03 +00004328** This function is called to obtain a pointer to region iRegion of the
4329** shared-memory associated with the database file fd. Shared-memory regions
4330** are numbered starting from zero. Each shared-memory region is szRegion
4331** bytes in size.
4332**
4333** If an error occurs, an error code is returned and *pp is set to NULL.
4334**
4335** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4336** region has not been allocated (by any client, including one running in a
4337** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4338** bExtend is non-zero and the requested shared-memory region has not yet
4339** been allocated, it is allocated by this function.
4340**
4341** If the shared-memory region has already been allocated or is allocated by
4342** this call as described above, then it is mapped into this processes
4343** address space (if it is not already), *pp is set to point to the mapped
4344** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004345*/
danda9fe0c2010-07-13 18:44:03 +00004346static int unixShmMap(
4347 sqlite3_file *fd, /* Handle open on database file */
4348 int iRegion, /* Region to retrieve */
4349 int szRegion, /* Size of regions */
4350 int bExtend, /* True to extend file if necessary */
4351 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004352){
danda9fe0c2010-07-13 18:44:03 +00004353 unixFile *pDbFd = (unixFile*)fd;
4354 unixShm *p;
4355 unixShmNode *pShmNode;
4356 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004357 int nShmPerMap = unixShmRegionPerMap();
4358 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004359
danda9fe0c2010-07-13 18:44:03 +00004360 /* If the shared-memory file has not yet been opened, open it now. */
4361 if( pDbFd->pShm==0 ){
4362 rc = unixOpenSharedMemory(pDbFd);
4363 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004364 }
drhd9e5c4f2010-05-12 18:01:39 +00004365
danda9fe0c2010-07-13 18:44:03 +00004366 p = pDbFd->pShm;
4367 pShmNode = p->pShmNode;
4368 sqlite3_mutex_enter(pShmNode->mutex);
4369 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004370 assert( pShmNode->pInode==pDbFd->pInode );
4371 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4372 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004373
dan781e34c2014-03-20 08:59:47 +00004374 /* Minimum number of regions required to be mapped. */
4375 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4376
4377 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004378 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004379 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004380 struct stat sStat; /* Used by fstat() */
4381
4382 pShmNode->szRegion = szRegion;
4383
drh3cb93392011-03-12 18:10:44 +00004384 if( pShmNode->h>=0 ){
4385 /* The requested region is not mapped into this processes address space.
4386 ** Check to see if it has been allocated (i.e. if the wal-index file is
4387 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004388 */
drh3cb93392011-03-12 18:10:44 +00004389 if( osFstat(pShmNode->h, &sStat) ){
4390 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004391 goto shmpage_out;
4392 }
drh3cb93392011-03-12 18:10:44 +00004393
4394 if( sStat.st_size<nByte ){
4395 /* The requested memory region does not exist. If bExtend is set to
4396 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004397 */
dan47a2b4a2013-04-26 16:09:29 +00004398 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004399 goto shmpage_out;
4400 }
dan47a2b4a2013-04-26 16:09:29 +00004401
4402 /* Alternatively, if bExtend is true, extend the file. Do this by
4403 ** writing a single byte to the end of each (OS) page being
4404 ** allocated or extended. Technically, we need only write to the
4405 ** last page in order to extend the file. But writing to all new
4406 ** pages forces the OS to allocate them immediately, which reduces
4407 ** the chances of SIGBUS while accessing the mapped region later on.
4408 */
4409 else{
4410 static const int pgsz = 4096;
4411 int iPg;
4412
4413 /* Write to the last byte of each newly allocated or extended page */
4414 assert( (nByte % pgsz)==0 );
4415 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4416 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4417 const char *zFile = pShmNode->zFilename;
4418 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4419 goto shmpage_out;
4420 }
4421 }
drh3cb93392011-03-12 18:10:44 +00004422 }
4423 }
danda9fe0c2010-07-13 18:44:03 +00004424 }
4425
4426 /* Map the requested memory region into this processes address space. */
4427 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004428 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004429 );
4430 if( !apNew ){
4431 rc = SQLITE_IOERR_NOMEM;
4432 goto shmpage_out;
4433 }
4434 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004435 while( pShmNode->nRegion<nReqRegion ){
4436 int nMap = szRegion*nShmPerMap;
4437 int i;
drh3cb93392011-03-12 18:10:44 +00004438 void *pMem;
4439 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004440 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004441 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004442 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004443 );
4444 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004445 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004446 goto shmpage_out;
4447 }
4448 }else{
4449 pMem = sqlite3_malloc(szRegion);
4450 if( pMem==0 ){
4451 rc = SQLITE_NOMEM;
4452 goto shmpage_out;
4453 }
4454 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004455 }
dan781e34c2014-03-20 08:59:47 +00004456
4457 for(i=0; i<nShmPerMap; i++){
4458 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4459 }
4460 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004461 }
4462 }
4463
4464shmpage_out:
4465 if( pShmNode->nRegion>iRegion ){
4466 *pp = pShmNode->apRegion[iRegion];
4467 }else{
4468 *pp = 0;
4469 }
drh66dfec8b2011-06-01 20:01:49 +00004470 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004471 sqlite3_mutex_leave(pShmNode->mutex);
4472 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004473}
4474
4475/*
drhd9e5c4f2010-05-12 18:01:39 +00004476** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004477**
4478** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4479** different here than in posix. In xShmLock(), one can go from unlocked
4480** to shared and back or from unlocked to exclusive and back. But one may
4481** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004482*/
4483static int unixShmLock(
4484 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004485 int ofst, /* First lock to acquire or release */
4486 int n, /* Number of locks to acquire or release */
4487 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004488){
drh73b64e42010-05-30 19:55:15 +00004489 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4490 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4491 unixShm *pX; /* For looping over all siblings */
4492 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4493 int rc = SQLITE_OK; /* Result code */
4494 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004495
drhd91c68f2010-05-14 14:52:25 +00004496 assert( pShmNode==pDbFd->pInode->pShmNode );
4497 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004498 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004499 assert( n>=1 );
4500 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4501 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4502 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4503 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4504 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004505 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4506 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004507
drhc99597c2010-05-31 01:41:15 +00004508 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004509 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004510 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004511 if( flags & SQLITE_SHM_UNLOCK ){
4512 u16 allMask = 0; /* Mask of locks held by siblings */
4513
4514 /* See if any siblings hold this same lock */
4515 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4516 if( pX==p ) continue;
4517 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4518 allMask |= pX->sharedMask;
4519 }
4520
4521 /* Unlock the system-level locks */
4522 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004523 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004524 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004525 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004526 }
drh73b64e42010-05-30 19:55:15 +00004527
4528 /* Undo the local locks */
4529 if( rc==SQLITE_OK ){
4530 p->exclMask &= ~mask;
4531 p->sharedMask &= ~mask;
4532 }
4533 }else if( flags & SQLITE_SHM_SHARED ){
4534 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4535
4536 /* Find out which shared locks are already held by sibling connections.
4537 ** If any sibling already holds an exclusive lock, go ahead and return
4538 ** SQLITE_BUSY.
4539 */
4540 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004541 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004542 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004543 break;
4544 }
4545 allShared |= pX->sharedMask;
4546 }
4547
4548 /* Get shared locks at the system level, if necessary */
4549 if( rc==SQLITE_OK ){
4550 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004551 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004552 }else{
drh73b64e42010-05-30 19:55:15 +00004553 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004554 }
drhd9e5c4f2010-05-12 18:01:39 +00004555 }
drh73b64e42010-05-30 19:55:15 +00004556
4557 /* Get the local shared locks */
4558 if( rc==SQLITE_OK ){
4559 p->sharedMask |= mask;
4560 }
4561 }else{
4562 /* Make sure no sibling connections hold locks that will block this
4563 ** lock. If any do, return SQLITE_BUSY right away.
4564 */
4565 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004566 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4567 rc = SQLITE_BUSY;
4568 break;
4569 }
4570 }
4571
4572 /* Get the exclusive locks at the system level. Then if successful
4573 ** also mark the local connection as being locked.
4574 */
4575 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004576 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004577 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004578 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004579 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004580 }
drhd9e5c4f2010-05-12 18:01:39 +00004581 }
4582 }
drhd91c68f2010-05-14 14:52:25 +00004583 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004584 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4585 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004586 return rc;
4587}
4588
drh286a2882010-05-20 23:51:06 +00004589/*
4590** Implement a memory barrier or memory fence on shared memory.
4591**
4592** All loads and stores begun before the barrier must complete before
4593** any load or store begun after the barrier.
4594*/
4595static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004596 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004597){
drhff828942010-06-26 21:34:06 +00004598 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004599 unixEnterMutex();
4600 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004601}
4602
dan18801912010-06-14 14:07:50 +00004603/*
danda9fe0c2010-07-13 18:44:03 +00004604** Close a connection to shared-memory. Delete the underlying
4605** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004606**
4607** If there is no shared memory associated with the connection then this
4608** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004609*/
danda9fe0c2010-07-13 18:44:03 +00004610static int unixShmUnmap(
4611 sqlite3_file *fd, /* The underlying database file */
4612 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004613){
danda9fe0c2010-07-13 18:44:03 +00004614 unixShm *p; /* The connection to be closed */
4615 unixShmNode *pShmNode; /* The underlying shared-memory file */
4616 unixShm **pp; /* For looping over sibling connections */
4617 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004618
danda9fe0c2010-07-13 18:44:03 +00004619 pDbFd = (unixFile*)fd;
4620 p = pDbFd->pShm;
4621 if( p==0 ) return SQLITE_OK;
4622 pShmNode = p->pShmNode;
4623
4624 assert( pShmNode==pDbFd->pInode->pShmNode );
4625 assert( pShmNode->pInode==pDbFd->pInode );
4626
4627 /* Remove connection p from the set of connections associated
4628 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004629 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004630 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4631 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004632
danda9fe0c2010-07-13 18:44:03 +00004633 /* Free the connection p */
4634 sqlite3_free(p);
4635 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004636 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004637
4638 /* If pShmNode->nRef has reached 0, then close the underlying
4639 ** shared-memory file, too */
4640 unixEnterMutex();
4641 assert( pShmNode->nRef>0 );
4642 pShmNode->nRef--;
4643 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004644 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004645 unixShmPurge(pDbFd);
4646 }
4647 unixLeaveMutex();
4648
4649 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004650}
drh286a2882010-05-20 23:51:06 +00004651
danda9fe0c2010-07-13 18:44:03 +00004652
drhd9e5c4f2010-05-12 18:01:39 +00004653#else
drh6b017cc2010-06-14 18:01:46 +00004654# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004655# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004656# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004657# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004658#endif /* #ifndef SQLITE_OMIT_WAL */
4659
mistachkine98844f2013-08-24 00:59:24 +00004660#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004661/*
danaef49d72013-03-25 16:28:54 +00004662** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004663*/
danf23da962013-03-23 21:00:41 +00004664static void unixUnmapfile(unixFile *pFd){
4665 assert( pFd->nFetchOut==0 );
4666 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004667 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004668 pFd->pMapRegion = 0;
4669 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004670 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004671 }
4672}
dan5d8a1372013-03-19 19:28:06 +00004673
danaef49d72013-03-25 16:28:54 +00004674/*
dane6ecd662013-04-01 17:56:59 +00004675** Attempt to set the size of the memory mapping maintained by file
4676** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4677**
4678** If successful, this function sets the following variables:
4679**
4680** unixFile.pMapRegion
4681** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004682** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004683**
4684** If unsuccessful, an error message is logged via sqlite3_log() and
4685** the three variables above are zeroed. In this case SQLite should
4686** continue accessing the database using the xRead() and xWrite()
4687** methods.
4688*/
4689static void unixRemapfile(
4690 unixFile *pFd, /* File descriptor object */
4691 i64 nNew /* Required mapping size */
4692){
dan4ff7bc42013-04-02 12:04:09 +00004693 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004694 int h = pFd->h; /* File descriptor open on db file */
4695 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004696 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004697 u8 *pNew = 0; /* Location of new mapping */
4698 int flags = PROT_READ; /* Flags to pass to mmap() */
4699
4700 assert( pFd->nFetchOut==0 );
4701 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004702 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004703 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004704 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004705 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004706
4707 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4708
4709 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004710#if HAVE_MREMAP
4711 i64 nReuse = pFd->mmapSize;
4712#else
dane6ecd662013-04-01 17:56:59 +00004713 const int szSyspage = unixGetPagesize();
4714 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004715#endif
dane6ecd662013-04-01 17:56:59 +00004716 u8 *pReq = &pOrig[nReuse];
4717
4718 /* Unmap any pages of the existing mapping that cannot be reused. */
4719 if( nReuse!=nOrig ){
4720 osMunmap(pReq, nOrig-nReuse);
4721 }
4722
4723#if HAVE_MREMAP
4724 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004725 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004726#else
4727 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4728 if( pNew!=MAP_FAILED ){
4729 if( pNew!=pReq ){
4730 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004731 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004732 }else{
4733 pNew = pOrig;
4734 }
4735 }
4736#endif
4737
dan48ccef82013-04-02 20:55:01 +00004738 /* The attempt to extend the existing mapping failed. Free it. */
4739 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004740 osMunmap(pOrig, nReuse);
4741 }
4742 }
4743
4744 /* If pNew is still NULL, try to create an entirely new mapping. */
4745 if( pNew==0 ){
4746 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004747 }
4748
dan4ff7bc42013-04-02 12:04:09 +00004749 if( pNew==MAP_FAILED ){
4750 pNew = 0;
4751 nNew = 0;
4752 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4753
4754 /* If the mmap() above failed, assume that all subsequent mmap() calls
4755 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4756 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004757 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004758 }
dane6ecd662013-04-01 17:56:59 +00004759 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004760 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004761}
4762
4763/*
danaef49d72013-03-25 16:28:54 +00004764** Memory map or remap the file opened by file-descriptor pFd (if the file
4765** is already mapped, the existing mapping is replaced by the new). Or, if
4766** there already exists a mapping for this file, and there are still
4767** outstanding xFetch() references to it, this function is a no-op.
4768**
4769** If parameter nByte is non-negative, then it is the requested size of
4770** the mapping to create. Otherwise, if nByte is less than zero, then the
4771** requested size is the size of the file on disk. The actual size of the
4772** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004773** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004774**
4775** SQLITE_OK is returned if no error occurs (even if the mapping is not
4776** recreated as a result of outstanding references) or an SQLite error
4777** code otherwise.
4778*/
danf23da962013-03-23 21:00:41 +00004779static int unixMapfile(unixFile *pFd, i64 nByte){
4780 i64 nMap = nByte;
4781 int rc;
daneb97b292013-03-20 14:26:59 +00004782
danf23da962013-03-23 21:00:41 +00004783 assert( nMap>=0 || pFd->nFetchOut==0 );
4784 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4785
4786 if( nMap<0 ){
daneb97b292013-03-20 14:26:59 +00004787 struct stat statbuf; /* Low-level file information */
danf23da962013-03-23 21:00:41 +00004788 rc = osFstat(pFd->h, &statbuf);
4789 if( rc!=SQLITE_OK ){
4790 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004791 }
danf23da962013-03-23 21:00:41 +00004792 nMap = statbuf.st_size;
4793 }
drh9b4c59f2013-04-15 17:03:42 +00004794 if( nMap>pFd->mmapSizeMax ){
4795 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004796 }
4797
danf23da962013-03-23 21:00:41 +00004798 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004799 if( nMap>0 ){
4800 unixRemapfile(pFd, nMap);
4801 }else{
danb7e3a322013-03-25 20:30:13 +00004802 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004803 }
4804 }
4805
danf23da962013-03-23 21:00:41 +00004806 return SQLITE_OK;
4807}
mistachkine98844f2013-08-24 00:59:24 +00004808#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004809
danaef49d72013-03-25 16:28:54 +00004810/*
4811** If possible, return a pointer to a mapping of file fd starting at offset
4812** iOff. The mapping must be valid for at least nAmt bytes.
4813**
4814** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4815** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4816** Finally, if an error does occur, return an SQLite error code. The final
4817** value of *pp is undefined in this case.
4818**
4819** If this function does return a pointer, the caller must eventually
4820** release the reference by calling unixUnfetch().
4821*/
danf23da962013-03-23 21:00:41 +00004822static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004823#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004824 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004825#endif
danf23da962013-03-23 21:00:41 +00004826 *pp = 0;
4827
drh9b4c59f2013-04-15 17:03:42 +00004828#if SQLITE_MAX_MMAP_SIZE>0
4829 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004830 if( pFd->pMapRegion==0 ){
4831 int rc = unixMapfile(pFd, -1);
4832 if( rc!=SQLITE_OK ) return rc;
4833 }
4834 if( pFd->mmapSize >= iOff+nAmt ){
4835 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4836 pFd->nFetchOut++;
4837 }
4838 }
drh6e0b6d52013-04-09 16:19:20 +00004839#endif
danf23da962013-03-23 21:00:41 +00004840 return SQLITE_OK;
4841}
4842
danaef49d72013-03-25 16:28:54 +00004843/*
dandf737fe2013-03-25 17:00:24 +00004844** If the third argument is non-NULL, then this function releases a
4845** reference obtained by an earlier call to unixFetch(). The second
4846** argument passed to this function must be the same as the corresponding
4847** argument that was passed to the unixFetch() invocation.
4848**
4849** Or, if the third argument is NULL, then this function is being called
4850** to inform the VFS layer that, according to POSIX, any existing mapping
4851** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004852*/
dandf737fe2013-03-25 17:00:24 +00004853static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004854#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004855 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004856 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004857
danaef49d72013-03-25 16:28:54 +00004858 /* If p==0 (unmap the entire file) then there must be no outstanding
4859 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4860 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004861 assert( (p==0)==(pFd->nFetchOut==0) );
4862
dandf737fe2013-03-25 17:00:24 +00004863 /* If p!=0, it must match the iOff value. */
4864 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4865
danf23da962013-03-23 21:00:41 +00004866 if( p ){
4867 pFd->nFetchOut--;
4868 }else{
4869 unixUnmapfile(pFd);
4870 }
4871
4872 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004873#else
4874 UNUSED_PARAMETER(fd);
4875 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004876 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004877#endif
danf23da962013-03-23 21:00:41 +00004878 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004879}
4880
4881/*
drh734c9862008-11-28 15:37:20 +00004882** Here ends the implementation of all sqlite3_file methods.
4883**
4884********************** End sqlite3_file Methods *******************************
4885******************************************************************************/
4886
4887/*
drh6b9d6dd2008-12-03 19:34:47 +00004888** This division contains definitions of sqlite3_io_methods objects that
4889** implement various file locking strategies. It also contains definitions
4890** of "finder" functions. A finder-function is used to locate the appropriate
4891** sqlite3_io_methods object for a particular database file. The pAppData
4892** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4893** the correct finder-function for that VFS.
4894**
4895** Most finder functions return a pointer to a fixed sqlite3_io_methods
4896** object. The only interesting finder-function is autolockIoFinder, which
4897** looks at the filesystem type and tries to guess the best locking
4898** strategy from that.
4899**
drh1875f7a2008-12-08 18:19:17 +00004900** For finder-funtion F, two objects are created:
4901**
4902** (1) The real finder-function named "FImpt()".
4903**
dane946c392009-08-22 11:39:46 +00004904** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004905**
4906**
4907** A pointer to the F pointer is used as the pAppData value for VFS
4908** objects. We have to do this instead of letting pAppData point
4909** directly at the finder-function since C90 rules prevent a void*
4910** from be cast into a function pointer.
4911**
drh6b9d6dd2008-12-03 19:34:47 +00004912**
drh7708e972008-11-29 00:56:52 +00004913** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004914**
drh7708e972008-11-29 00:56:52 +00004915** * A constant sqlite3_io_methods object call METHOD that has locking
4916** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4917**
4918** * An I/O method finder function called FINDER that returns a pointer
4919** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004920*/
drhd9e5c4f2010-05-12 18:01:39 +00004921#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004922static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004923 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004924 CLOSE, /* xClose */ \
4925 unixRead, /* xRead */ \
4926 unixWrite, /* xWrite */ \
4927 unixTruncate, /* xTruncate */ \
4928 unixSync, /* xSync */ \
4929 unixFileSize, /* xFileSize */ \
4930 LOCK, /* xLock */ \
4931 UNLOCK, /* xUnlock */ \
4932 CKLOCK, /* xCheckReservedLock */ \
4933 unixFileControl, /* xFileControl */ \
4934 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004935 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004936 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004937 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004938 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004939 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004940 unixFetch, /* xFetch */ \
4941 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004942}; \
drh0c2694b2009-09-03 16:23:44 +00004943static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4944 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004945 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004946} \
drh0c2694b2009-09-03 16:23:44 +00004947static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004948 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004949
4950/*
4951** Here are all of the sqlite3_io_methods objects for each of the
4952** locking strategies. Functions that return pointers to these methods
4953** are also created.
4954*/
4955IOMETHODS(
4956 posixIoFinder, /* Finder function name */
4957 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004958 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004959 unixClose, /* xClose method */
4960 unixLock, /* xLock method */
4961 unixUnlock, /* xUnlock method */
4962 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004963)
drh7708e972008-11-29 00:56:52 +00004964IOMETHODS(
4965 nolockIoFinder, /* Finder function name */
4966 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004967 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004968 nolockClose, /* xClose method */
4969 nolockLock, /* xLock method */
4970 nolockUnlock, /* xUnlock method */
4971 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004972)
drh7708e972008-11-29 00:56:52 +00004973IOMETHODS(
4974 dotlockIoFinder, /* Finder function name */
4975 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004976 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004977 dotlockClose, /* xClose method */
4978 dotlockLock, /* xLock method */
4979 dotlockUnlock, /* xUnlock method */
4980 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004981)
drh7708e972008-11-29 00:56:52 +00004982
chw78a13182009-04-07 05:35:03 +00004983#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004984IOMETHODS(
4985 flockIoFinder, /* Finder function name */
4986 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004987 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004988 flockClose, /* xClose method */
4989 flockLock, /* xLock method */
4990 flockUnlock, /* xUnlock method */
4991 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004992)
drh7708e972008-11-29 00:56:52 +00004993#endif
4994
drh6c7d5c52008-11-21 20:32:33 +00004995#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004996IOMETHODS(
4997 semIoFinder, /* Finder function name */
4998 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004999 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005000 semClose, /* xClose method */
5001 semLock, /* xLock method */
5002 semUnlock, /* xUnlock method */
5003 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005004)
aswiftaebf4132008-11-21 00:10:35 +00005005#endif
drh7708e972008-11-29 00:56:52 +00005006
drhd2cb50b2009-01-09 21:41:17 +00005007#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005008IOMETHODS(
5009 afpIoFinder, /* Finder function name */
5010 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005011 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005012 afpClose, /* xClose method */
5013 afpLock, /* xLock method */
5014 afpUnlock, /* xUnlock method */
5015 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005016)
drh715ff302008-12-03 22:32:44 +00005017#endif
5018
5019/*
5020** The proxy locking method is a "super-method" in the sense that it
5021** opens secondary file descriptors for the conch and lock files and
5022** it uses proxy, dot-file, AFP, and flock() locking methods on those
5023** secondary files. For this reason, the division that implements
5024** proxy locking is located much further down in the file. But we need
5025** to go ahead and define the sqlite3_io_methods and finder function
5026** for proxy locking here. So we forward declare the I/O methods.
5027*/
drhd2cb50b2009-01-09 21:41:17 +00005028#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005029static int proxyClose(sqlite3_file*);
5030static int proxyLock(sqlite3_file*, int);
5031static int proxyUnlock(sqlite3_file*, int);
5032static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005033IOMETHODS(
5034 proxyIoFinder, /* Finder function name */
5035 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005036 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005037 proxyClose, /* xClose method */
5038 proxyLock, /* xLock method */
5039 proxyUnlock, /* xUnlock method */
5040 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005041)
aswiftaebf4132008-11-21 00:10:35 +00005042#endif
drh7708e972008-11-29 00:56:52 +00005043
drh7ed97b92010-01-20 13:07:21 +00005044/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5045#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5046IOMETHODS(
5047 nfsIoFinder, /* Finder function name */
5048 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005049 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005050 unixClose, /* xClose method */
5051 unixLock, /* xLock method */
5052 nfsUnlock, /* xUnlock method */
5053 unixCheckReservedLock /* xCheckReservedLock method */
5054)
5055#endif
drh7708e972008-11-29 00:56:52 +00005056
drhd2cb50b2009-01-09 21:41:17 +00005057#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005058/*
drh6b9d6dd2008-12-03 19:34:47 +00005059** This "finder" function attempts to determine the best locking strategy
5060** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005061** object that implements that strategy.
5062**
5063** This is for MacOSX only.
5064*/
drh1875f7a2008-12-08 18:19:17 +00005065static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005066 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005067 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005068){
5069 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005070 const char *zFilesystem; /* Filesystem type name */
5071 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005072 } aMap[] = {
5073 { "hfs", &posixIoMethods },
5074 { "ufs", &posixIoMethods },
5075 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005076 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005077 { "webdav", &nolockIoMethods },
5078 { 0, 0 }
5079 };
5080 int i;
5081 struct statfs fsInfo;
5082 struct flock lockInfo;
5083
5084 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005085 /* If filePath==NULL that means we are dealing with a transient file
5086 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005087 return &nolockIoMethods;
5088 }
5089 if( statfs(filePath, &fsInfo) != -1 ){
5090 if( fsInfo.f_flags & MNT_RDONLY ){
5091 return &nolockIoMethods;
5092 }
5093 for(i=0; aMap[i].zFilesystem; i++){
5094 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5095 return aMap[i].pMethods;
5096 }
5097 }
5098 }
5099
5100 /* Default case. Handles, amongst others, "nfs".
5101 ** Test byte-range lock using fcntl(). If the call succeeds,
5102 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005103 */
drh7708e972008-11-29 00:56:52 +00005104 lockInfo.l_len = 1;
5105 lockInfo.l_start = 0;
5106 lockInfo.l_whence = SEEK_SET;
5107 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005108 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005109 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5110 return &nfsIoMethods;
5111 } else {
5112 return &posixIoMethods;
5113 }
drh7708e972008-11-29 00:56:52 +00005114 }else{
5115 return &dotlockIoMethods;
5116 }
5117}
drh0c2694b2009-09-03 16:23:44 +00005118static const sqlite3_io_methods
5119 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005120
drhd2cb50b2009-01-09 21:41:17 +00005121#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005122
chw78a13182009-04-07 05:35:03 +00005123#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5124/*
5125** This "finder" function attempts to determine the best locking strategy
5126** for the database file "filePath". It then returns the sqlite3_io_methods
5127** object that implements that strategy.
5128**
5129** This is for VXWorks only.
5130*/
5131static const sqlite3_io_methods *autolockIoFinderImpl(
5132 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005133 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005134){
5135 struct flock lockInfo;
5136
5137 if( !filePath ){
5138 /* If filePath==NULL that means we are dealing with a transient file
5139 ** that does not need to be locked. */
5140 return &nolockIoMethods;
5141 }
5142
5143 /* Test if fcntl() is supported and use POSIX style locks.
5144 ** Otherwise fall back to the named semaphore method.
5145 */
5146 lockInfo.l_len = 1;
5147 lockInfo.l_start = 0;
5148 lockInfo.l_whence = SEEK_SET;
5149 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005150 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005151 return &posixIoMethods;
5152 }else{
5153 return &semIoMethods;
5154 }
5155}
drh0c2694b2009-09-03 16:23:44 +00005156static const sqlite3_io_methods
5157 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005158
5159#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5160
drh7708e972008-11-29 00:56:52 +00005161/*
5162** An abstract type for a pointer to a IO method finder function:
5163*/
drh0c2694b2009-09-03 16:23:44 +00005164typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005165
aswiftaebf4132008-11-21 00:10:35 +00005166
drh734c9862008-11-28 15:37:20 +00005167/****************************************************************************
5168**************************** sqlite3_vfs methods ****************************
5169**
5170** This division contains the implementation of methods on the
5171** sqlite3_vfs object.
5172*/
5173
danielk1977a3d4c882007-03-23 10:08:38 +00005174/*
danielk1977e339d652008-06-28 11:23:00 +00005175** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005176*/
5177static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005178 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005179 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005180 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005181 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005182 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005183){
drh7708e972008-11-29 00:56:52 +00005184 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005185 unixFile *pNew = (unixFile *)pId;
5186 int rc = SQLITE_OK;
5187
drh8af6c222010-05-14 12:43:01 +00005188 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005189
dan00157392010-10-05 11:33:15 +00005190 /* Usually the path zFilename should not be a relative pathname. The
5191 ** exception is when opening the proxy "conch" file in builds that
5192 ** include the special Apple locking styles.
5193 */
dan00157392010-10-05 11:33:15 +00005194#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005195 assert( zFilename==0 || zFilename[0]=='/'
5196 || pVfs->pAppData==(void*)&autolockIoFinder );
5197#else
5198 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005199#endif
dan00157392010-10-05 11:33:15 +00005200
drhb07028f2011-10-14 21:49:18 +00005201 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005202 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005203
drh308c2a52010-05-14 11:30:18 +00005204 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005205 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005206 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005207 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005208 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005209#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005210 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005211#endif
drhc02a43a2012-01-10 23:18:38 +00005212 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5213 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005214 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005215 }
drh503a6862013-03-01 01:07:17 +00005216 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005217 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005218 }
drh339eb0b2008-03-07 15:34:11 +00005219
drh6c7d5c52008-11-21 20:32:33 +00005220#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005221 pNew->pId = vxworksFindFileId(zFilename);
5222 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005223 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005224 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005225 }
5226#endif
5227
drhc02a43a2012-01-10 23:18:38 +00005228 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005229 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005230 }else{
drh0c2694b2009-09-03 16:23:44 +00005231 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005232#if SQLITE_ENABLE_LOCKING_STYLE
5233 /* Cache zFilename in the locking context (AFP and dotlock override) for
5234 ** proxyLock activation is possible (remote proxy is based on db name)
5235 ** zFilename remains valid until file is closed, to support */
5236 pNew->lockingContext = (void*)zFilename;
5237#endif
drhda0e7682008-07-30 15:27:54 +00005238 }
danielk1977e339d652008-06-28 11:23:00 +00005239
drh7ed97b92010-01-20 13:07:21 +00005240 if( pLockingStyle == &posixIoMethods
5241#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5242 || pLockingStyle == &nfsIoMethods
5243#endif
5244 ){
drh7708e972008-11-29 00:56:52 +00005245 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005246 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005247 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005248 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005249 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005250 ** in two scenarios:
5251 **
5252 ** (a) A call to fstat() failed.
5253 ** (b) A malloc failed.
5254 **
5255 ** Scenario (b) may only occur if the process is holding no other
5256 ** file descriptors open on the same file. If there were other file
5257 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005258 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005259 ** handle h - as it is guaranteed that no posix locks will be released
5260 ** by doing so.
5261 **
5262 ** If scenario (a) caused the error then things are not so safe. The
5263 ** implicit assumption here is that if fstat() fails, things are in
5264 ** such bad shape that dropping a lock or two doesn't matter much.
5265 */
drh0e9365c2011-03-02 02:08:13 +00005266 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005267 h = -1;
5268 }
drh7708e972008-11-29 00:56:52 +00005269 unixLeaveMutex();
5270 }
danielk1977e339d652008-06-28 11:23:00 +00005271
drhd2cb50b2009-01-09 21:41:17 +00005272#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005273 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005274 /* AFP locking uses the file path so it needs to be included in
5275 ** the afpLockingContext.
5276 */
5277 afpLockingContext *pCtx;
5278 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5279 if( pCtx==0 ){
5280 rc = SQLITE_NOMEM;
5281 }else{
5282 /* NB: zFilename exists and remains valid until the file is closed
5283 ** according to requirement F11141. So we do not need to make a
5284 ** copy of the filename. */
5285 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005286 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005287 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005288 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005289 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005290 if( rc!=SQLITE_OK ){
5291 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005292 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005293 h = -1;
5294 }
drh7708e972008-11-29 00:56:52 +00005295 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005296 }
drh7708e972008-11-29 00:56:52 +00005297 }
5298#endif
danielk1977e339d652008-06-28 11:23:00 +00005299
drh7708e972008-11-29 00:56:52 +00005300 else if( pLockingStyle == &dotlockIoMethods ){
5301 /* Dotfile locking uses the file path so it needs to be included in
5302 ** the dotlockLockingContext
5303 */
5304 char *zLockFile;
5305 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005306 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005307 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005308 zLockFile = (char *)sqlite3_malloc(nFilename);
5309 if( zLockFile==0 ){
5310 rc = SQLITE_NOMEM;
5311 }else{
5312 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005313 }
drh7708e972008-11-29 00:56:52 +00005314 pNew->lockingContext = zLockFile;
5315 }
danielk1977e339d652008-06-28 11:23:00 +00005316
drh6c7d5c52008-11-21 20:32:33 +00005317#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005318 else if( pLockingStyle == &semIoMethods ){
5319 /* Named semaphore locking uses the file path so it needs to be
5320 ** included in the semLockingContext
5321 */
5322 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005323 rc = findInodeInfo(pNew, &pNew->pInode);
5324 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5325 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005326 int n;
drh2238dcc2009-08-27 17:56:20 +00005327 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005328 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005329 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005330 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005331 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5332 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005333 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005334 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005335 }
chw97185482008-11-17 08:05:31 +00005336 }
drh7708e972008-11-29 00:56:52 +00005337 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005338 }
drh7708e972008-11-29 00:56:52 +00005339#endif
aswift5b1a2562008-08-22 00:22:35 +00005340
5341 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005342#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005343 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005344 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005345 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005346 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005347 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005348 }
chw97185482008-11-17 08:05:31 +00005349#endif
danielk1977e339d652008-06-28 11:23:00 +00005350 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005351 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005352 }else{
drh7708e972008-11-29 00:56:52 +00005353 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005354 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005355 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005356 }
danielk1977e339d652008-06-28 11:23:00 +00005357 return rc;
drh054889e2005-11-30 03:20:31 +00005358}
drh9c06c952005-11-26 00:25:00 +00005359
danielk1977ad94b582007-08-20 06:44:22 +00005360/*
drh8b3cf822010-06-01 21:02:51 +00005361** Return the name of a directory in which to put temporary files.
5362** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005363*/
drh7234c6d2010-06-19 15:10:09 +00005364static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005365 static const char *azDirs[] = {
5366 0,
aswiftaebf4132008-11-21 00:10:35 +00005367 0,
mistachkind95a3d32013-08-30 21:52:38 +00005368 0,
danielk197717b90b52008-06-06 11:11:25 +00005369 "/var/tmp",
5370 "/usr/tmp",
5371 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005372 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005373 };
drh8b3cf822010-06-01 21:02:51 +00005374 unsigned int i;
5375 struct stat buf;
5376 const char *zDir = 0;
5377
5378 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005379 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5380 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005381 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005382 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005383 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005384 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005385 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005386 break;
5387 }
5388 return zDir;
5389}
5390
5391/*
5392** Create a temporary file name in zBuf. zBuf must be allocated
5393** by the calling process and must be big enough to hold at least
5394** pVfs->mxPathname bytes.
5395*/
5396static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005397 static const unsigned char zChars[] =
5398 "abcdefghijklmnopqrstuvwxyz"
5399 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5400 "0123456789";
drh41022642008-11-21 00:24:42 +00005401 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005402 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005403
5404 /* It's odd to simulate an io-error here, but really this is just
5405 ** using the io-error infrastructure to test that SQLite handles this
5406 ** function failing.
5407 */
5408 SimulateIOError( return SQLITE_IOERR );
5409
drh7234c6d2010-06-19 15:10:09 +00005410 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005411 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005412
5413 /* Check that the output buffer is large enough for the temporary file
5414 ** name. If it is not, return SQLITE_ERROR.
5415 */
drhc02a43a2012-01-10 23:18:38 +00005416 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005417 return SQLITE_ERROR;
5418 }
5419
5420 do{
drhc02a43a2012-01-10 23:18:38 +00005421 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005422 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005423 sqlite3_randomness(15, &zBuf[j]);
5424 for(i=0; i<15; i++, j++){
5425 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5426 }
5427 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005428 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005429 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005430 return SQLITE_OK;
5431}
5432
drhd2cb50b2009-01-09 21:41:17 +00005433#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005434/*
5435** Routine to transform a unixFile into a proxy-locking unixFile.
5436** Implementation in the proxy-lock division, but used by unixOpen()
5437** if SQLITE_PREFER_PROXY_LOCKING is defined.
5438*/
5439static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005440#endif
drhc66d5b62008-12-03 22:48:32 +00005441
dan08da86a2009-08-21 17:18:03 +00005442/*
5443** Search for an unused file descriptor that was opened on the database
5444** file (not a journal or master-journal file) identified by pathname
5445** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5446** argument to this function.
5447**
5448** Such a file descriptor may exist if a database connection was closed
5449** but the associated file descriptor could not be closed because some
5450** other file descriptor open on the same file is holding a file-lock.
5451** Refer to comments in the unixClose() function and the lengthy comment
5452** describing "Posix Advisory Locking" at the start of this file for
5453** further details. Also, ticket #4018.
5454**
5455** If a suitable file descriptor is found, then it is returned. If no
5456** such file descriptor is located, -1 is returned.
5457*/
dane946c392009-08-22 11:39:46 +00005458static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5459 UnixUnusedFd *pUnused = 0;
5460
5461 /* Do not search for an unused file descriptor on vxworks. Not because
5462 ** vxworks would not benefit from the change (it might, we're not sure),
5463 ** but because no way to test it is currently available. It is better
5464 ** not to risk breaking vxworks support for the sake of such an obscure
5465 ** feature. */
5466#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005467 struct stat sStat; /* Results of stat() call */
5468
5469 /* A stat() call may fail for various reasons. If this happens, it is
5470 ** almost certain that an open() call on the same path will also fail.
5471 ** For this reason, if an error occurs in the stat() call here, it is
5472 ** ignored and -1 is returned. The caller will try to open a new file
5473 ** descriptor on the same path, fail, and return an error to SQLite.
5474 **
5475 ** Even if a subsequent open() call does succeed, the consequences of
5476 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005477 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005478 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005479
5480 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005481 pInode = inodeList;
5482 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5483 || pInode->fileId.ino!=sStat.st_ino) ){
5484 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005485 }
drh8af6c222010-05-14 12:43:01 +00005486 if( pInode ){
dane946c392009-08-22 11:39:46 +00005487 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005488 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005489 pUnused = *pp;
5490 if( pUnused ){
5491 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005492 }
5493 }
5494 unixLeaveMutex();
5495 }
dane946c392009-08-22 11:39:46 +00005496#endif /* if !OS_VXWORKS */
5497 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005498}
danielk197717b90b52008-06-06 11:11:25 +00005499
5500/*
danddb0ac42010-07-14 14:48:58 +00005501** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005502** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005503** and a value suitable for passing as the third argument to open(2) is
5504** written to *pMode. If an IO error occurs, an SQLite error code is
5505** returned and the value of *pMode is not modified.
5506**
drh8c815d12012-02-13 20:16:37 +00005507** In most cases cases, this routine sets *pMode to 0, which will become
5508** an indication to robust_open() to create the file using
5509** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5510** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005511** this function queries the file-system for the permissions on the
5512** corresponding database file and sets *pMode to this value. Whenever
5513** possible, WAL and journal files are created using the same permissions
5514** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005515**
5516** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5517** original filename is unavailable. But 8_3_NAMES is only used for
5518** FAT filesystems and permissions do not matter there, so just use
5519** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005520*/
5521static int findCreateFileMode(
5522 const char *zPath, /* Path of file (possibly) being created */
5523 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005524 mode_t *pMode, /* OUT: Permissions to open file with */
5525 uid_t *pUid, /* OUT: uid to set on the file */
5526 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005527){
5528 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005529 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005530 *pUid = 0;
5531 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005532 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005533 char zDb[MAX_PATHNAME+1]; /* Database file path */
5534 int nDb; /* Number of valid bytes in zDb */
5535 struct stat sStat; /* Output of stat() on database file */
5536
dana0c989d2010-11-05 18:07:37 +00005537 /* zPath is a path to a WAL or journal file. The following block derives
5538 ** the path to the associated database file from zPath. This block handles
5539 ** the following naming conventions:
5540 **
5541 ** "<path to db>-journal"
5542 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005543 ** "<path to db>-journalNN"
5544 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005545 **
drhd337c5b2011-10-20 18:23:35 +00005546 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005547 ** used by the test_multiplex.c module.
5548 */
5549 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005550#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005551 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005552 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005553#else
5554 while( zPath[nDb]!='-' ){
5555 assert( nDb>0 );
5556 assert( zPath[nDb]!='\n' );
5557 nDb--;
5558 }
5559#endif
danddb0ac42010-07-14 14:48:58 +00005560 memcpy(zDb, zPath, nDb);
5561 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005562
drh58384f12011-07-28 00:14:45 +00005563 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005564 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005565 *pUid = sStat.st_uid;
5566 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005567 }else{
5568 rc = SQLITE_IOERR_FSTAT;
5569 }
5570 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5571 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005572 }
5573 return rc;
5574}
5575
5576/*
danielk1977ad94b582007-08-20 06:44:22 +00005577** Open the file zPath.
5578**
danielk1977b4b47412007-08-17 15:53:36 +00005579** Previously, the SQLite OS layer used three functions in place of this
5580** one:
5581**
5582** sqlite3OsOpenReadWrite();
5583** sqlite3OsOpenReadOnly();
5584** sqlite3OsOpenExclusive();
5585**
5586** These calls correspond to the following combinations of flags:
5587**
5588** ReadWrite() -> (READWRITE | CREATE)
5589** ReadOnly() -> (READONLY)
5590** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5591**
5592** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5593** true, the file was configured to be automatically deleted when the
5594** file handle closed. To achieve the same effect using this new
5595** interface, add the DELETEONCLOSE flag to those specified above for
5596** OpenExclusive().
5597*/
5598static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005599 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5600 const char *zPath, /* Pathname of file to be opened */
5601 sqlite3_file *pFile, /* The file descriptor to be filled in */
5602 int flags, /* Input flags to control the opening */
5603 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005604){
dan08da86a2009-08-21 17:18:03 +00005605 unixFile *p = (unixFile *)pFile;
5606 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005607 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005608 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005609 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005610 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005611 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005612
5613 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5614 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5615 int isCreate = (flags & SQLITE_OPEN_CREATE);
5616 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5617 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005618#if SQLITE_ENABLE_LOCKING_STYLE
5619 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5620#endif
drh3d4435b2011-08-26 20:55:50 +00005621#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5622 struct statfs fsInfo;
5623#endif
danielk1977b4b47412007-08-17 15:53:36 +00005624
danielk1977fee2d252007-08-18 10:59:19 +00005625 /* If creating a master or main-file journal, this function will open
5626 ** a file-descriptor on the directory too. The first time unixSync()
5627 ** is called the directory file descriptor will be fsync()ed and close()d.
5628 */
drh0059eae2011-08-08 23:48:40 +00005629 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005630 eType==SQLITE_OPEN_MASTER_JOURNAL
5631 || eType==SQLITE_OPEN_MAIN_JOURNAL
5632 || eType==SQLITE_OPEN_WAL
5633 ));
danielk1977fee2d252007-08-18 10:59:19 +00005634
danielk197717b90b52008-06-06 11:11:25 +00005635 /* If argument zPath is a NULL pointer, this function is required to open
5636 ** a temporary file. Use this buffer to store the file name in.
5637 */
drhc02a43a2012-01-10 23:18:38 +00005638 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005639 const char *zName = zPath;
5640
danielk1977fee2d252007-08-18 10:59:19 +00005641 /* Check the following statements are true:
5642 **
5643 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5644 ** (b) if CREATE is set, then READWRITE must also be set, and
5645 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005646 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005647 */
danielk1977b4b47412007-08-17 15:53:36 +00005648 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005649 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005650 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005651 assert(isDelete==0 || isCreate);
5652
danddb0ac42010-07-14 14:48:58 +00005653 /* The main DB, main journal, WAL file and master journal are never
5654 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005655 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5656 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5657 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005658 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005659
danielk1977fee2d252007-08-18 10:59:19 +00005660 /* Assert that the upper layer has set one of the "file-type" flags. */
5661 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5662 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5663 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005664 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005665 );
5666
drhb00d8622014-01-01 15:18:36 +00005667 /* Detect a pid change and reset the PRNG. There is a race condition
5668 ** here such that two or more threads all trying to open databases at
5669 ** the same instant might all reset the PRNG. But multiple resets
5670 ** are harmless.
5671 */
5672 if( randomnessPid!=getpid() ){
5673 randomnessPid = getpid();
5674 sqlite3_randomness(0,0);
5675 }
5676
dan08da86a2009-08-21 17:18:03 +00005677 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005678
dan08da86a2009-08-21 17:18:03 +00005679 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005680 UnixUnusedFd *pUnused;
5681 pUnused = findReusableFd(zName, flags);
5682 if( pUnused ){
5683 fd = pUnused->fd;
5684 }else{
dan6aa657f2009-08-24 18:57:58 +00005685 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005686 if( !pUnused ){
5687 return SQLITE_NOMEM;
5688 }
5689 }
5690 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005691
5692 /* Database filenames are double-zero terminated if they are not
5693 ** URIs with parameters. Hence, they can always be passed into
5694 ** sqlite3_uri_parameter(). */
5695 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5696
dan08da86a2009-08-21 17:18:03 +00005697 }else if( !zName ){
5698 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005699 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005700 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005701 if( rc!=SQLITE_OK ){
5702 return rc;
5703 }
5704 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005705
5706 /* Generated temporary filenames are always double-zero terminated
5707 ** for use by sqlite3_uri_parameter(). */
5708 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005709 }
5710
dan08da86a2009-08-21 17:18:03 +00005711 /* Determine the value of the flags parameter passed to POSIX function
5712 ** open(). These must be calculated even if open() is not called, as
5713 ** they may be stored as part of the file handle and used by the
5714 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005715 if( isReadonly ) openFlags |= O_RDONLY;
5716 if( isReadWrite ) openFlags |= O_RDWR;
5717 if( isCreate ) openFlags |= O_CREAT;
5718 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5719 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005720
danielk1977b4b47412007-08-17 15:53:36 +00005721 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005722 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005723 uid_t uid; /* Userid for the file */
5724 gid_t gid; /* Groupid for the file */
5725 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005726 if( rc!=SQLITE_OK ){
5727 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005728 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005729 return rc;
5730 }
drhad4f1e52011-03-04 15:43:57 +00005731 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005732 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005733 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5734 /* Failed to open the file for read/write access. Try read-only. */
5735 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005736 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005737 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005738 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005739 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005740 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005741 }
5742 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005743 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005744 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005745 }
drhac7c3ac2012-02-11 19:23:48 +00005746
5747 /* If this process is running as root and if creating a new rollback
5748 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005749 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005750 */
5751 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005752 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005753 }
danielk1977b4b47412007-08-17 15:53:36 +00005754 }
dan08da86a2009-08-21 17:18:03 +00005755 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005756 if( pOutFlags ){
5757 *pOutFlags = flags;
5758 }
5759
dane946c392009-08-22 11:39:46 +00005760 if( p->pUnused ){
5761 p->pUnused->fd = fd;
5762 p->pUnused->flags = flags;
5763 }
5764
danielk1977b4b47412007-08-17 15:53:36 +00005765 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005766#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005767 zPath = zName;
5768#else
drh036ac7f2011-08-08 23:18:05 +00005769 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005770#endif
danielk1977b4b47412007-08-17 15:53:36 +00005771 }
drh41022642008-11-21 00:24:42 +00005772#if SQLITE_ENABLE_LOCKING_STYLE
5773 else{
dan08da86a2009-08-21 17:18:03 +00005774 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005775 }
5776#endif
5777
drhda0e7682008-07-30 15:27:54 +00005778 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005779
drh7ed97b92010-01-20 13:07:21 +00005780
5781#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005782 if( fstatfs(fd, &fsInfo) == -1 ){
5783 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005784 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005785 return SQLITE_IOERR_ACCESS;
5786 }
5787 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5788 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5789 }
5790#endif
drhc02a43a2012-01-10 23:18:38 +00005791
5792 /* Set up appropriate ctrlFlags */
5793 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5794 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5795 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5796 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5797 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5798
drh7ed97b92010-01-20 13:07:21 +00005799#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005800#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005801 isAutoProxy = 1;
5802#endif
5803 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005804 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5805 int useProxy = 0;
5806
dan08da86a2009-08-21 17:18:03 +00005807 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5808 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005809 if( envforce!=NULL ){
5810 useProxy = atoi(envforce)>0;
5811 }else{
aswiftaebf4132008-11-21 00:10:35 +00005812 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005813 /* In theory, the close(fd) call is sub-optimal. If the file opened
5814 ** with fd is a database file, and there are other connections open
5815 ** on that file that are currently holding advisory locks on it,
5816 ** then the call to close() will cancel those locks. In practice,
5817 ** we're assuming that statfs() doesn't fail very often. At least
5818 ** not while other file descriptors opened by the same process on
5819 ** the same file are working. */
5820 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005821 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005822 rc = SQLITE_IOERR_ACCESS;
5823 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005824 }
5825 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5826 }
5827 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005828 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005829 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005830 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005831 if( rc!=SQLITE_OK ){
5832 /* Use unixClose to clean up the resources added in fillInUnixFile
5833 ** and clear all the structure's references. Specifically,
5834 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5835 */
5836 unixClose(pFile);
5837 return rc;
5838 }
aswiftaebf4132008-11-21 00:10:35 +00005839 }
dane946c392009-08-22 11:39:46 +00005840 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005841 }
5842 }
5843#endif
5844
drhc02a43a2012-01-10 23:18:38 +00005845 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5846
dane946c392009-08-22 11:39:46 +00005847open_finished:
5848 if( rc!=SQLITE_OK ){
5849 sqlite3_free(p->pUnused);
5850 }
5851 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005852}
5853
dane946c392009-08-22 11:39:46 +00005854
danielk1977b4b47412007-08-17 15:53:36 +00005855/*
danielk1977fee2d252007-08-18 10:59:19 +00005856** Delete the file at zPath. If the dirSync argument is true, fsync()
5857** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005858*/
drh6b9d6dd2008-12-03 19:34:47 +00005859static int unixDelete(
5860 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5861 const char *zPath, /* Name of file to be deleted */
5862 int dirSync /* If true, fsync() directory after deleting file */
5863){
danielk1977fee2d252007-08-18 10:59:19 +00005864 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005865 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005866 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005867 if( osUnlink(zPath)==(-1) ){
5868 if( errno==ENOENT ){
5869 rc = SQLITE_IOERR_DELETE_NOENT;
5870 }else{
drhb4308162012-11-09 21:40:02 +00005871 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005872 }
drhb4308162012-11-09 21:40:02 +00005873 return rc;
drh5d4feff2010-07-14 01:45:22 +00005874 }
danielk1977d39fa702008-10-16 13:27:40 +00005875#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005876 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005877 int fd;
drh90315a22011-08-10 01:52:12 +00005878 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005879 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005880#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005881 if( fsync(fd)==-1 )
5882#else
5883 if( fsync(fd) )
5884#endif
5885 {
dane18d4952011-02-21 11:46:24 +00005886 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005887 }
drh0e9365c2011-03-02 02:08:13 +00005888 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005889 }else if( rc==SQLITE_CANTOPEN ){
5890 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005891 }
5892 }
danielk1977d138dd82008-10-15 16:02:48 +00005893#endif
danielk1977fee2d252007-08-18 10:59:19 +00005894 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005895}
5896
danielk197790949c22007-08-17 16:50:38 +00005897/*
mistachkin48864df2013-03-21 21:20:32 +00005898** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005899** test performed depends on the value of flags:
5900**
5901** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5902** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5903** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5904**
5905** Otherwise return 0.
5906*/
danielk1977861f7452008-06-05 11:39:11 +00005907static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005908 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5909 const char *zPath, /* Path of the file to examine */
5910 int flags, /* What do we want to learn about the zPath file? */
5911 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005912){
rse25c0d1a2007-09-20 08:38:14 +00005913 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005914 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005915 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005916 switch( flags ){
5917 case SQLITE_ACCESS_EXISTS:
5918 amode = F_OK;
5919 break;
5920 case SQLITE_ACCESS_READWRITE:
5921 amode = W_OK|R_OK;
5922 break;
drh50d3f902007-08-27 21:10:36 +00005923 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005924 amode = R_OK;
5925 break;
5926
5927 default:
5928 assert(!"Invalid flags argument");
5929 }
drh99ab3b12011-03-02 15:09:07 +00005930 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005931 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5932 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005933 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005934 *pResOut = 0;
5935 }
5936 }
danielk1977861f7452008-06-05 11:39:11 +00005937 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005938}
5939
danielk1977b4b47412007-08-17 15:53:36 +00005940
5941/*
5942** Turn a relative pathname into a full pathname. The relative path
5943** is stored as a nul-terminated string in the buffer pointed to by
5944** zPath.
5945**
5946** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5947** (in this case, MAX_PATHNAME bytes). The full-path is written to
5948** this buffer before returning.
5949*/
danielk1977adfb9b02007-09-17 07:02:56 +00005950static int unixFullPathname(
5951 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5952 const char *zPath, /* Possibly relative input path */
5953 int nOut, /* Size of output buffer in bytes */
5954 char *zOut /* Output buffer */
5955){
danielk1977843e65f2007-09-01 16:16:15 +00005956
5957 /* It's odd to simulate an io-error here, but really this is just
5958 ** using the io-error infrastructure to test that SQLite handles this
5959 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005960 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005961 */
5962 SimulateIOError( return SQLITE_ERROR );
5963
drh153c62c2007-08-24 03:51:33 +00005964 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005965 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005966
drh3c7f2dc2007-12-06 13:26:20 +00005967 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005968 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005969 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005970 }else{
5971 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005972 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005973 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005974 }
drhea678832008-12-10 19:26:22 +00005975 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005976 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005977 }
5978 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005979}
5980
drh0ccebe72005-06-07 22:22:50 +00005981
drh761df872006-12-21 01:29:22 +00005982#ifndef SQLITE_OMIT_LOAD_EXTENSION
5983/*
5984** Interfaces for opening a shared library, finding entry points
5985** within the shared library, and closing the shared library.
5986*/
5987#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005988static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5989 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005990 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5991}
danielk197795c8a542007-09-01 06:51:27 +00005992
5993/*
5994** SQLite calls this function immediately after a call to unixDlSym() or
5995** unixDlOpen() fails (returns a null pointer). If a more detailed error
5996** message is available, it is written to zBufOut. If no error message
5997** is available, zBufOut is left unmodified and SQLite uses a default
5998** error message.
5999*/
danielk1977397d65f2008-11-19 11:35:39 +00006000static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006001 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006002 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006003 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006004 zErr = dlerror();
6005 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006006 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006007 }
drh6c7d5c52008-11-21 20:32:33 +00006008 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006009}
drh1875f7a2008-12-08 18:19:17 +00006010static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6011 /*
6012 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6013 ** cast into a pointer to a function. And yet the library dlsym() routine
6014 ** returns a void* which is really a pointer to a function. So how do we
6015 ** use dlsym() with -pedantic-errors?
6016 **
6017 ** Variable x below is defined to be a pointer to a function taking
6018 ** parameters void* and const char* and returning a pointer to a function.
6019 ** We initialize x by assigning it a pointer to the dlsym() function.
6020 ** (That assignment requires a cast.) Then we call the function that
6021 ** x points to.
6022 **
6023 ** This work-around is unlikely to work correctly on any system where
6024 ** you really cannot cast a function pointer into void*. But then, on the
6025 ** other hand, dlsym() will not work on such a system either, so we have
6026 ** not really lost anything.
6027 */
6028 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006029 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006030 x = (void(*(*)(void*,const char*))(void))dlsym;
6031 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006032}
danielk1977397d65f2008-11-19 11:35:39 +00006033static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6034 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006035 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006036}
danielk1977b4b47412007-08-17 15:53:36 +00006037#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6038 #define unixDlOpen 0
6039 #define unixDlError 0
6040 #define unixDlSym 0
6041 #define unixDlClose 0
6042#endif
6043
6044/*
danielk197790949c22007-08-17 16:50:38 +00006045** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006046*/
danielk1977397d65f2008-11-19 11:35:39 +00006047static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6048 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006049 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006050
drhbbd42a62004-05-22 17:41:58 +00006051 /* We have to initialize zBuf to prevent valgrind from reporting
6052 ** errors. The reports issued by valgrind are incorrect - we would
6053 ** prefer that the randomness be increased by making use of the
6054 ** uninitialized space in zBuf - but valgrind errors tend to worry
6055 ** some users. Rather than argue, it seems easier just to initialize
6056 ** the whole array and silence valgrind, even if that means less randomness
6057 ** in the random seed.
6058 **
6059 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006060 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006061 ** tests repeatable.
6062 */
danielk1977b4b47412007-08-17 15:53:36 +00006063 memset(zBuf, 0, nBuf);
drhb00d8622014-01-01 15:18:36 +00006064 randomnessPid = getpid();
drhbbd42a62004-05-22 17:41:58 +00006065#if !defined(SQLITE_TEST)
6066 {
drhb00d8622014-01-01 15:18:36 +00006067 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006068 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006069 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006070 time_t t;
6071 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006072 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006073 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6074 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6075 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006076 }else{
drhc18b4042012-02-10 03:10:27 +00006077 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006078 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006079 }
drhbbd42a62004-05-22 17:41:58 +00006080 }
6081#endif
drh72cbd072008-10-14 17:58:38 +00006082 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006083}
6084
danielk1977b4b47412007-08-17 15:53:36 +00006085
drhbbd42a62004-05-22 17:41:58 +00006086/*
6087** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006088** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006089** The return value is the number of microseconds of sleep actually
6090** requested from the underlying operating system, a number which
6091** might be greater than or equal to the argument, but not less
6092** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006093*/
danielk1977397d65f2008-11-19 11:35:39 +00006094static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006095#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006096 struct timespec sp;
6097
6098 sp.tv_sec = microseconds / 1000000;
6099 sp.tv_nsec = (microseconds % 1000000) * 1000;
6100 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006101 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006102 return microseconds;
6103#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006104 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006105 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006106 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006107#else
danielk1977b4b47412007-08-17 15:53:36 +00006108 int seconds = (microseconds+999999)/1000000;
6109 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006110 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006111 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006112#endif
drh88f474a2006-01-02 20:00:12 +00006113}
6114
6115/*
drh6b9d6dd2008-12-03 19:34:47 +00006116** The following variable, if set to a non-zero value, is interpreted as
6117** the number of seconds since 1970 and is used to set the result of
6118** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006119*/
6120#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006121int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006122#endif
6123
6124/*
drhb7e8ea22010-05-03 14:32:30 +00006125** Find the current time (in Universal Coordinated Time). Write into *piNow
6126** the current time and date as a Julian Day number times 86_400_000. In
6127** other words, write into *piNow the number of milliseconds since the Julian
6128** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6129** proleptic Gregorian calendar.
6130**
drh31702252011-10-12 23:13:43 +00006131** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6132** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006133*/
6134static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6135 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006136 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006137#if defined(NO_GETTOD)
6138 time_t t;
6139 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006140 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006141#elif OS_VXWORKS
6142 struct timespec sNow;
6143 clock_gettime(CLOCK_REALTIME, &sNow);
6144 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6145#else
6146 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006147 if( gettimeofday(&sNow, 0)==0 ){
6148 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6149 }else{
6150 rc = SQLITE_ERROR;
6151 }
drhb7e8ea22010-05-03 14:32:30 +00006152#endif
6153
6154#ifdef SQLITE_TEST
6155 if( sqlite3_current_time ){
6156 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6157 }
6158#endif
6159 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006160 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006161}
6162
6163/*
drhbbd42a62004-05-22 17:41:58 +00006164** Find the current time (in Universal Coordinated Time). Write the
6165** current time and date as a Julian Day number into *prNow and
6166** return 0. Return 1 if the time and date cannot be found.
6167*/
danielk1977397d65f2008-11-19 11:35:39 +00006168static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006169 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006170 int rc;
drhff828942010-06-26 21:34:06 +00006171 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006172 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006173 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006174 return rc;
drhbbd42a62004-05-22 17:41:58 +00006175}
danielk1977b4b47412007-08-17 15:53:36 +00006176
drh6b9d6dd2008-12-03 19:34:47 +00006177/*
6178** We added the xGetLastError() method with the intention of providing
6179** better low-level error messages when operating-system problems come up
6180** during SQLite operation. But so far, none of that has been implemented
6181** in the core. So this routine is never called. For now, it is merely
6182** a place-holder.
6183*/
danielk1977397d65f2008-11-19 11:35:39 +00006184static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6185 UNUSED_PARAMETER(NotUsed);
6186 UNUSED_PARAMETER(NotUsed2);
6187 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006188 return 0;
6189}
6190
drhf2424c52010-04-26 00:04:55 +00006191
6192/*
drh734c9862008-11-28 15:37:20 +00006193************************ End of sqlite3_vfs methods ***************************
6194******************************************************************************/
6195
drh715ff302008-12-03 22:32:44 +00006196/******************************************************************************
6197************************** Begin Proxy Locking ********************************
6198**
6199** Proxy locking is a "uber-locking-method" in this sense: It uses the
6200** other locking methods on secondary lock files. Proxy locking is a
6201** meta-layer over top of the primitive locking implemented above. For
6202** this reason, the division that implements of proxy locking is deferred
6203** until late in the file (here) after all of the other I/O methods have
6204** been defined - so that the primitive locking methods are available
6205** as services to help with the implementation of proxy locking.
6206**
6207****
6208**
6209** The default locking schemes in SQLite use byte-range locks on the
6210** database file to coordinate safe, concurrent access by multiple readers
6211** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6212** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6213** as POSIX read & write locks over fixed set of locations (via fsctl),
6214** on AFP and SMB only exclusive byte-range locks are available via fsctl
6215** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6216** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6217** address in the shared range is taken for a SHARED lock, the entire
6218** shared range is taken for an EXCLUSIVE lock):
6219**
drhf2f105d2012-08-20 15:53:54 +00006220** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006221** RESERVED_BYTE 0x40000001
6222** SHARED_RANGE 0x40000002 -> 0x40000200
6223**
6224** This works well on the local file system, but shows a nearly 100x
6225** slowdown in read performance on AFP because the AFP client disables
6226** the read cache when byte-range locks are present. Enabling the read
6227** cache exposes a cache coherency problem that is present on all OS X
6228** supported network file systems. NFS and AFP both observe the
6229** close-to-open semantics for ensuring cache coherency
6230** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6231** address the requirements for concurrent database access by multiple
6232** readers and writers
6233** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6234**
6235** To address the performance and cache coherency issues, proxy file locking
6236** changes the way database access is controlled by limiting access to a
6237** single host at a time and moving file locks off of the database file
6238** and onto a proxy file on the local file system.
6239**
6240**
6241** Using proxy locks
6242** -----------------
6243**
6244** C APIs
6245**
6246** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6247** <proxy_path> | ":auto:");
6248** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6249**
6250**
6251** SQL pragmas
6252**
6253** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6254** PRAGMA [database.]lock_proxy_file
6255**
6256** Specifying ":auto:" means that if there is a conch file with a matching
6257** host ID in it, the proxy path in the conch file will be used, otherwise
6258** a proxy path based on the user's temp dir
6259** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6260** actual proxy file name is generated from the name and path of the
6261** database file. For example:
6262**
6263** For database path "/Users/me/foo.db"
6264** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6265**
6266** Once a lock proxy is configured for a database connection, it can not
6267** be removed, however it may be switched to a different proxy path via
6268** the above APIs (assuming the conch file is not being held by another
6269** connection or process).
6270**
6271**
6272** How proxy locking works
6273** -----------------------
6274**
6275** Proxy file locking relies primarily on two new supporting files:
6276**
6277** * conch file to limit access to the database file to a single host
6278** at a time
6279**
6280** * proxy file to act as a proxy for the advisory locks normally
6281** taken on the database
6282**
6283** The conch file - to use a proxy file, sqlite must first "hold the conch"
6284** by taking an sqlite-style shared lock on the conch file, reading the
6285** contents and comparing the host's unique host ID (see below) and lock
6286** proxy path against the values stored in the conch. The conch file is
6287** stored in the same directory as the database file and the file name
6288** is patterned after the database file name as ".<databasename>-conch".
6289** If the conch file does not exist, or it's contents do not match the
6290** host ID and/or proxy path, then the lock is escalated to an exclusive
6291** lock and the conch file contents is updated with the host ID and proxy
6292** path and the lock is downgraded to a shared lock again. If the conch
6293** is held by another process (with a shared lock), the exclusive lock
6294** will fail and SQLITE_BUSY is returned.
6295**
6296** The proxy file - a single-byte file used for all advisory file locks
6297** normally taken on the database file. This allows for safe sharing
6298** of the database file for multiple readers and writers on the same
6299** host (the conch ensures that they all use the same local lock file).
6300**
drh715ff302008-12-03 22:32:44 +00006301** Requesting the lock proxy does not immediately take the conch, it is
6302** only taken when the first request to lock database file is made.
6303** This matches the semantics of the traditional locking behavior, where
6304** opening a connection to a database file does not take a lock on it.
6305** The shared lock and an open file descriptor are maintained until
6306** the connection to the database is closed.
6307**
6308** The proxy file and the lock file are never deleted so they only need
6309** to be created the first time they are used.
6310**
6311** Configuration options
6312** ---------------------
6313**
6314** SQLITE_PREFER_PROXY_LOCKING
6315**
6316** Database files accessed on non-local file systems are
6317** automatically configured for proxy locking, lock files are
6318** named automatically using the same logic as
6319** PRAGMA lock_proxy_file=":auto:"
6320**
6321** SQLITE_PROXY_DEBUG
6322**
6323** Enables the logging of error messages during host id file
6324** retrieval and creation
6325**
drh715ff302008-12-03 22:32:44 +00006326** LOCKPROXYDIR
6327**
6328** Overrides the default directory used for lock proxy files that
6329** are named automatically via the ":auto:" setting
6330**
6331** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6332**
6333** Permissions to use when creating a directory for storing the
6334** lock proxy files, only used when LOCKPROXYDIR is not set.
6335**
6336**
6337** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6338** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6339** force proxy locking to be used for every database file opened, and 0
6340** will force automatic proxy locking to be disabled for all database
6341** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6342** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6343*/
6344
6345/*
6346** Proxy locking is only available on MacOSX
6347*/
drhd2cb50b2009-01-09 21:41:17 +00006348#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006349
drh715ff302008-12-03 22:32:44 +00006350/*
6351** The proxyLockingContext has the path and file structures for the remote
6352** and local proxy files in it
6353*/
6354typedef struct proxyLockingContext proxyLockingContext;
6355struct proxyLockingContext {
6356 unixFile *conchFile; /* Open conch file */
6357 char *conchFilePath; /* Name of the conch file */
6358 unixFile *lockProxy; /* Open proxy lock file */
6359 char *lockProxyPath; /* Name of the proxy lock file */
6360 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006361 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006362 void *oldLockingContext; /* Original lockingcontext to restore on close */
6363 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6364};
6365
drh7ed97b92010-01-20 13:07:21 +00006366/*
6367** The proxy lock file path for the database at dbPath is written into lPath,
6368** which must point to valid, writable memory large enough for a maxLen length
6369** file path.
drh715ff302008-12-03 22:32:44 +00006370*/
drh715ff302008-12-03 22:32:44 +00006371static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6372 int len;
6373 int dbLen;
6374 int i;
6375
6376#ifdef LOCKPROXYDIR
6377 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6378#else
6379# ifdef _CS_DARWIN_USER_TEMP_DIR
6380 {
drh7ed97b92010-01-20 13:07:21 +00006381 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006382 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6383 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006384 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006385 }
drh7ed97b92010-01-20 13:07:21 +00006386 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006387 }
6388# else
6389 len = strlcpy(lPath, "/tmp/", maxLen);
6390# endif
6391#endif
6392
6393 if( lPath[len-1]!='/' ){
6394 len = strlcat(lPath, "/", maxLen);
6395 }
6396
6397 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006398 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006399 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006400 char c = dbPath[i];
6401 lPath[i+len] = (c=='/')?'_':c;
6402 }
6403 lPath[i+len]='\0';
6404 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006405 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006406 return SQLITE_OK;
6407}
6408
drh7ed97b92010-01-20 13:07:21 +00006409/*
6410 ** Creates the lock file and any missing directories in lockPath
6411 */
6412static int proxyCreateLockPath(const char *lockPath){
6413 int i, len;
6414 char buf[MAXPATHLEN];
6415 int start = 0;
6416
6417 assert(lockPath!=NULL);
6418 /* try to create all the intermediate directories */
6419 len = (int)strlen(lockPath);
6420 buf[0] = lockPath[0];
6421 for( i=1; i<len; i++ ){
6422 if( lockPath[i] == '/' && (i - start > 0) ){
6423 /* only mkdir if leaf dir != "." or "/" or ".." */
6424 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6425 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6426 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006427 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006428 int err=errno;
6429 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006430 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006431 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006432 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006433 return err;
6434 }
6435 }
6436 }
6437 start=i+1;
6438 }
6439 buf[i] = lockPath[i];
6440 }
drh308c2a52010-05-14 11:30:18 +00006441 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006442 return 0;
6443}
6444
drh715ff302008-12-03 22:32:44 +00006445/*
6446** Create a new VFS file descriptor (stored in memory obtained from
6447** sqlite3_malloc) and open the file named "path" in the file descriptor.
6448**
6449** The caller is responsible not only for closing the file descriptor
6450** but also for freeing the memory associated with the file descriptor.
6451*/
drh7ed97b92010-01-20 13:07:21 +00006452static int proxyCreateUnixFile(
6453 const char *path, /* path for the new unixFile */
6454 unixFile **ppFile, /* unixFile created and returned by ref */
6455 int islockfile /* if non zero missing dirs will be created */
6456) {
6457 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006458 unixFile *pNew;
6459 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006460 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006461 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006462 int terrno = 0;
6463 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006464
drh7ed97b92010-01-20 13:07:21 +00006465 /* 1. first try to open/create the file
6466 ** 2. if that fails, and this is a lock file (not-conch), try creating
6467 ** the parent directories and then try again.
6468 ** 3. if that fails, try to open the file read-only
6469 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6470 */
6471 pUnused = findReusableFd(path, openFlags);
6472 if( pUnused ){
6473 fd = pUnused->fd;
6474 }else{
6475 pUnused = sqlite3_malloc(sizeof(*pUnused));
6476 if( !pUnused ){
6477 return SQLITE_NOMEM;
6478 }
6479 }
6480 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006481 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006482 terrno = errno;
6483 if( fd<0 && errno==ENOENT && islockfile ){
6484 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006485 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006486 }
6487 }
6488 }
6489 if( fd<0 ){
6490 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006491 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006492 terrno = errno;
6493 }
6494 if( fd<0 ){
6495 if( islockfile ){
6496 return SQLITE_BUSY;
6497 }
6498 switch (terrno) {
6499 case EACCES:
6500 return SQLITE_PERM;
6501 case EIO:
6502 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6503 default:
drh9978c972010-02-23 17:36:32 +00006504 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006505 }
6506 }
6507
6508 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6509 if( pNew==NULL ){
6510 rc = SQLITE_NOMEM;
6511 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006512 }
6513 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006514 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006515 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006516 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006517 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006518 pUnused->fd = fd;
6519 pUnused->flags = openFlags;
6520 pNew->pUnused = pUnused;
6521
drhc02a43a2012-01-10 23:18:38 +00006522 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006523 if( rc==SQLITE_OK ){
6524 *ppFile = pNew;
6525 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006526 }
drh7ed97b92010-01-20 13:07:21 +00006527end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006528 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006529 sqlite3_free(pNew);
6530 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006531 return rc;
6532}
6533
drh7ed97b92010-01-20 13:07:21 +00006534#ifdef SQLITE_TEST
6535/* simulate multiple hosts by creating unique hostid file paths */
6536int sqlite3_hostid_num = 0;
6537#endif
6538
6539#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6540
drh0ab216a2010-07-02 17:10:40 +00006541/* Not always defined in the headers as it ought to be */
6542extern int gethostuuid(uuid_t id, const struct timespec *wait);
6543
drh7ed97b92010-01-20 13:07:21 +00006544/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6545** bytes of writable memory.
6546*/
6547static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006548 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6549 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006550#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6551 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006552 {
6553 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6554 if( gethostuuid(pHostID, &timeout) ){
6555 int err = errno;
6556 if( pError ){
6557 *pError = err;
6558 }
6559 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006560 }
drh7ed97b92010-01-20 13:07:21 +00006561 }
drh3d4435b2011-08-26 20:55:50 +00006562#else
6563 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006564#endif
drh7ed97b92010-01-20 13:07:21 +00006565#ifdef SQLITE_TEST
6566 /* simulate multiple hosts by creating unique hostid file paths */
6567 if( sqlite3_hostid_num != 0){
6568 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6569 }
6570#endif
6571
6572 return SQLITE_OK;
6573}
6574
6575/* The conch file contains the header, host id and lock file path
6576 */
6577#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6578#define PROXY_HEADERLEN 1 /* conch file header length */
6579#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6580#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6581
6582/*
6583** Takes an open conch file, copies the contents to a new path and then moves
6584** it back. The newly created file's file descriptor is assigned to the
6585** conch file structure and finally the original conch file descriptor is
6586** closed. Returns zero if successful.
6587*/
6588static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6589 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6590 unixFile *conchFile = pCtx->conchFile;
6591 char tPath[MAXPATHLEN];
6592 char buf[PROXY_MAXCONCHLEN];
6593 char *cPath = pCtx->conchFilePath;
6594 size_t readLen = 0;
6595 size_t pathLen = 0;
6596 char errmsg[64] = "";
6597 int fd = -1;
6598 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006599 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006600
6601 /* create a new path by replace the trailing '-conch' with '-break' */
6602 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6603 if( pathLen>MAXPATHLEN || pathLen<6 ||
6604 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006605 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006606 goto end_breaklock;
6607 }
6608 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006609 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006610 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006611 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006612 goto end_breaklock;
6613 }
6614 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006615 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006616 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006617 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006618 goto end_breaklock;
6619 }
drhe562be52011-03-02 18:01:10 +00006620 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006621 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006622 goto end_breaklock;
6623 }
6624 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006625 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006626 goto end_breaklock;
6627 }
6628 rc = 0;
6629 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006630 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006631 conchFile->h = fd;
6632 conchFile->openFlags = O_RDWR | O_CREAT;
6633
6634end_breaklock:
6635 if( rc ){
6636 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006637 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006638 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006639 }
6640 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6641 }
6642 return rc;
6643}
6644
6645/* Take the requested lock on the conch file and break a stale lock if the
6646** host id matches.
6647*/
6648static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6649 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6650 unixFile *conchFile = pCtx->conchFile;
6651 int rc = SQLITE_OK;
6652 int nTries = 0;
6653 struct timespec conchModTime;
6654
drh3d4435b2011-08-26 20:55:50 +00006655 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006656 do {
6657 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6658 nTries ++;
6659 if( rc==SQLITE_BUSY ){
6660 /* If the lock failed (busy):
6661 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6662 * 2nd try: fail if the mod time changed or host id is different, wait
6663 * 10 sec and try again
6664 * 3rd try: break the lock unless the mod time has changed.
6665 */
6666 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006667 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006668 pFile->lastErrno = errno;
6669 return SQLITE_IOERR_LOCK;
6670 }
6671
6672 if( nTries==1 ){
6673 conchModTime = buf.st_mtimespec;
6674 usleep(500000); /* wait 0.5 sec and try the lock again*/
6675 continue;
6676 }
6677
6678 assert( nTries>1 );
6679 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6680 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6681 return SQLITE_BUSY;
6682 }
6683
6684 if( nTries==2 ){
6685 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006686 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006687 if( len<0 ){
6688 pFile->lastErrno = errno;
6689 return SQLITE_IOERR_LOCK;
6690 }
6691 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6692 /* don't break the lock if the host id doesn't match */
6693 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6694 return SQLITE_BUSY;
6695 }
6696 }else{
6697 /* don't break the lock on short read or a version mismatch */
6698 return SQLITE_BUSY;
6699 }
6700 usleep(10000000); /* wait 10 sec and try the lock again */
6701 continue;
6702 }
6703
6704 assert( nTries==3 );
6705 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6706 rc = SQLITE_OK;
6707 if( lockType==EXCLUSIVE_LOCK ){
6708 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6709 }
6710 if( !rc ){
6711 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6712 }
6713 }
6714 }
6715 } while( rc==SQLITE_BUSY && nTries<3 );
6716
6717 return rc;
6718}
6719
6720/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006721** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6722** lockPath means that the lockPath in the conch file will be used if the
6723** host IDs match, or a new lock path will be generated automatically
6724** and written to the conch file.
6725*/
6726static int proxyTakeConch(unixFile *pFile){
6727 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6728
drh7ed97b92010-01-20 13:07:21 +00006729 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006730 return SQLITE_OK;
6731 }else{
6732 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006733 uuid_t myHostID;
6734 int pError = 0;
6735 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006736 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006737 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006738 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006739 int createConch = 0;
6740 int hostIdMatch = 0;
6741 int readLen = 0;
6742 int tryOldLockPath = 0;
6743 int forceNewLockPath = 0;
6744
drh308c2a52010-05-14 11:30:18 +00006745 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6746 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006747
drh7ed97b92010-01-20 13:07:21 +00006748 rc = proxyGetHostID(myHostID, &pError);
6749 if( (rc&0xff)==SQLITE_IOERR ){
6750 pFile->lastErrno = pError;
6751 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006752 }
drh7ed97b92010-01-20 13:07:21 +00006753 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006754 if( rc!=SQLITE_OK ){
6755 goto end_takeconch;
6756 }
drh7ed97b92010-01-20 13:07:21 +00006757 /* read the existing conch file */
6758 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6759 if( readLen<0 ){
6760 /* I/O error: lastErrno set by seekAndRead */
6761 pFile->lastErrno = conchFile->lastErrno;
6762 rc = SQLITE_IOERR_READ;
6763 goto end_takeconch;
6764 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6765 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6766 /* a short read or version format mismatch means we need to create a new
6767 ** conch file.
6768 */
6769 createConch = 1;
6770 }
6771 /* if the host id matches and the lock path already exists in the conch
6772 ** we'll try to use the path there, if we can't open that path, we'll
6773 ** retry with a new auto-generated path
6774 */
6775 do { /* in case we need to try again for an :auto: named lock file */
6776
6777 if( !createConch && !forceNewLockPath ){
6778 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6779 PROXY_HOSTIDLEN);
6780 /* if the conch has data compare the contents */
6781 if( !pCtx->lockProxyPath ){
6782 /* for auto-named local lock file, just check the host ID and we'll
6783 ** use the local lock file path that's already in there
6784 */
6785 if( hostIdMatch ){
6786 size_t pathLen = (readLen - PROXY_PATHINDEX);
6787
6788 if( pathLen>=MAXPATHLEN ){
6789 pathLen=MAXPATHLEN-1;
6790 }
6791 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6792 lockPath[pathLen] = 0;
6793 tempLockPath = lockPath;
6794 tryOldLockPath = 1;
6795 /* create a copy of the lock path if the conch is taken */
6796 goto end_takeconch;
6797 }
6798 }else if( hostIdMatch
6799 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6800 readLen-PROXY_PATHINDEX)
6801 ){
6802 /* conch host and lock path match */
6803 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006804 }
drh7ed97b92010-01-20 13:07:21 +00006805 }
6806
6807 /* if the conch isn't writable and doesn't match, we can't take it */
6808 if( (conchFile->openFlags&O_RDWR) == 0 ){
6809 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006810 goto end_takeconch;
6811 }
drh7ed97b92010-01-20 13:07:21 +00006812
6813 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006814 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006815 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6816 tempLockPath = lockPath;
6817 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006818 }
drh7ed97b92010-01-20 13:07:21 +00006819
6820 /* update conch with host and path (this will fail if other process
6821 ** has a shared lock already), if the host id matches, use the big
6822 ** stick.
drh715ff302008-12-03 22:32:44 +00006823 */
drh7ed97b92010-01-20 13:07:21 +00006824 futimes(conchFile->h, NULL);
6825 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006826 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006827 /* We are trying for an exclusive lock but another thread in this
6828 ** same process is still holding a shared lock. */
6829 rc = SQLITE_BUSY;
6830 } else {
6831 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006832 }
drh715ff302008-12-03 22:32:44 +00006833 }else{
drh7ed97b92010-01-20 13:07:21 +00006834 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006835 }
drh7ed97b92010-01-20 13:07:21 +00006836 if( rc==SQLITE_OK ){
6837 char writeBuffer[PROXY_MAXCONCHLEN];
6838 int writeSize = 0;
6839
6840 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6841 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6842 if( pCtx->lockProxyPath!=NULL ){
6843 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6844 }else{
6845 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6846 }
6847 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006848 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006849 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6850 fsync(conchFile->h);
6851 /* If we created a new conch file (not just updated the contents of a
6852 ** valid conch file), try to match the permissions of the database
6853 */
6854 if( rc==SQLITE_OK && createConch ){
6855 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006856 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006857 if( err==0 ){
6858 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6859 S_IROTH|S_IWOTH);
6860 /* try to match the database file R/W permissions, ignore failure */
6861#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006862 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006863#else
drhff812312011-02-23 13:33:46 +00006864 do{
drhe562be52011-03-02 18:01:10 +00006865 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006866 }while( rc==(-1) && errno==EINTR );
6867 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006868 int code = errno;
6869 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6870 cmode, code, strerror(code));
6871 } else {
6872 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6873 }
6874 }else{
6875 int code = errno;
6876 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6877 err, code, strerror(code));
6878#endif
6879 }
drh715ff302008-12-03 22:32:44 +00006880 }
6881 }
drh7ed97b92010-01-20 13:07:21 +00006882 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6883
6884 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006885 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006886 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006887 int fd;
drh7ed97b92010-01-20 13:07:21 +00006888 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006889 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006890 }
6891 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006892 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006893 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006894 if( fd>=0 ){
6895 pFile->h = fd;
6896 }else{
drh9978c972010-02-23 17:36:32 +00006897 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006898 during locking */
6899 }
6900 }
6901 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6902 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6903 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6904 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6905 /* we couldn't create the proxy lock file with the old lock file path
6906 ** so try again via auto-naming
6907 */
6908 forceNewLockPath = 1;
6909 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006910 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006911 }
6912 }
6913 if( rc==SQLITE_OK ){
6914 /* Need to make a copy of path if we extracted the value
6915 ** from the conch file or the path was allocated on the stack
6916 */
6917 if( tempLockPath ){
6918 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6919 if( !pCtx->lockProxyPath ){
6920 rc = SQLITE_NOMEM;
6921 }
6922 }
6923 }
6924 if( rc==SQLITE_OK ){
6925 pCtx->conchHeld = 1;
6926
6927 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6928 afpLockingContext *afpCtx;
6929 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6930 afpCtx->dbPath = pCtx->lockProxyPath;
6931 }
6932 } else {
6933 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6934 }
drh308c2a52010-05-14 11:30:18 +00006935 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6936 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006937 return rc;
drh308c2a52010-05-14 11:30:18 +00006938 } while (1); /* in case we need to retry the :auto: lock file -
6939 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006940 }
6941}
6942
6943/*
6944** If pFile holds a lock on a conch file, then release that lock.
6945*/
6946static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006947 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006948 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6949 unixFile *conchFile; /* Name of the conch file */
6950
6951 pCtx = (proxyLockingContext *)pFile->lockingContext;
6952 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006953 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006954 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006955 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006956 if( pCtx->conchHeld>0 ){
6957 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6958 }
drh715ff302008-12-03 22:32:44 +00006959 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006960 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6961 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006962 return rc;
6963}
6964
6965/*
6966** Given the name of a database file, compute the name of its conch file.
6967** Store the conch filename in memory obtained from sqlite3_malloc().
6968** Make *pConchPath point to the new name. Return SQLITE_OK on success
6969** or SQLITE_NOMEM if unable to obtain memory.
6970**
6971** The caller is responsible for ensuring that the allocated memory
6972** space is eventually freed.
6973**
6974** *pConchPath is set to NULL if a memory allocation error occurs.
6975*/
6976static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6977 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006978 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006979 char *conchPath; /* buffer in which to construct conch name */
6980
6981 /* Allocate space for the conch filename and initialize the name to
6982 ** the name of the original database file. */
6983 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6984 if( conchPath==0 ){
6985 return SQLITE_NOMEM;
6986 }
6987 memcpy(conchPath, dbPath, len+1);
6988
6989 /* now insert a "." before the last / character */
6990 for( i=(len-1); i>=0; i-- ){
6991 if( conchPath[i]=='/' ){
6992 i++;
6993 break;
6994 }
6995 }
6996 conchPath[i]='.';
6997 while ( i<len ){
6998 conchPath[i+1]=dbPath[i];
6999 i++;
7000 }
7001
7002 /* append the "-conch" suffix to the file */
7003 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007004 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007005
7006 return SQLITE_OK;
7007}
7008
7009
7010/* Takes a fully configured proxy locking-style unix file and switches
7011** the local lock file path
7012*/
7013static int switchLockProxyPath(unixFile *pFile, const char *path) {
7014 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7015 char *oldPath = pCtx->lockProxyPath;
7016 int rc = SQLITE_OK;
7017
drh308c2a52010-05-14 11:30:18 +00007018 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007019 return SQLITE_BUSY;
7020 }
7021
7022 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7023 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7024 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7025 return SQLITE_OK;
7026 }else{
7027 unixFile *lockProxy = pCtx->lockProxy;
7028 pCtx->lockProxy=NULL;
7029 pCtx->conchHeld = 0;
7030 if( lockProxy!=NULL ){
7031 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7032 if( rc ) return rc;
7033 sqlite3_free(lockProxy);
7034 }
7035 sqlite3_free(oldPath);
7036 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7037 }
7038
7039 return rc;
7040}
7041
7042/*
7043** pFile is a file that has been opened by a prior xOpen call. dbPath
7044** is a string buffer at least MAXPATHLEN+1 characters in size.
7045**
7046** This routine find the filename associated with pFile and writes it
7047** int dbPath.
7048*/
7049static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007050#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007051 if( pFile->pMethod == &afpIoMethods ){
7052 /* afp style keeps a reference to the db path in the filePath field
7053 ** of the struct */
drhea678832008-12-10 19:26:22 +00007054 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007055 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7056 } else
drh715ff302008-12-03 22:32:44 +00007057#endif
7058 if( pFile->pMethod == &dotlockIoMethods ){
7059 /* dot lock style uses the locking context to store the dot lock
7060 ** file path */
7061 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7062 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7063 }else{
7064 /* all other styles use the locking context to store the db file path */
7065 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007066 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007067 }
7068 return SQLITE_OK;
7069}
7070
7071/*
7072** Takes an already filled in unix file and alters it so all file locking
7073** will be performed on the local proxy lock file. The following fields
7074** are preserved in the locking context so that they can be restored and
7075** the unix structure properly cleaned up at close time:
7076** ->lockingContext
7077** ->pMethod
7078*/
7079static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7080 proxyLockingContext *pCtx;
7081 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7082 char *lockPath=NULL;
7083 int rc = SQLITE_OK;
7084
drh308c2a52010-05-14 11:30:18 +00007085 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007086 return SQLITE_BUSY;
7087 }
7088 proxyGetDbPathForUnixFile(pFile, dbPath);
7089 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7090 lockPath=NULL;
7091 }else{
7092 lockPath=(char *)path;
7093 }
7094
drh308c2a52010-05-14 11:30:18 +00007095 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7096 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007097
7098 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7099 if( pCtx==0 ){
7100 return SQLITE_NOMEM;
7101 }
7102 memset(pCtx, 0, sizeof(*pCtx));
7103
7104 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7105 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007106 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7107 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7108 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7109 ** (c) the file system is read-only, then enable no-locking access.
7110 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7111 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7112 */
7113 struct statfs fsInfo;
7114 struct stat conchInfo;
7115 int goLockless = 0;
7116
drh99ab3b12011-03-02 15:09:07 +00007117 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007118 int err = errno;
7119 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7120 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7121 }
7122 }
7123 if( goLockless ){
7124 pCtx->conchHeld = -1; /* read only FS/ lockless */
7125 rc = SQLITE_OK;
7126 }
7127 }
drh715ff302008-12-03 22:32:44 +00007128 }
7129 if( rc==SQLITE_OK && lockPath ){
7130 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7131 }
7132
7133 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007134 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7135 if( pCtx->dbPath==NULL ){
7136 rc = SQLITE_NOMEM;
7137 }
7138 }
7139 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007140 /* all memory is allocated, proxys are created and assigned,
7141 ** switch the locking context and pMethod then return.
7142 */
drh715ff302008-12-03 22:32:44 +00007143 pCtx->oldLockingContext = pFile->lockingContext;
7144 pFile->lockingContext = pCtx;
7145 pCtx->pOldMethod = pFile->pMethod;
7146 pFile->pMethod = &proxyIoMethods;
7147 }else{
7148 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007149 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007150 sqlite3_free(pCtx->conchFile);
7151 }
drhd56b1212010-08-11 06:14:15 +00007152 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007153 sqlite3_free(pCtx->conchFilePath);
7154 sqlite3_free(pCtx);
7155 }
drh308c2a52010-05-14 11:30:18 +00007156 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7157 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007158 return rc;
7159}
7160
7161
7162/*
7163** This routine handles sqlite3_file_control() calls that are specific
7164** to proxy locking.
7165*/
7166static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7167 switch( op ){
7168 case SQLITE_GET_LOCKPROXYFILE: {
7169 unixFile *pFile = (unixFile*)id;
7170 if( pFile->pMethod == &proxyIoMethods ){
7171 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7172 proxyTakeConch(pFile);
7173 if( pCtx->lockProxyPath ){
7174 *(const char **)pArg = pCtx->lockProxyPath;
7175 }else{
7176 *(const char **)pArg = ":auto: (not held)";
7177 }
7178 } else {
7179 *(const char **)pArg = NULL;
7180 }
7181 return SQLITE_OK;
7182 }
7183 case SQLITE_SET_LOCKPROXYFILE: {
7184 unixFile *pFile = (unixFile*)id;
7185 int rc = SQLITE_OK;
7186 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7187 if( pArg==NULL || (const char *)pArg==0 ){
7188 if( isProxyStyle ){
7189 /* turn off proxy locking - not supported */
7190 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7191 }else{
7192 /* turn off proxy locking - already off - NOOP */
7193 rc = SQLITE_OK;
7194 }
7195 }else{
7196 const char *proxyPath = (const char *)pArg;
7197 if( isProxyStyle ){
7198 proxyLockingContext *pCtx =
7199 (proxyLockingContext*)pFile->lockingContext;
7200 if( !strcmp(pArg, ":auto:")
7201 || (pCtx->lockProxyPath &&
7202 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7203 ){
7204 rc = SQLITE_OK;
7205 }else{
7206 rc = switchLockProxyPath(pFile, proxyPath);
7207 }
7208 }else{
7209 /* turn on proxy file locking */
7210 rc = proxyTransformUnixFile(pFile, proxyPath);
7211 }
7212 }
7213 return rc;
7214 }
7215 default: {
7216 assert( 0 ); /* The call assures that only valid opcodes are sent */
7217 }
7218 }
7219 /*NOTREACHED*/
7220 return SQLITE_ERROR;
7221}
7222
7223/*
7224** Within this division (the proxying locking implementation) the procedures
7225** above this point are all utilities. The lock-related methods of the
7226** proxy-locking sqlite3_io_method object follow.
7227*/
7228
7229
7230/*
7231** This routine checks if there is a RESERVED lock held on the specified
7232** file by this or any other process. If such a lock is held, set *pResOut
7233** to a non-zero value otherwise *pResOut is set to zero. The return value
7234** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7235*/
7236static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7237 unixFile *pFile = (unixFile*)id;
7238 int rc = proxyTakeConch(pFile);
7239 if( rc==SQLITE_OK ){
7240 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007241 if( pCtx->conchHeld>0 ){
7242 unixFile *proxy = pCtx->lockProxy;
7243 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7244 }else{ /* conchHeld < 0 is lockless */
7245 pResOut=0;
7246 }
drh715ff302008-12-03 22:32:44 +00007247 }
7248 return rc;
7249}
7250
7251/*
drh308c2a52010-05-14 11:30:18 +00007252** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007253** of the following:
7254**
7255** (1) SHARED_LOCK
7256** (2) RESERVED_LOCK
7257** (3) PENDING_LOCK
7258** (4) EXCLUSIVE_LOCK
7259**
7260** Sometimes when requesting one lock state, additional lock states
7261** are inserted in between. The locking might fail on one of the later
7262** transitions leaving the lock state different from what it started but
7263** still short of its goal. The following chart shows the allowed
7264** transitions and the inserted intermediate states:
7265**
7266** UNLOCKED -> SHARED
7267** SHARED -> RESERVED
7268** SHARED -> (PENDING) -> EXCLUSIVE
7269** RESERVED -> (PENDING) -> EXCLUSIVE
7270** PENDING -> EXCLUSIVE
7271**
7272** This routine will only increase a lock. Use the sqlite3OsUnlock()
7273** routine to lower a locking level.
7274*/
drh308c2a52010-05-14 11:30:18 +00007275static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007276 unixFile *pFile = (unixFile*)id;
7277 int rc = proxyTakeConch(pFile);
7278 if( rc==SQLITE_OK ){
7279 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007280 if( pCtx->conchHeld>0 ){
7281 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007282 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7283 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007284 }else{
7285 /* conchHeld < 0 is lockless */
7286 }
drh715ff302008-12-03 22:32:44 +00007287 }
7288 return rc;
7289}
7290
7291
7292/*
drh308c2a52010-05-14 11:30:18 +00007293** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007294** must be either NO_LOCK or SHARED_LOCK.
7295**
7296** If the locking level of the file descriptor is already at or below
7297** the requested locking level, this routine is a no-op.
7298*/
drh308c2a52010-05-14 11:30:18 +00007299static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007300 unixFile *pFile = (unixFile*)id;
7301 int rc = proxyTakeConch(pFile);
7302 if( rc==SQLITE_OK ){
7303 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007304 if( pCtx->conchHeld>0 ){
7305 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007306 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7307 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007308 }else{
7309 /* conchHeld < 0 is lockless */
7310 }
drh715ff302008-12-03 22:32:44 +00007311 }
7312 return rc;
7313}
7314
7315/*
7316** Close a file that uses proxy locks.
7317*/
7318static int proxyClose(sqlite3_file *id) {
7319 if( id ){
7320 unixFile *pFile = (unixFile*)id;
7321 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7322 unixFile *lockProxy = pCtx->lockProxy;
7323 unixFile *conchFile = pCtx->conchFile;
7324 int rc = SQLITE_OK;
7325
7326 if( lockProxy ){
7327 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7328 if( rc ) return rc;
7329 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7330 if( rc ) return rc;
7331 sqlite3_free(lockProxy);
7332 pCtx->lockProxy = 0;
7333 }
7334 if( conchFile ){
7335 if( pCtx->conchHeld ){
7336 rc = proxyReleaseConch(pFile);
7337 if( rc ) return rc;
7338 }
7339 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7340 if( rc ) return rc;
7341 sqlite3_free(conchFile);
7342 }
drhd56b1212010-08-11 06:14:15 +00007343 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007344 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007345 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007346 /* restore the original locking context and pMethod then close it */
7347 pFile->lockingContext = pCtx->oldLockingContext;
7348 pFile->pMethod = pCtx->pOldMethod;
7349 sqlite3_free(pCtx);
7350 return pFile->pMethod->xClose(id);
7351 }
7352 return SQLITE_OK;
7353}
7354
7355
7356
drhd2cb50b2009-01-09 21:41:17 +00007357#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007358/*
7359** The proxy locking style is intended for use with AFP filesystems.
7360** And since AFP is only supported on MacOSX, the proxy locking is also
7361** restricted to MacOSX.
7362**
7363**
7364******************* End of the proxy lock implementation **********************
7365******************************************************************************/
7366
drh734c9862008-11-28 15:37:20 +00007367/*
danielk1977e339d652008-06-28 11:23:00 +00007368** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007369**
7370** This routine registers all VFS implementations for unix-like operating
7371** systems. This routine, and the sqlite3_os_end() routine that follows,
7372** should be the only routines in this file that are visible from other
7373** files.
drh6b9d6dd2008-12-03 19:34:47 +00007374**
7375** This routine is called once during SQLite initialization and by a
7376** single thread. The memory allocation and mutex subsystems have not
7377** necessarily been initialized when this routine is called, and so they
7378** should not be used.
drh153c62c2007-08-24 03:51:33 +00007379*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007380int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007381 /*
7382 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007383 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7384 ** to the "finder" function. (pAppData is a pointer to a pointer because
7385 ** silly C90 rules prohibit a void* from being cast to a function pointer
7386 ** and so we have to go through the intermediate pointer to avoid problems
7387 ** when compiling with -pedantic-errors on GCC.)
7388 **
7389 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007390 ** finder-function. The finder-function returns a pointer to the
7391 ** sqlite_io_methods object that implements the desired locking
7392 ** behaviors. See the division above that contains the IOMETHODS
7393 ** macro for addition information on finder-functions.
7394 **
7395 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7396 ** object. But the "autolockIoFinder" available on MacOSX does a little
7397 ** more than that; it looks at the filesystem type that hosts the
7398 ** database file and tries to choose an locking method appropriate for
7399 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007400 */
drh7708e972008-11-29 00:56:52 +00007401 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007402 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007403 sizeof(unixFile), /* szOsFile */ \
7404 MAX_PATHNAME, /* mxPathname */ \
7405 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007406 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007407 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007408 unixOpen, /* xOpen */ \
7409 unixDelete, /* xDelete */ \
7410 unixAccess, /* xAccess */ \
7411 unixFullPathname, /* xFullPathname */ \
7412 unixDlOpen, /* xDlOpen */ \
7413 unixDlError, /* xDlError */ \
7414 unixDlSym, /* xDlSym */ \
7415 unixDlClose, /* xDlClose */ \
7416 unixRandomness, /* xRandomness */ \
7417 unixSleep, /* xSleep */ \
7418 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007419 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007420 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007421 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007422 unixGetSystemCall, /* xGetSystemCall */ \
7423 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007424 }
7425
drh6b9d6dd2008-12-03 19:34:47 +00007426 /*
7427 ** All default VFSes for unix are contained in the following array.
7428 **
7429 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7430 ** by the SQLite core when the VFS is registered. So the following
7431 ** array cannot be const.
7432 */
danielk1977e339d652008-06-28 11:23:00 +00007433 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007434#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007435 UNIXVFS("unix", autolockIoFinder ),
7436#else
7437 UNIXVFS("unix", posixIoFinder ),
7438#endif
7439 UNIXVFS("unix-none", nolockIoFinder ),
7440 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007441 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007442#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007443 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007444#endif
7445#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007446 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007447#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007448 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007449#endif
chw78a13182009-04-07 05:35:03 +00007450#endif
drhd2cb50b2009-01-09 21:41:17 +00007451#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007452 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007453 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007454 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007455#endif
drh153c62c2007-08-24 03:51:33 +00007456 };
drh6b9d6dd2008-12-03 19:34:47 +00007457 unsigned int i; /* Loop counter */
7458
drh2aa5a002011-04-13 13:42:25 +00007459 /* Double-check that the aSyscall[] array has been constructed
7460 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhd1ab8062013-03-25 20:50:25 +00007461 assert( ArraySize(aSyscall)==24 );
drh2aa5a002011-04-13 13:42:25 +00007462
drh6b9d6dd2008-12-03 19:34:47 +00007463 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007464 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007465 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007466 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007467 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007468}
danielk1977e339d652008-06-28 11:23:00 +00007469
7470/*
drh6b9d6dd2008-12-03 19:34:47 +00007471** Shutdown the operating system interface.
7472**
7473** Some operating systems might need to do some cleanup in this routine,
7474** to release dynamically allocated objects. But not on unix.
7475** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007476*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007477int sqlite3_os_end(void){
7478 return SQLITE_OK;
7479}
drhdce8bdb2007-08-16 13:01:44 +00007480
danielk197729bafea2008-06-26 10:41:19 +00007481#endif /* SQLITE_OS_UNIX */