blob: ef6cba910aa5e31287d6a8008b32a28b52878269 [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** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
drh1da88f02011-12-17 16:09:16 +0000125
danielk1977e339d652008-06-28 11:23:00 +0000126
drh40bbb0a2008-09-23 10:23:26 +0000127#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000129# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <semaphore.h>
131# include <limits.h>
132# else
drh9b35ea62008-11-29 02:20:26 +0000133# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000135# endif
drhbfe66312006-10-03 17:40:40 +0000136#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000137
drhf8b4d8c2010-03-05 13:53:22 +0000138#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000139# include <sys/mount.h>
140#endif
141
drhdbe4b882011-06-20 18:00:17 +0000142#ifdef HAVE_UTIME
143# include <utime.h>
144#endif
145
drh9cbe6352005-11-29 03:13:21 +0000146/*
drh7ed97b92010-01-20 13:07:21 +0000147** Allowed values of unixFile.fsFlags
148*/
149#define SQLITE_FSFLAGS_IS_MSDOS 0x1
150
151/*
drhf1a221e2006-01-15 17:27:17 +0000152** If we are to be thread-safe, include the pthreads header and define
153** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000154*/
drhd677b3d2007-08-20 22:48:41 +0000155#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000156# include <pthread.h>
157# define SQLITE_UNIX_THREADS 1
158#endif
159
160/*
161** Default permissions when creating a new file
162*/
163#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
164# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
165#endif
166
danielk1977b4b47412007-08-17 15:53:36 +0000167/*
aswiftaebf4132008-11-21 00:10:35 +0000168 ** Default permissions when creating auto proxy dir
169 */
170#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
171# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
172#endif
173
174/*
danielk1977b4b47412007-08-17 15:53:36 +0000175** Maximum supported path-length.
176*/
177#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000178
drh734c9862008-11-28 15:37:20 +0000179/*
drh734c9862008-11-28 15:37:20 +0000180** Only set the lastErrno if the error code is a real error and not
181** a normal expected return code of SQLITE_BUSY or SQLITE_OK
182*/
183#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
184
drhd91c68f2010-05-14 14:52:25 +0000185/* Forward references */
186typedef struct unixShm unixShm; /* Connection shared memory */
187typedef struct unixShmNode unixShmNode; /* Shared memory instance */
188typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
189typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000190
191/*
dane946c392009-08-22 11:39:46 +0000192** Sometimes, after a file handle is closed by SQLite, the file descriptor
193** cannot be closed immediately. In these cases, instances of the following
194** structure are used to store the file descriptor while waiting for an
195** opportunity to either close or reuse it.
196*/
dane946c392009-08-22 11:39:46 +0000197struct UnixUnusedFd {
198 int fd; /* File descriptor to close */
199 int flags; /* Flags this file descriptor was opened with */
200 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
201};
202
203/*
drh9b35ea62008-11-29 02:20:26 +0000204** The unixFile structure is subclass of sqlite3_file specific to the unix
205** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000206*/
drh054889e2005-11-30 03:20:31 +0000207typedef struct unixFile unixFile;
208struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000209 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000210 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000211 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000212 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000213 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000214 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000215 int lastErrno; /* The unix errno from last I/O error */
216 void *lockingContext; /* Locking style specific state */
217 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000218 const char *zPath; /* Name of the file */
219 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000220 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000221#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000222 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000223#endif
drh7ed97b92010-01-20 13:07:21 +0000224#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000225 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000226#endif
227#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000228 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000229#endif
drh8f941bc2009-01-14 23:03:40 +0000230#ifndef NDEBUG
231 /* The next group of variables are used to track whether or not the
232 ** transaction counter in bytes 24-27 of database files are updated
233 ** whenever any part of the database changes. An assertion fault will
234 ** occur if a file is updated without also updating the transaction
235 ** counter. This test is made to avoid new problems similar to the
236 ** one described by ticket #3584.
237 */
238 unsigned char transCntrChng; /* True if the transaction counter changed */
239 unsigned char dbUpdate; /* True if any part of database file changed */
240 unsigned char inNormalWrite; /* True if in a normal write operation */
241#endif
danielk1977967a4a12007-08-20 14:23:44 +0000242#ifdef SQLITE_TEST
243 /* In test mode, increase the size of this structure a bit so that
244 ** it is larger than the struct CrashFile defined in test6.c.
245 */
246 char aPadding[32];
247#endif
drh9cbe6352005-11-29 03:13:21 +0000248};
249
drh0ccebe72005-06-07 22:22:50 +0000250/*
drha7e61d82011-03-12 17:02:57 +0000251** Allowed values for the unixFile.ctrlFlags bitmask:
252*/
drhf0b190d2011-07-26 16:03:07 +0000253#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
254#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
255#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000256#ifndef SQLITE_DISABLE_DIRSYNC
257# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
258#else
259# define UNIXFILE_DIRSYNC 0x00
260#endif
drhcb15f352011-12-23 01:04:17 +0000261#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000262#define UNIXFILE_DELETE 0x20 /* Delete on close */
263#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
264#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drh3ee34842012-02-11 21:21:17 +0000265#define UNIXFILE_CHOWN 0x100 /* File ownership was changed */
drha7e61d82011-03-12 17:02:57 +0000266
267/*
drh198bf392006-01-06 21:52:49 +0000268** Include code that is common to all os_*.c files
269*/
270#include "os_common.h"
271
272/*
drh0ccebe72005-06-07 22:22:50 +0000273** Define various macros that are missing from some systems.
274*/
drhbbd42a62004-05-22 17:41:58 +0000275#ifndef O_LARGEFILE
276# define O_LARGEFILE 0
277#endif
278#ifdef SQLITE_DISABLE_LFS
279# undef O_LARGEFILE
280# define O_LARGEFILE 0
281#endif
282#ifndef O_NOFOLLOW
283# define O_NOFOLLOW 0
284#endif
285#ifndef O_BINARY
286# define O_BINARY 0
287#endif
288
289/*
drh2b4b5962005-06-15 17:47:55 +0000290** The threadid macro resolves to the thread-id or to 0. Used for
291** testing and debugging only.
292*/
drhd677b3d2007-08-20 22:48:41 +0000293#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000294#define threadid pthread_self()
295#else
296#define threadid 0
297#endif
298
drh99ab3b12011-03-02 15:09:07 +0000299/*
drh9a3baf12011-04-25 18:01:27 +0000300** Different Unix systems declare open() in different ways. Same use
301** open(const char*,int,mode_t). Others use open(const char*,int,...).
302** The difference is important when using a pointer to the function.
303**
304** The safest way to deal with the problem is to always use this wrapper
305** which always has the same well-defined interface.
306*/
307static int posixOpen(const char *zFile, int flags, int mode){
308 return open(zFile, flags, mode);
309}
310
drh90315a22011-08-10 01:52:12 +0000311/* Forward reference */
312static int openDirectory(const char*, int*);
313
drh9a3baf12011-04-25 18:01:27 +0000314/*
drh99ab3b12011-03-02 15:09:07 +0000315** Many system calls are accessed through pointer-to-functions so that
316** they may be overridden at runtime to facilitate fault injection during
317** testing and sandboxing. The following array holds the names and pointers
318** to all overrideable system calls.
319*/
320static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000321 const char *zName; /* Name of the sytem call */
322 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
323 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000324} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000325 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
326#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000327
drh58ad5802011-03-23 22:02:23 +0000328 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000329#define osClose ((int(*)(int))aSyscall[1].pCurrent)
330
drh58ad5802011-03-23 22:02:23 +0000331 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000332#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
333
drh58ad5802011-03-23 22:02:23 +0000334 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000335#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
336
drh58ad5802011-03-23 22:02:23 +0000337 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000338#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
339
340/*
341** The DJGPP compiler environment looks mostly like Unix, but it
342** lacks the fcntl() system call. So redefine fcntl() to be something
343** that always succeeds. This means that locking does not occur under
344** DJGPP. But it is DOS - what did you expect?
345*/
346#ifdef __DJGPP__
347 { "fstat", 0, 0 },
348#define osFstat(a,b,c) 0
349#else
drh58ad5802011-03-23 22:02:23 +0000350 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
352#endif
353
drh58ad5802011-03-23 22:02:23 +0000354 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000355#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
356
drh58ad5802011-03-23 22:02:23 +0000357 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000358#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000359
drh58ad5802011-03-23 22:02:23 +0000360 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000361#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
362
drhd4a80312011-04-15 14:33:20 +0000363#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000364 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000365#else
drh58ad5802011-03-23 22:02:23 +0000366 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000367#endif
368#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
369
370#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000371 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000372#else
drh58ad5802011-03-23 22:02:23 +0000373 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000374#endif
375#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
376
drh58ad5802011-03-23 22:02:23 +0000377 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000378#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
379
drhd4a80312011-04-15 14:33:20 +0000380#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000381 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000384#endif
385#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
386 aSyscall[12].pCurrent)
387
388#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000389 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000390#else
drh58ad5802011-03-23 22:02:23 +0000391 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000392#endif
393#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
394 aSyscall[13].pCurrent)
395
drha6c47492011-04-11 18:35:09 +0000396#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000398#else
399 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000400#endif
drh2aa5a002011-04-13 13:42:25 +0000401#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000402
403#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000404 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
dan0fd7d862011-03-29 10:04:23 +0000408#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000409
drh036ac7f2011-08-08 23:18:05 +0000410 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
411#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
412
drh90315a22011-08-10 01:52:12 +0000413 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
414#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
415
drh9ef6bc42011-11-04 02:24:02 +0000416 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
417#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
418
419 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
420#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
421
drh23c4b972012-02-11 23:55:15 +0000422 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000423#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000424
drh8c815d12012-02-13 20:16:37 +0000425 { "umask", (sqlite3_syscall_ptr)umask, 0 },
426#define osUmask ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
427
drhe562be52011-03-02 18:01:10 +0000428}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000429
430/*
431** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000432** "unix" VFSes. Return SQLITE_OK opon successfully updating the
433** system call pointer, or SQLITE_NOTFOUND if there is no configurable
434** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000435*/
436static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000437 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
438 const char *zName, /* Name of system call to override */
439 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000440){
drh58ad5802011-03-23 22:02:23 +0000441 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000442 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000443
444 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000445 if( zName==0 ){
446 /* If no zName is given, restore all system calls to their default
447 ** settings and return NULL
448 */
dan51438a72011-04-02 17:00:47 +0000449 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000450 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
451 if( aSyscall[i].pDefault ){
452 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000453 }
454 }
455 }else{
456 /* If zName is specified, operate on only the one system call
457 ** specified.
458 */
459 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
460 if( strcmp(zName, aSyscall[i].zName)==0 ){
461 if( aSyscall[i].pDefault==0 ){
462 aSyscall[i].pDefault = aSyscall[i].pCurrent;
463 }
drh1df30962011-03-02 19:06:42 +0000464 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000465 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
466 aSyscall[i].pCurrent = pNewFunc;
467 break;
468 }
469 }
470 }
471 return rc;
472}
473
drh1df30962011-03-02 19:06:42 +0000474/*
475** Return the value of a system call. Return NULL if zName is not a
476** recognized system call name. NULL is also returned if the system call
477** is currently undefined.
478*/
drh58ad5802011-03-23 22:02:23 +0000479static sqlite3_syscall_ptr unixGetSystemCall(
480 sqlite3_vfs *pNotUsed,
481 const char *zName
482){
483 unsigned int i;
484
485 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000486 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
487 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
488 }
489 return 0;
490}
491
492/*
493** Return the name of the first system call after zName. If zName==NULL
494** then return the name of the first system call. Return NULL if zName
495** is the last system call or if zName is not the name of a valid
496** system call.
497*/
498static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000499 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000500
501 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000502 if( zName ){
503 for(i=0; i<ArraySize(aSyscall)-1; i++){
504 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000505 }
506 }
dan0fd7d862011-03-29 10:04:23 +0000507 for(i++; i<ArraySize(aSyscall); i++){
508 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000509 }
510 return 0;
511}
512
drhad4f1e52011-03-04 15:43:57 +0000513/*
drh8c815d12012-02-13 20:16:37 +0000514** Invoke open(). Do so multiple times, until it either succeeds or
515** files for some reason other than EINTR.
516**
517** If the file creation mode "m" is 0 then set it to the default for
518** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
519** 0644) as modified by the system umask. If m is not 0, then
520** make the file creation mode be exactly m ignoring the umask.
521**
522** The m parameter will be non-zero only when creating -wal, -journal,
523** and -shm files. We want those files to have *exactly* the same
524** permissions as their original database, unadulterated by the umask.
525** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
526** transaction crashes and leaves behind hot journals, then any
527** process that is able to write to the database will also be able to
528** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000529*/
drh8c815d12012-02-13 20:16:37 +0000530static int robust_open(const char *z, int f, mode_t m){
drhad4f1e52011-03-04 15:43:57 +0000531 int rc;
drh8c815d12012-02-13 20:16:37 +0000532 mode_t m2;
533 mode_t origM;
534 if( m==0 ){
535 m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
536 }else{
537 m2 = m;
538 origM = osUmask(0);
539 }
540 do{ rc = osOpen(z,f,m2); }while( rc<0 && errno==EINTR );
541 if( m ){
542 osUmask(origM);
543 }
drhad4f1e52011-03-04 15:43:57 +0000544 return rc;
545}
danielk197713adf8a2004-06-03 16:08:41 +0000546
drh107886a2008-11-21 22:21:50 +0000547/*
dan9359c7b2009-08-21 08:29:10 +0000548** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000549** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000550** vxworksFileId objects used by this file, all of which may be
551** shared by multiple threads.
552**
553** Function unixMutexHeld() is used to assert() that the global mutex
554** is held when required. This function is only used as part of assert()
555** statements. e.g.
556**
557** unixEnterMutex()
558** assert( unixMutexHeld() );
559** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000560*/
561static void unixEnterMutex(void){
562 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
563}
564static void unixLeaveMutex(void){
565 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
566}
dan9359c7b2009-08-21 08:29:10 +0000567#ifdef SQLITE_DEBUG
568static int unixMutexHeld(void) {
569 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
570}
571#endif
drh107886a2008-11-21 22:21:50 +0000572
drh734c9862008-11-28 15:37:20 +0000573
drh30ddce62011-10-15 00:16:30 +0000574#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000575/*
576** Helper function for printing out trace information from debugging
577** binaries. This returns the string represetation of the supplied
578** integer lock-type.
579*/
drh308c2a52010-05-14 11:30:18 +0000580static const char *azFileLock(int eFileLock){
581 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000582 case NO_LOCK: return "NONE";
583 case SHARED_LOCK: return "SHARED";
584 case RESERVED_LOCK: return "RESERVED";
585 case PENDING_LOCK: return "PENDING";
586 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000587 }
588 return "ERROR";
589}
590#endif
591
592#ifdef SQLITE_LOCK_TRACE
593/*
594** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000595**
drh734c9862008-11-28 15:37:20 +0000596** This routine is used for troubleshooting locks on multithreaded
597** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
598** command-line option on the compiler. This code is normally
599** turned off.
600*/
601static int lockTrace(int fd, int op, struct flock *p){
602 char *zOpName, *zType;
603 int s;
604 int savedErrno;
605 if( op==F_GETLK ){
606 zOpName = "GETLK";
607 }else if( op==F_SETLK ){
608 zOpName = "SETLK";
609 }else{
drh99ab3b12011-03-02 15:09:07 +0000610 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000611 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
612 return s;
613 }
614 if( p->l_type==F_RDLCK ){
615 zType = "RDLCK";
616 }else if( p->l_type==F_WRLCK ){
617 zType = "WRLCK";
618 }else if( p->l_type==F_UNLCK ){
619 zType = "UNLCK";
620 }else{
621 assert( 0 );
622 }
623 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000624 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000625 savedErrno = errno;
626 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
627 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
628 (int)p->l_pid, s);
629 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
630 struct flock l2;
631 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000632 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000633 if( l2.l_type==F_RDLCK ){
634 zType = "RDLCK";
635 }else if( l2.l_type==F_WRLCK ){
636 zType = "WRLCK";
637 }else if( l2.l_type==F_UNLCK ){
638 zType = "UNLCK";
639 }else{
640 assert( 0 );
641 }
642 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
643 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
644 }
645 errno = savedErrno;
646 return s;
647}
drh99ab3b12011-03-02 15:09:07 +0000648#undef osFcntl
649#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000650#endif /* SQLITE_LOCK_TRACE */
651
drhff812312011-02-23 13:33:46 +0000652/*
653** Retry ftruncate() calls that fail due to EINTR
654*/
drhff812312011-02-23 13:33:46 +0000655static int robust_ftruncate(int h, sqlite3_int64 sz){
656 int rc;
drh99ab3b12011-03-02 15:09:07 +0000657 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000658 return rc;
659}
drh734c9862008-11-28 15:37:20 +0000660
661/*
662** This routine translates a standard POSIX errno code into something
663** useful to the clients of the sqlite3 functions. Specifically, it is
664** intended to translate a variety of "try again" errors into SQLITE_BUSY
665** and a variety of "please close the file descriptor NOW" errors into
666** SQLITE_IOERR
667**
668** Errors during initialization of locks, or file system support for locks,
669** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
670*/
671static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
672 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000673#if 0
674 /* At one point this code was not commented out. In theory, this branch
675 ** should never be hit, as this function should only be called after
676 ** a locking-related function (i.e. fcntl()) has returned non-zero with
677 ** the value of errno as the first argument. Since a system call has failed,
678 ** errno should be non-zero.
679 **
680 ** Despite this, if errno really is zero, we still don't want to return
681 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
682 ** propagated back to the caller. Commenting this branch out means errno==0
683 ** will be handled by the "default:" case below.
684 */
drh734c9862008-11-28 15:37:20 +0000685 case 0:
686 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000687#endif
688
drh734c9862008-11-28 15:37:20 +0000689 case EAGAIN:
690 case ETIMEDOUT:
691 case EBUSY:
692 case EINTR:
693 case ENOLCK:
694 /* random NFS retry error, unless during file system support
695 * introspection, in which it actually means what it says */
696 return SQLITE_BUSY;
697
698 case EACCES:
699 /* EACCES is like EAGAIN during locking operations, but not any other time*/
700 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
701 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
702 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
703 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
704 return SQLITE_BUSY;
705 }
706 /* else fall through */
707 case EPERM:
708 return SQLITE_PERM;
709
danea83bc62011-04-01 11:56:32 +0000710 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
711 ** this module never makes such a call. And the code in SQLite itself
712 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
713 ** this case is also commented out. If the system does set errno to EDEADLK,
714 ** the default SQLITE_IOERR_XXX code will be returned. */
715#if 0
drh734c9862008-11-28 15:37:20 +0000716 case EDEADLK:
717 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000718#endif
drh734c9862008-11-28 15:37:20 +0000719
720#if EOPNOTSUPP!=ENOTSUP
721 case EOPNOTSUPP:
722 /* something went terribly awry, unless during file system support
723 * introspection, in which it actually means what it says */
724#endif
725#ifdef ENOTSUP
726 case ENOTSUP:
727 /* invalid fd, unless during file system support introspection, in which
728 * it actually means what it says */
729#endif
730 case EIO:
731 case EBADF:
732 case EINVAL:
733 case ENOTCONN:
734 case ENODEV:
735 case ENXIO:
736 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000737#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000738 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000739#endif
drh734c9862008-11-28 15:37:20 +0000740 case ENOSYS:
741 /* these should force the client to close the file and reconnect */
742
743 default:
744 return sqliteIOErr;
745 }
746}
747
748
749
750/******************************************************************************
751****************** Begin Unique File ID Utility Used By VxWorks ***************
752**
753** On most versions of unix, we can get a unique ID for a file by concatenating
754** the device number and the inode number. But this does not work on VxWorks.
755** On VxWorks, a unique file id must be based on the canonical filename.
756**
757** A pointer to an instance of the following structure can be used as a
758** unique file ID in VxWorks. Each instance of this structure contains
759** a copy of the canonical filename. There is also a reference count.
760** The structure is reclaimed when the number of pointers to it drops to
761** zero.
762**
763** There are never very many files open at one time and lookups are not
764** a performance-critical path, so it is sufficient to put these
765** structures on a linked list.
766*/
767struct vxworksFileId {
768 struct vxworksFileId *pNext; /* Next in a list of them all */
769 int nRef; /* Number of references to this one */
770 int nName; /* Length of the zCanonicalName[] string */
771 char *zCanonicalName; /* Canonical filename */
772};
773
774#if OS_VXWORKS
775/*
drh9b35ea62008-11-29 02:20:26 +0000776** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000777** variable:
778*/
779static struct vxworksFileId *vxworksFileList = 0;
780
781/*
782** Simplify a filename into its canonical form
783** by making the following changes:
784**
785** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000786** * convert /./ into just /
787** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000788**
789** Changes are made in-place. Return the new name length.
790**
791** The original filename is in z[0..n-1]. Return the number of
792** characters in the simplified name.
793*/
794static int vxworksSimplifyName(char *z, int n){
795 int i, j;
796 while( n>1 && z[n-1]=='/' ){ n--; }
797 for(i=j=0; i<n; i++){
798 if( z[i]=='/' ){
799 if( z[i+1]=='/' ) continue;
800 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
801 i += 1;
802 continue;
803 }
804 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
805 while( j>0 && z[j-1]!='/' ){ j--; }
806 if( j>0 ){ j--; }
807 i += 2;
808 continue;
809 }
810 }
811 z[j++] = z[i];
812 }
813 z[j] = 0;
814 return j;
815}
816
817/*
818** Find a unique file ID for the given absolute pathname. Return
819** a pointer to the vxworksFileId object. This pointer is the unique
820** file ID.
821**
822** The nRef field of the vxworksFileId object is incremented before
823** the object is returned. A new vxworksFileId object is created
824** and added to the global list if necessary.
825**
826** If a memory allocation error occurs, return NULL.
827*/
828static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
829 struct vxworksFileId *pNew; /* search key and new file ID */
830 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
831 int n; /* Length of zAbsoluteName string */
832
833 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000834 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000835 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
836 if( pNew==0 ) return 0;
837 pNew->zCanonicalName = (char*)&pNew[1];
838 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
839 n = vxworksSimplifyName(pNew->zCanonicalName, n);
840
841 /* Search for an existing entry that matching the canonical name.
842 ** If found, increment the reference count and return a pointer to
843 ** the existing file ID.
844 */
845 unixEnterMutex();
846 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
847 if( pCandidate->nName==n
848 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
849 ){
850 sqlite3_free(pNew);
851 pCandidate->nRef++;
852 unixLeaveMutex();
853 return pCandidate;
854 }
855 }
856
857 /* No match was found. We will make a new file ID */
858 pNew->nRef = 1;
859 pNew->nName = n;
860 pNew->pNext = vxworksFileList;
861 vxworksFileList = pNew;
862 unixLeaveMutex();
863 return pNew;
864}
865
866/*
867** Decrement the reference count on a vxworksFileId object. Free
868** the object when the reference count reaches zero.
869*/
870static void vxworksReleaseFileId(struct vxworksFileId *pId){
871 unixEnterMutex();
872 assert( pId->nRef>0 );
873 pId->nRef--;
874 if( pId->nRef==0 ){
875 struct vxworksFileId **pp;
876 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
877 assert( *pp==pId );
878 *pp = pId->pNext;
879 sqlite3_free(pId);
880 }
881 unixLeaveMutex();
882}
883#endif /* OS_VXWORKS */
884/*************** End of Unique File ID Utility Used By VxWorks ****************
885******************************************************************************/
886
887
888/******************************************************************************
889*************************** Posix Advisory Locking ****************************
890**
drh9b35ea62008-11-29 02:20:26 +0000891** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000892** section 6.5.2.2 lines 483 through 490 specify that when a process
893** sets or clears a lock, that operation overrides any prior locks set
894** by the same process. It does not explicitly say so, but this implies
895** that it overrides locks set by the same process using a different
896** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000897**
898** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000899** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
900**
901** Suppose ./file1 and ./file2 are really the same file (because
902** one is a hard or symbolic link to the other) then if you set
903** an exclusive lock on fd1, then try to get an exclusive lock
904** on fd2, it works. I would have expected the second lock to
905** fail since there was already a lock on the file due to fd1.
906** But not so. Since both locks came from the same process, the
907** second overrides the first, even though they were on different
908** file descriptors opened on different file names.
909**
drh734c9862008-11-28 15:37:20 +0000910** This means that we cannot use POSIX locks to synchronize file access
911** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000912** to synchronize access for threads in separate processes, but not
913** threads within the same process.
914**
915** To work around the problem, SQLite has to manage file locks internally
916** on its own. Whenever a new database is opened, we have to find the
917** specific inode of the database file (the inode is determined by the
918** st_dev and st_ino fields of the stat structure that fstat() fills in)
919** and check for locks already existing on that inode. When locks are
920** created or removed, we have to look at our own internal record of the
921** locks to see if another thread has previously set a lock on that same
922** inode.
923**
drh9b35ea62008-11-29 02:20:26 +0000924** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
925** For VxWorks, we have to use the alternative unique ID system based on
926** canonical filename and implemented in the previous division.)
927**
danielk1977ad94b582007-08-20 06:44:22 +0000928** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000929** descriptor. It is now a structure that holds the integer file
930** descriptor and a pointer to a structure that describes the internal
931** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000932** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000933** point to the same locking structure. The locking structure keeps
934** a reference count (so we will know when to delete it) and a "cnt"
935** field that tells us its internal lock status. cnt==0 means the
936** file is unlocked. cnt==-1 means the file has an exclusive lock.
937** cnt>0 means there are cnt shared locks on the file.
938**
939** Any attempt to lock or unlock a file first checks the locking
940** structure. The fcntl() system call is only invoked to set a
941** POSIX lock if the internal lock structure transitions between
942** a locked and an unlocked state.
943**
drh734c9862008-11-28 15:37:20 +0000944** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000945**
946** If you close a file descriptor that points to a file that has locks,
947** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000948** released. To work around this problem, each unixInodeInfo object
949** maintains a count of the number of pending locks on tha inode.
950** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000951** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000952** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000953** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000954** be closed and that list is walked (and cleared) when the last lock
955** clears.
956**
drh9b35ea62008-11-29 02:20:26 +0000957** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000958**
drh9b35ea62008-11-29 02:20:26 +0000959** Many older versions of linux use the LinuxThreads library which is
960** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000961** A cannot be modified or overridden by a different thread B.
962** Only thread A can modify the lock. Locking behavior is correct
963** if the appliation uses the newer Native Posix Thread Library (NPTL)
964** on linux - with NPTL a lock created by thread A can override locks
965** in thread B. But there is no way to know at compile-time which
966** threading library is being used. So there is no way to know at
967** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000968** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000969** current process.
drh5fdae772004-06-29 03:29:00 +0000970**
drh8af6c222010-05-14 12:43:01 +0000971** SQLite used to support LinuxThreads. But support for LinuxThreads
972** was dropped beginning with version 3.7.0. SQLite will still work with
973** LinuxThreads provided that (1) there is no more than one connection
974** per database file in the same process and (2) database connections
975** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000976*/
977
978/*
979** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000980** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000981*/
982struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000983 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000984#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000985 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000986#else
drh107886a2008-11-21 22:21:50 +0000987 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000988#endif
989};
990
991/*
drhbbd42a62004-05-22 17:41:58 +0000992** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000993** inode. Or, on LinuxThreads, there is one of these structures for
994** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000995**
danielk1977ad94b582007-08-20 06:44:22 +0000996** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000997** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000998** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000999*/
drh8af6c222010-05-14 12:43:01 +00001000struct unixInodeInfo {
1001 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001002 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001003 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1004 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001005 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001006 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1007 int nLock; /* Number of outstanding file locks */
1008 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1009 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1010 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001011#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001012 unsigned long long sharedByte; /* for AFP simulated shared lock */
1013#endif
drh6c7d5c52008-11-21 20:32:33 +00001014#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001015 sem_t *pSem; /* Named POSIX semaphore */
1016 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001017#endif
drhbbd42a62004-05-22 17:41:58 +00001018};
1019
drhda0e7682008-07-30 15:27:54 +00001020/*
drh8af6c222010-05-14 12:43:01 +00001021** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001022*/
drhd91c68f2010-05-14 14:52:25 +00001023static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001024
drh5fdae772004-06-29 03:29:00 +00001025/*
dane18d4952011-02-21 11:46:24 +00001026**
1027** This function - unixLogError_x(), is only ever called via the macro
1028** unixLogError().
1029**
1030** It is invoked after an error occurs in an OS function and errno has been
1031** set. It logs a message using sqlite3_log() containing the current value of
1032** errno and, if possible, the human-readable equivalent from strerror() or
1033** strerror_r().
1034**
1035** The first argument passed to the macro should be the error code that
1036** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1037** The two subsequent arguments should be the name of the OS function that
1038** failed (e.g. "unlink", "open") and the the associated file-system path,
1039** if any.
1040*/
drh0e9365c2011-03-02 02:08:13 +00001041#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1042static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001043 int errcode, /* SQLite error code */
1044 const char *zFunc, /* Name of OS function that failed */
1045 const char *zPath, /* File path associated with error */
1046 int iLine /* Source line number where error occurred */
1047){
1048 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001049 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001050
1051 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1052 ** the strerror() function to obtain the human-readable error message
1053 ** equivalent to errno. Otherwise, use strerror_r().
1054 */
1055#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1056 char aErr[80];
1057 memset(aErr, 0, sizeof(aErr));
1058 zErr = aErr;
1059
1060 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1061 ** assume that the system provides the the GNU version of strerror_r() that
1062 ** returns a pointer to a buffer containing the error message. That pointer
1063 ** may point to aErr[], or it may point to some static storage somewhere.
1064 ** Otherwise, assume that the system provides the POSIX version of
1065 ** strerror_r(), which always writes an error message into aErr[].
1066 **
1067 ** If the code incorrectly assumes that it is the POSIX version that is
1068 ** available, the error message will often be an empty string. Not a
1069 ** huge problem. Incorrectly concluding that the GNU version is available
1070 ** could lead to a segfault though.
1071 */
1072#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1073 zErr =
1074# endif
drh0e9365c2011-03-02 02:08:13 +00001075 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001076
1077#elif SQLITE_THREADSAFE
1078 /* This is a threadsafe build, but strerror_r() is not available. */
1079 zErr = "";
1080#else
1081 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001082 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001083#endif
1084
1085 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001086 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001087 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001088 "os_unix.c:%d: (%d) %s(%s) - %s",
1089 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001090 );
1091
1092 return errcode;
1093}
1094
drh0e9365c2011-03-02 02:08:13 +00001095/*
1096** Close a file descriptor.
1097**
1098** We assume that close() almost always works, since it is only in a
1099** very sick application or on a very sick platform that it might fail.
1100** If it does fail, simply leak the file descriptor, but do log the
1101** error.
1102**
1103** Note that it is not safe to retry close() after EINTR since the
1104** file descriptor might have already been reused by another thread.
1105** So we don't even try to recover from an EINTR. Just log the error
1106** and move on.
1107*/
1108static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001109 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001110 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1111 pFile ? pFile->zPath : 0, lineno);
1112 }
1113}
dane18d4952011-02-21 11:46:24 +00001114
1115/*
danb0ac3e32010-06-16 10:55:42 +00001116** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001117*/
drh0e9365c2011-03-02 02:08:13 +00001118static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001119 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001120 UnixUnusedFd *p;
1121 UnixUnusedFd *pNext;
1122 for(p=pInode->pUnused; p; p=pNext){
1123 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001124 robust_close(pFile, p->fd, __LINE__);
1125 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001126 }
drh0e9365c2011-03-02 02:08:13 +00001127 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001128}
1129
1130/*
drh8af6c222010-05-14 12:43:01 +00001131** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001132**
1133** The mutex entered using the unixEnterMutex() function must be held
1134** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001135*/
danb0ac3e32010-06-16 10:55:42 +00001136static void releaseInodeInfo(unixFile *pFile){
1137 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001138 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001139 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001140 pInode->nRef--;
1141 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001142 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001143 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001144 if( pInode->pPrev ){
1145 assert( pInode->pPrev->pNext==pInode );
1146 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001147 }else{
drh8af6c222010-05-14 12:43:01 +00001148 assert( inodeList==pInode );
1149 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001150 }
drh8af6c222010-05-14 12:43:01 +00001151 if( pInode->pNext ){
1152 assert( pInode->pNext->pPrev==pInode );
1153 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001154 }
drh8af6c222010-05-14 12:43:01 +00001155 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001156 }
drhbbd42a62004-05-22 17:41:58 +00001157 }
1158}
1159
1160/*
drh8af6c222010-05-14 12:43:01 +00001161** Given a file descriptor, locate the unixInodeInfo object that
1162** describes that file descriptor. Create a new one if necessary. The
1163** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001164**
dan9359c7b2009-08-21 08:29:10 +00001165** The mutex entered using the unixEnterMutex() function must be held
1166** when this function is called.
1167**
drh6c7d5c52008-11-21 20:32:33 +00001168** Return an appropriate error code.
1169*/
drh8af6c222010-05-14 12:43:01 +00001170static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001171 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001172 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001173){
1174 int rc; /* System call return code */
1175 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001176 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1177 struct stat statbuf; /* Low-level file information */
1178 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001179
dan9359c7b2009-08-21 08:29:10 +00001180 assert( unixMutexHeld() );
1181
drh6c7d5c52008-11-21 20:32:33 +00001182 /* Get low-level information about the file that we can used to
1183 ** create a unique name for the file.
1184 */
1185 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001186 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001187 if( rc!=0 ){
1188 pFile->lastErrno = errno;
1189#ifdef EOVERFLOW
1190 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1191#endif
1192 return SQLITE_IOERR;
1193 }
1194
drheb0d74f2009-02-03 15:27:02 +00001195#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001196 /* On OS X on an msdos filesystem, the inode number is reported
1197 ** incorrectly for zero-size files. See ticket #3260. To work
1198 ** around this problem (we consider it a bug in OS X, not SQLite)
1199 ** we always increase the file size to 1 by writing a single byte
1200 ** prior to accessing the inode number. The one byte written is
1201 ** an ASCII 'S' character which also happens to be the first byte
1202 ** in the header of every SQLite database. In this way, if there
1203 ** is a race condition such that another thread has already populated
1204 ** the first page of the database, no damage is done.
1205 */
drh7ed97b92010-01-20 13:07:21 +00001206 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001207 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001208 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001209 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001210 return SQLITE_IOERR;
1211 }
drh99ab3b12011-03-02 15:09:07 +00001212 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001213 if( rc!=0 ){
1214 pFile->lastErrno = errno;
1215 return SQLITE_IOERR;
1216 }
1217 }
drheb0d74f2009-02-03 15:27:02 +00001218#endif
drh6c7d5c52008-11-21 20:32:33 +00001219
drh8af6c222010-05-14 12:43:01 +00001220 memset(&fileId, 0, sizeof(fileId));
1221 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001222#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001223 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001224#else
drh8af6c222010-05-14 12:43:01 +00001225 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001226#endif
drh8af6c222010-05-14 12:43:01 +00001227 pInode = inodeList;
1228 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1229 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001230 }
drh8af6c222010-05-14 12:43:01 +00001231 if( pInode==0 ){
1232 pInode = sqlite3_malloc( sizeof(*pInode) );
1233 if( pInode==0 ){
1234 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001235 }
drh8af6c222010-05-14 12:43:01 +00001236 memset(pInode, 0, sizeof(*pInode));
1237 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1238 pInode->nRef = 1;
1239 pInode->pNext = inodeList;
1240 pInode->pPrev = 0;
1241 if( inodeList ) inodeList->pPrev = pInode;
1242 inodeList = pInode;
1243 }else{
1244 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001245 }
drh8af6c222010-05-14 12:43:01 +00001246 *ppInode = pInode;
1247 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001248}
drh6c7d5c52008-11-21 20:32:33 +00001249
aswift5b1a2562008-08-22 00:22:35 +00001250
1251/*
danielk197713adf8a2004-06-03 16:08:41 +00001252** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001253** file by this or any other process. If such a lock is held, set *pResOut
1254** to a non-zero value otherwise *pResOut is set to zero. The return value
1255** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001256*/
danielk1977861f7452008-06-05 11:39:11 +00001257static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001258 int rc = SQLITE_OK;
1259 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001260 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001261
danielk1977861f7452008-06-05 11:39:11 +00001262 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1263
drh054889e2005-11-30 03:20:31 +00001264 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001265 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001266
1267 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001268 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001269 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001270 }
1271
drh2ac3ee92004-06-07 16:27:46 +00001272 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001273 */
danielk197709480a92009-02-09 05:32:32 +00001274#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001275 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001276 struct flock lock;
1277 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001278 lock.l_start = RESERVED_BYTE;
1279 lock.l_len = 1;
1280 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001281 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1282 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1283 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001284 } else if( lock.l_type!=F_UNLCK ){
1285 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001286 }
1287 }
danielk197709480a92009-02-09 05:32:32 +00001288#endif
danielk197713adf8a2004-06-03 16:08:41 +00001289
drh6c7d5c52008-11-21 20:32:33 +00001290 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001291 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001292
aswift5b1a2562008-08-22 00:22:35 +00001293 *pResOut = reserved;
1294 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001295}
1296
1297/*
drha7e61d82011-03-12 17:02:57 +00001298** Attempt to set a system-lock on the file pFile. The lock is
1299** described by pLock.
1300**
drh77197112011-03-15 19:08:48 +00001301** If the pFile was opened read/write from unix-excl, then the only lock
1302** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001303** the first time any lock is attempted. All subsequent system locking
1304** operations become no-ops. Locking operations still happen internally,
1305** in order to coordinate access between separate database connections
1306** within this process, but all of that is handled in memory and the
1307** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001308**
1309** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1310** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1311** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001312**
1313** Zero is returned if the call completes successfully, or -1 if a call
1314** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001315*/
1316static int unixFileLock(unixFile *pFile, struct flock *pLock){
1317 int rc;
drh3cb93392011-03-12 18:10:44 +00001318 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001319 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001320 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001321 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1322 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1323 ){
drh3cb93392011-03-12 18:10:44 +00001324 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001325 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001326 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001327 lock.l_whence = SEEK_SET;
1328 lock.l_start = SHARED_FIRST;
1329 lock.l_len = SHARED_SIZE;
1330 lock.l_type = F_WRLCK;
1331 rc = osFcntl(pFile->h, F_SETLK, &lock);
1332 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001333 pInode->bProcessLock = 1;
1334 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001335 }else{
1336 rc = 0;
1337 }
1338 }else{
1339 rc = osFcntl(pFile->h, F_SETLK, pLock);
1340 }
1341 return rc;
1342}
1343
1344/*
drh308c2a52010-05-14 11:30:18 +00001345** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001346** of the following:
1347**
drh2ac3ee92004-06-07 16:27:46 +00001348** (1) SHARED_LOCK
1349** (2) RESERVED_LOCK
1350** (3) PENDING_LOCK
1351** (4) EXCLUSIVE_LOCK
1352**
drhb3e04342004-06-08 00:47:47 +00001353** Sometimes when requesting one lock state, additional lock states
1354** are inserted in between. The locking might fail on one of the later
1355** transitions leaving the lock state different from what it started but
1356** still short of its goal. The following chart shows the allowed
1357** transitions and the inserted intermediate states:
1358**
1359** UNLOCKED -> SHARED
1360** SHARED -> RESERVED
1361** SHARED -> (PENDING) -> EXCLUSIVE
1362** RESERVED -> (PENDING) -> EXCLUSIVE
1363** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001364**
drha6abd042004-06-09 17:37:22 +00001365** This routine will only increase a lock. Use the sqlite3OsUnlock()
1366** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001367*/
drh308c2a52010-05-14 11:30:18 +00001368static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001369 /* The following describes the implementation of the various locks and
1370 ** lock transitions in terms of the POSIX advisory shared and exclusive
1371 ** lock primitives (called read-locks and write-locks below, to avoid
1372 ** confusion with SQLite lock names). The algorithms are complicated
1373 ** slightly in order to be compatible with windows systems simultaneously
1374 ** accessing the same database file, in case that is ever required.
1375 **
1376 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1377 ** byte', each single bytes at well known offsets, and the 'shared byte
1378 ** range', a range of 510 bytes at a well known offset.
1379 **
1380 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1381 ** byte'. If this is successful, a random byte from the 'shared byte
1382 ** range' is read-locked and the lock on the 'pending byte' released.
1383 **
danielk197790ba3bd2004-06-25 08:32:25 +00001384 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1385 ** A RESERVED lock is implemented by grabbing a write-lock on the
1386 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001387 **
1388 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001389 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1390 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1391 ** obtained, but existing SHARED locks are allowed to persist. A process
1392 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1393 ** This property is used by the algorithm for rolling back a journal file
1394 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001395 **
danielk197790ba3bd2004-06-25 08:32:25 +00001396 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1397 ** implemented by obtaining a write-lock on the entire 'shared byte
1398 ** range'. Since all other locks require a read-lock on one of the bytes
1399 ** within this range, this ensures that no other locks are held on the
1400 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001401 **
1402 ** The reason a single byte cannot be used instead of the 'shared byte
1403 ** range' is that some versions of windows do not support read-locks. By
1404 ** locking a random byte from a range, concurrent SHARED locks may exist
1405 ** even if the locking primitive used is always a write-lock.
1406 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001407 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001408 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001409 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001410 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001411 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001412
drh054889e2005-11-30 03:20:31 +00001413 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001414 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1415 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001416 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001417
1418 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001419 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001420 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001421 */
drh308c2a52010-05-14 11:30:18 +00001422 if( pFile->eFileLock>=eFileLock ){
1423 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1424 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001425 return SQLITE_OK;
1426 }
1427
drh0c2694b2009-09-03 16:23:44 +00001428 /* Make sure the locking sequence is correct.
1429 ** (1) We never move from unlocked to anything higher than shared lock.
1430 ** (2) SQLite never explicitly requests a pendig lock.
1431 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001432 */
drh308c2a52010-05-14 11:30:18 +00001433 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1434 assert( eFileLock!=PENDING_LOCK );
1435 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001436
drh8af6c222010-05-14 12:43:01 +00001437 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001438 */
drh6c7d5c52008-11-21 20:32:33 +00001439 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001440 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001441
danielk1977ad94b582007-08-20 06:44:22 +00001442 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001443 ** handle that precludes the requested lock, return BUSY.
1444 */
drh8af6c222010-05-14 12:43:01 +00001445 if( (pFile->eFileLock!=pInode->eFileLock &&
1446 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001447 ){
1448 rc = SQLITE_BUSY;
1449 goto end_lock;
1450 }
1451
1452 /* If a SHARED lock is requested, and some thread using this PID already
1453 ** has a SHARED or RESERVED lock, then increment reference counts and
1454 ** return SQLITE_OK.
1455 */
drh308c2a52010-05-14 11:30:18 +00001456 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001457 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001458 assert( eFileLock==SHARED_LOCK );
1459 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001460 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001461 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001462 pInode->nShared++;
1463 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001464 goto end_lock;
1465 }
1466
danielk19779a1d0ab2004-06-01 14:09:28 +00001467
drh3cde3bb2004-06-12 02:17:14 +00001468 /* A PENDING lock is needed before acquiring a SHARED lock and before
1469 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1470 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001471 */
drh0c2694b2009-09-03 16:23:44 +00001472 lock.l_len = 1L;
1473 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001474 if( eFileLock==SHARED_LOCK
1475 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001476 ){
drh308c2a52010-05-14 11:30:18 +00001477 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001478 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001479 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001480 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001481 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001482 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001483 pFile->lastErrno = tErrno;
1484 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001485 goto end_lock;
1486 }
drh3cde3bb2004-06-12 02:17:14 +00001487 }
1488
1489
1490 /* If control gets to this point, then actually go ahead and make
1491 ** operating system calls for the specified lock.
1492 */
drh308c2a52010-05-14 11:30:18 +00001493 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001494 assert( pInode->nShared==0 );
1495 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001496 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001497
drh2ac3ee92004-06-07 16:27:46 +00001498 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001499 lock.l_start = SHARED_FIRST;
1500 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001501 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001502 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001503 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001504 }
dan661d71a2011-03-30 19:08:03 +00001505
drh2ac3ee92004-06-07 16:27:46 +00001506 /* Drop the temporary PENDING lock */
1507 lock.l_start = PENDING_BYTE;
1508 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001509 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001510 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1511 /* This could happen with a network mount */
1512 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001513 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001514 }
dan661d71a2011-03-30 19:08:03 +00001515
1516 if( rc ){
1517 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001518 pFile->lastErrno = tErrno;
1519 }
dan661d71a2011-03-30 19:08:03 +00001520 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001521 }else{
drh308c2a52010-05-14 11:30:18 +00001522 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001523 pInode->nLock++;
1524 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001525 }
drh8af6c222010-05-14 12:43:01 +00001526 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001527 /* We are trying for an exclusive lock but another thread in this
1528 ** same process is still holding a shared lock. */
1529 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001530 }else{
drh3cde3bb2004-06-12 02:17:14 +00001531 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001532 ** assumed that there is a SHARED or greater lock on the file
1533 ** already.
1534 */
drh308c2a52010-05-14 11:30:18 +00001535 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001536 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001537
1538 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1539 if( eFileLock==RESERVED_LOCK ){
1540 lock.l_start = RESERVED_BYTE;
1541 lock.l_len = 1L;
1542 }else{
1543 lock.l_start = SHARED_FIRST;
1544 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001545 }
dan661d71a2011-03-30 19:08:03 +00001546
1547 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001548 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001549 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001550 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001551 pFile->lastErrno = tErrno;
1552 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001553 }
drhbbd42a62004-05-22 17:41:58 +00001554 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001555
drh8f941bc2009-01-14 23:03:40 +00001556
1557#ifndef NDEBUG
1558 /* Set up the transaction-counter change checking flags when
1559 ** transitioning from a SHARED to a RESERVED lock. The change
1560 ** from SHARED to RESERVED marks the beginning of a normal
1561 ** write operation (not a hot journal rollback).
1562 */
1563 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001564 && pFile->eFileLock<=SHARED_LOCK
1565 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001566 ){
1567 pFile->transCntrChng = 0;
1568 pFile->dbUpdate = 0;
1569 pFile->inNormalWrite = 1;
1570 }
1571#endif
1572
1573
danielk1977ecb2a962004-06-02 06:30:16 +00001574 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001575 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001576 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001577 }else if( eFileLock==EXCLUSIVE_LOCK ){
1578 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001579 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001580 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001581
1582end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001583 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001584 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1585 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001586 return rc;
1587}
1588
1589/*
dan08da86a2009-08-21 17:18:03 +00001590** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001591** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001592*/
1593static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001594 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001595 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001596 p->pNext = pInode->pUnused;
1597 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001598 pFile->h = -1;
1599 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001600}
1601
1602/*
drh308c2a52010-05-14 11:30:18 +00001603** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001604** must be either NO_LOCK or SHARED_LOCK.
1605**
1606** If the locking level of the file descriptor is already at or below
1607** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001608**
1609** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1610** the byte range is divided into 2 parts and the first part is unlocked then
1611** set to a read lock, then the other part is simply unlocked. This works
1612** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1613** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001614*/
drha7e61d82011-03-12 17:02:57 +00001615static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001616 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001617 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001618 struct flock lock;
1619 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001620
drh054889e2005-11-30 03:20:31 +00001621 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001622 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001623 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001624 getpid()));
drha6abd042004-06-09 17:37:22 +00001625
drh308c2a52010-05-14 11:30:18 +00001626 assert( eFileLock<=SHARED_LOCK );
1627 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001628 return SQLITE_OK;
1629 }
drh6c7d5c52008-11-21 20:32:33 +00001630 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001631 pInode = pFile->pInode;
1632 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001633 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001634 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001635
1636#ifndef NDEBUG
1637 /* When reducing a lock such that other processes can start
1638 ** reading the database file again, make sure that the
1639 ** transaction counter was updated if any part of the database
1640 ** file changed. If the transaction counter is not updated,
1641 ** other connections to the same file might not realize that
1642 ** the file has changed and hence might not know to flush their
1643 ** cache. The use of a stale cache can lead to database corruption.
1644 */
drh8f941bc2009-01-14 23:03:40 +00001645 pFile->inNormalWrite = 0;
1646#endif
1647
drh7ed97b92010-01-20 13:07:21 +00001648 /* downgrading to a shared lock on NFS involves clearing the write lock
1649 ** before establishing the readlock - to avoid a race condition we downgrade
1650 ** the lock in 2 blocks, so that part of the range will be covered by a
1651 ** write lock until the rest is covered by a read lock:
1652 ** 1: [WWWWW]
1653 ** 2: [....W]
1654 ** 3: [RRRRW]
1655 ** 4: [RRRR.]
1656 */
drh308c2a52010-05-14 11:30:18 +00001657 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001658
1659#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001660 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001661 assert( handleNFSUnlock==0 );
1662#endif
1663#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001664 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001665 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001666 off_t divSize = SHARED_SIZE - 1;
1667
1668 lock.l_type = F_UNLCK;
1669 lock.l_whence = SEEK_SET;
1670 lock.l_start = SHARED_FIRST;
1671 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001672 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001673 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001674 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001675 if( IS_LOCK_ERROR(rc) ){
1676 pFile->lastErrno = tErrno;
1677 }
1678 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001679 }
drh7ed97b92010-01-20 13:07:21 +00001680 lock.l_type = F_RDLCK;
1681 lock.l_whence = SEEK_SET;
1682 lock.l_start = SHARED_FIRST;
1683 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001684 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001685 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001686 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1687 if( IS_LOCK_ERROR(rc) ){
1688 pFile->lastErrno = tErrno;
1689 }
1690 goto end_unlock;
1691 }
1692 lock.l_type = F_UNLCK;
1693 lock.l_whence = SEEK_SET;
1694 lock.l_start = SHARED_FIRST+divSize;
1695 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001696 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001697 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001698 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001699 if( IS_LOCK_ERROR(rc) ){
1700 pFile->lastErrno = tErrno;
1701 }
1702 goto end_unlock;
1703 }
drh30f776f2011-02-25 03:25:07 +00001704 }else
1705#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1706 {
drh7ed97b92010-01-20 13:07:21 +00001707 lock.l_type = F_RDLCK;
1708 lock.l_whence = SEEK_SET;
1709 lock.l_start = SHARED_FIRST;
1710 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001711 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001712 /* In theory, the call to unixFileLock() cannot fail because another
1713 ** process is holding an incompatible lock. If it does, this
1714 ** indicates that the other process is not following the locking
1715 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1716 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1717 ** an assert to fail). */
1718 rc = SQLITE_IOERR_RDLOCK;
1719 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001720 goto end_unlock;
1721 }
drh9c105bb2004-10-02 20:38:28 +00001722 }
1723 }
drhbbd42a62004-05-22 17:41:58 +00001724 lock.l_type = F_UNLCK;
1725 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001726 lock.l_start = PENDING_BYTE;
1727 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001728 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001729 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001730 }else{
danea83bc62011-04-01 11:56:32 +00001731 rc = SQLITE_IOERR_UNLOCK;
1732 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001733 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001734 }
drhbbd42a62004-05-22 17:41:58 +00001735 }
drh308c2a52010-05-14 11:30:18 +00001736 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001737 /* Decrement the shared lock counter. Release the lock using an
1738 ** OS call only when all threads in this same process have released
1739 ** the lock.
1740 */
drh8af6c222010-05-14 12:43:01 +00001741 pInode->nShared--;
1742 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001743 lock.l_type = F_UNLCK;
1744 lock.l_whence = SEEK_SET;
1745 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001746 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001747 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001748 }else{
danea83bc62011-04-01 11:56:32 +00001749 rc = SQLITE_IOERR_UNLOCK;
1750 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001751 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001752 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001753 }
drha6abd042004-06-09 17:37:22 +00001754 }
1755
drhbbd42a62004-05-22 17:41:58 +00001756 /* Decrement the count of locks against this same file. When the
1757 ** count reaches zero, close any other file descriptors whose close
1758 ** was deferred because of outstanding locks.
1759 */
drh8af6c222010-05-14 12:43:01 +00001760 pInode->nLock--;
1761 assert( pInode->nLock>=0 );
1762 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001763 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001764 }
1765 }
aswift5b1a2562008-08-22 00:22:35 +00001766
1767end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001768 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001769 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001770 return rc;
drhbbd42a62004-05-22 17:41:58 +00001771}
1772
1773/*
drh308c2a52010-05-14 11:30:18 +00001774** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001775** must be either NO_LOCK or SHARED_LOCK.
1776**
1777** If the locking level of the file descriptor is already at or below
1778** the requested locking level, this routine is a no-op.
1779*/
drh308c2a52010-05-14 11:30:18 +00001780static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001781 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001782}
1783
1784/*
danielk1977e339d652008-06-28 11:23:00 +00001785** This function performs the parts of the "close file" operation
1786** common to all locking schemes. It closes the directory and file
1787** handles, if they are valid, and sets all fields of the unixFile
1788** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001789**
1790** It is *not* necessary to hold the mutex when this routine is called,
1791** even on VxWorks. A mutex will be acquired on VxWorks by the
1792** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001793*/
1794static int closeUnixFile(sqlite3_file *id){
1795 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001796 if( pFile->h>=0 ){
1797 robust_close(pFile, pFile->h, __LINE__);
1798 pFile->h = -1;
1799 }
1800#if OS_VXWORKS
1801 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001802 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001803 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001804 }
1805 vxworksReleaseFileId(pFile->pId);
1806 pFile->pId = 0;
1807 }
1808#endif
1809 OSTRACE(("CLOSE %-3d\n", pFile->h));
1810 OpenCounter(-1);
1811 sqlite3_free(pFile->pUnused);
1812 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001813 return SQLITE_OK;
1814}
1815
1816/*
danielk1977e3026632004-06-22 11:29:02 +00001817** Close a file.
1818*/
danielk197762079062007-08-15 17:08:46 +00001819static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001820 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001821 unixFile *pFile = (unixFile *)id;
1822 unixUnlock(id, NO_LOCK);
1823 unixEnterMutex();
1824
1825 /* unixFile.pInode is always valid here. Otherwise, a different close
1826 ** routine (e.g. nolockClose()) would be called instead.
1827 */
1828 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1829 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1830 /* If there are outstanding locks, do not actually close the file just
1831 ** yet because that would clear those locks. Instead, add the file
1832 ** descriptor to pInode->pUnused list. It will be automatically closed
1833 ** when the last lock is cleared.
1834 */
1835 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001836 }
dan661d71a2011-03-30 19:08:03 +00001837 releaseInodeInfo(pFile);
1838 rc = closeUnixFile(id);
1839 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001840 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001841}
1842
drh734c9862008-11-28 15:37:20 +00001843/************** End of the posix advisory lock implementation *****************
1844******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001845
drh734c9862008-11-28 15:37:20 +00001846/******************************************************************************
1847****************************** No-op Locking **********************************
1848**
1849** Of the various locking implementations available, this is by far the
1850** simplest: locking is ignored. No attempt is made to lock the database
1851** file for reading or writing.
1852**
1853** This locking mode is appropriate for use on read-only databases
1854** (ex: databases that are burned into CD-ROM, for example.) It can
1855** also be used if the application employs some external mechanism to
1856** prevent simultaneous access of the same database by two or more
1857** database connections. But there is a serious risk of database
1858** corruption if this locking mode is used in situations where multiple
1859** database connections are accessing the same database file at the same
1860** time and one or more of those connections are writing.
1861*/
drhbfe66312006-10-03 17:40:40 +00001862
drh734c9862008-11-28 15:37:20 +00001863static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1864 UNUSED_PARAMETER(NotUsed);
1865 *pResOut = 0;
1866 return SQLITE_OK;
1867}
drh734c9862008-11-28 15:37:20 +00001868static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1869 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1870 return SQLITE_OK;
1871}
drh734c9862008-11-28 15:37:20 +00001872static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1873 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1874 return SQLITE_OK;
1875}
1876
1877/*
drh9b35ea62008-11-29 02:20:26 +00001878** Close the file.
drh734c9862008-11-28 15:37:20 +00001879*/
1880static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001881 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001882}
1883
1884/******************* End of the no-op lock implementation *********************
1885******************************************************************************/
1886
1887/******************************************************************************
1888************************* Begin dot-file Locking ******************************
1889**
drh0c2694b2009-09-03 16:23:44 +00001890** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001891** files (really a directory) to control access to the database. This works
1892** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001893**
1894** (1) There is zero concurrency. A single reader blocks all other
1895** connections from reading or writing the database.
1896**
1897** (2) An application crash or power loss can leave stale lock files
1898** sitting around that need to be cleared manually.
1899**
1900** Nevertheless, a dotlock is an appropriate locking mode for use if no
1901** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001902**
drh9ef6bc42011-11-04 02:24:02 +00001903** Dotfile locking works by creating a subdirectory in the same directory as
1904** the database and with the same name but with a ".lock" extension added.
1905** The existance of a lock directory implies an EXCLUSIVE lock. All other
1906** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001907*/
1908
1909/*
1910** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001911** lock directory.
drh734c9862008-11-28 15:37:20 +00001912*/
1913#define DOTLOCK_SUFFIX ".lock"
1914
drh7708e972008-11-29 00:56:52 +00001915/*
1916** This routine checks if there is a RESERVED lock held on the specified
1917** file by this or any other process. If such a lock is held, set *pResOut
1918** to a non-zero value otherwise *pResOut is set to zero. The return value
1919** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1920**
1921** In dotfile locking, either a lock exists or it does not. So in this
1922** variation of CheckReservedLock(), *pResOut is set to true if any lock
1923** is held on the file and false if the file is unlocked.
1924*/
drh734c9862008-11-28 15:37:20 +00001925static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1926 int rc = SQLITE_OK;
1927 int reserved = 0;
1928 unixFile *pFile = (unixFile*)id;
1929
1930 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1931
1932 assert( pFile );
1933
1934 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001935 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001936 /* Either this connection or some other connection in the same process
1937 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001938 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001939 }else{
1940 /* The lock is held if and only if the lockfile exists */
1941 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001942 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001943 }
drh308c2a52010-05-14 11:30:18 +00001944 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001945 *pResOut = reserved;
1946 return rc;
1947}
1948
drh7708e972008-11-29 00:56:52 +00001949/*
drh308c2a52010-05-14 11:30:18 +00001950** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001951** of the following:
1952**
1953** (1) SHARED_LOCK
1954** (2) RESERVED_LOCK
1955** (3) PENDING_LOCK
1956** (4) EXCLUSIVE_LOCK
1957**
1958** Sometimes when requesting one lock state, additional lock states
1959** are inserted in between. The locking might fail on one of the later
1960** transitions leaving the lock state different from what it started but
1961** still short of its goal. The following chart shows the allowed
1962** transitions and the inserted intermediate states:
1963**
1964** UNLOCKED -> SHARED
1965** SHARED -> RESERVED
1966** SHARED -> (PENDING) -> EXCLUSIVE
1967** RESERVED -> (PENDING) -> EXCLUSIVE
1968** PENDING -> EXCLUSIVE
1969**
1970** This routine will only increase a lock. Use the sqlite3OsUnlock()
1971** routine to lower a locking level.
1972**
1973** With dotfile locking, we really only support state (4): EXCLUSIVE.
1974** But we track the other locking levels internally.
1975*/
drh308c2a52010-05-14 11:30:18 +00001976static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001977 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001978 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001979 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001980
drh7708e972008-11-29 00:56:52 +00001981
1982 /* If we have any lock, then the lock file already exists. All we have
1983 ** to do is adjust our internal record of the lock level.
1984 */
drh308c2a52010-05-14 11:30:18 +00001985 if( pFile->eFileLock > NO_LOCK ){
1986 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001987 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001988#ifdef HAVE_UTIME
1989 utime(zLockFile, NULL);
1990#else
drh734c9862008-11-28 15:37:20 +00001991 utimes(zLockFile, NULL);
1992#endif
drh7708e972008-11-29 00:56:52 +00001993 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001994 }
1995
1996 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00001997 rc = osMkdir(zLockFile, 0777);
1998 if( rc<0 ){
1999 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002000 int tErrno = errno;
2001 if( EEXIST == tErrno ){
2002 rc = SQLITE_BUSY;
2003 } else {
2004 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2005 if( IS_LOCK_ERROR(rc) ){
2006 pFile->lastErrno = tErrno;
2007 }
2008 }
drh7708e972008-11-29 00:56:52 +00002009 return rc;
drh734c9862008-11-28 15:37:20 +00002010 }
drh734c9862008-11-28 15:37:20 +00002011
2012 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002013 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002014 return rc;
2015}
2016
drh7708e972008-11-29 00:56:52 +00002017/*
drh308c2a52010-05-14 11:30:18 +00002018** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002019** must be either NO_LOCK or SHARED_LOCK.
2020**
2021** If the locking level of the file descriptor is already at or below
2022** the requested locking level, this routine is a no-op.
2023**
2024** When the locking level reaches NO_LOCK, delete the lock file.
2025*/
drh308c2a52010-05-14 11:30:18 +00002026static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002027 unixFile *pFile = (unixFile*)id;
2028 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002029 int rc;
drh734c9862008-11-28 15:37:20 +00002030
2031 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002032 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2033 pFile->eFileLock, getpid()));
2034 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002035
2036 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002037 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002038 return SQLITE_OK;
2039 }
drh7708e972008-11-29 00:56:52 +00002040
2041 /* To downgrade to shared, simply update our internal notion of the
2042 ** lock state. No need to mess with the file on disk.
2043 */
drh308c2a52010-05-14 11:30:18 +00002044 if( eFileLock==SHARED_LOCK ){
2045 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002046 return SQLITE_OK;
2047 }
2048
drh7708e972008-11-29 00:56:52 +00002049 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002050 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002051 rc = osRmdir(zLockFile);
2052 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2053 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002054 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002055 rc = 0;
drh734c9862008-11-28 15:37:20 +00002056 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002057 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002058 }
2059 if( IS_LOCK_ERROR(rc) ){
2060 pFile->lastErrno = tErrno;
2061 }
2062 return rc;
2063 }
drh308c2a52010-05-14 11:30:18 +00002064 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002065 return SQLITE_OK;
2066}
2067
2068/*
drh9b35ea62008-11-29 02:20:26 +00002069** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002070*/
2071static int dotlockClose(sqlite3_file *id) {
2072 int rc;
2073 if( id ){
2074 unixFile *pFile = (unixFile*)id;
2075 dotlockUnlock(id, NO_LOCK);
2076 sqlite3_free(pFile->lockingContext);
2077 }
drh734c9862008-11-28 15:37:20 +00002078 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002079 return rc;
2080}
2081/****************** End of the dot-file lock implementation *******************
2082******************************************************************************/
2083
2084/******************************************************************************
2085************************** Begin flock Locking ********************************
2086**
2087** Use the flock() system call to do file locking.
2088**
drh6b9d6dd2008-12-03 19:34:47 +00002089** flock() locking is like dot-file locking in that the various
2090** fine-grain locking levels supported by SQLite are collapsed into
2091** a single exclusive lock. In other words, SHARED, RESERVED, and
2092** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2093** still works when you do this, but concurrency is reduced since
2094** only a single process can be reading the database at a time.
2095**
drh734c9862008-11-28 15:37:20 +00002096** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2097** compiling for VXWORKS.
2098*/
2099#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002100
drh6b9d6dd2008-12-03 19:34:47 +00002101/*
drhff812312011-02-23 13:33:46 +00002102** Retry flock() calls that fail with EINTR
2103*/
2104#ifdef EINTR
2105static int robust_flock(int fd, int op){
2106 int rc;
2107 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2108 return rc;
2109}
2110#else
drh5c819272011-02-23 14:00:12 +00002111# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002112#endif
2113
2114
2115/*
drh6b9d6dd2008-12-03 19:34:47 +00002116** This routine checks if there is a RESERVED lock held on the specified
2117** file by this or any other process. If such a lock is held, set *pResOut
2118** to a non-zero value otherwise *pResOut is set to zero. The return value
2119** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2120*/
drh734c9862008-11-28 15:37:20 +00002121static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2122 int rc = SQLITE_OK;
2123 int reserved = 0;
2124 unixFile *pFile = (unixFile*)id;
2125
2126 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2127
2128 assert( pFile );
2129
2130 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002131 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002132 reserved = 1;
2133 }
2134
2135 /* Otherwise see if some other process holds it. */
2136 if( !reserved ){
2137 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002138 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002139 if( !lrc ){
2140 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002141 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002142 if ( lrc ) {
2143 int tErrno = errno;
2144 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002145 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002146 if( IS_LOCK_ERROR(lrc) ){
2147 pFile->lastErrno = tErrno;
2148 rc = lrc;
2149 }
2150 }
2151 } else {
2152 int tErrno = errno;
2153 reserved = 1;
2154 /* someone else might have it reserved */
2155 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2156 if( IS_LOCK_ERROR(lrc) ){
2157 pFile->lastErrno = tErrno;
2158 rc = lrc;
2159 }
2160 }
2161 }
drh308c2a52010-05-14 11:30:18 +00002162 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002163
2164#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2165 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2166 rc = SQLITE_OK;
2167 reserved=1;
2168 }
2169#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2170 *pResOut = reserved;
2171 return rc;
2172}
2173
drh6b9d6dd2008-12-03 19:34:47 +00002174/*
drh308c2a52010-05-14 11:30:18 +00002175** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002176** of the following:
2177**
2178** (1) SHARED_LOCK
2179** (2) RESERVED_LOCK
2180** (3) PENDING_LOCK
2181** (4) EXCLUSIVE_LOCK
2182**
2183** Sometimes when requesting one lock state, additional lock states
2184** are inserted in between. The locking might fail on one of the later
2185** transitions leaving the lock state different from what it started but
2186** still short of its goal. The following chart shows the allowed
2187** transitions and the inserted intermediate states:
2188**
2189** UNLOCKED -> SHARED
2190** SHARED -> RESERVED
2191** SHARED -> (PENDING) -> EXCLUSIVE
2192** RESERVED -> (PENDING) -> EXCLUSIVE
2193** PENDING -> EXCLUSIVE
2194**
2195** flock() only really support EXCLUSIVE locks. We track intermediate
2196** lock states in the sqlite3_file structure, but all locks SHARED or
2197** above are really EXCLUSIVE locks and exclude all other processes from
2198** access the file.
2199**
2200** This routine will only increase a lock. Use the sqlite3OsUnlock()
2201** routine to lower a locking level.
2202*/
drh308c2a52010-05-14 11:30:18 +00002203static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002204 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002205 unixFile *pFile = (unixFile*)id;
2206
2207 assert( pFile );
2208
2209 /* if we already have a lock, it is exclusive.
2210 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002211 if (pFile->eFileLock > NO_LOCK) {
2212 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002213 return SQLITE_OK;
2214 }
2215
2216 /* grab an exclusive lock */
2217
drhff812312011-02-23 13:33:46 +00002218 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002219 int tErrno = errno;
2220 /* didn't get, must be busy */
2221 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2222 if( IS_LOCK_ERROR(rc) ){
2223 pFile->lastErrno = tErrno;
2224 }
2225 } else {
2226 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002227 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002228 }
drh308c2a52010-05-14 11:30:18 +00002229 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2230 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002231#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2232 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2233 rc = SQLITE_BUSY;
2234 }
2235#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2236 return rc;
2237}
2238
drh6b9d6dd2008-12-03 19:34:47 +00002239
2240/*
drh308c2a52010-05-14 11:30:18 +00002241** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002242** must be either NO_LOCK or SHARED_LOCK.
2243**
2244** If the locking level of the file descriptor is already at or below
2245** the requested locking level, this routine is a no-op.
2246*/
drh308c2a52010-05-14 11:30:18 +00002247static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002248 unixFile *pFile = (unixFile*)id;
2249
2250 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002251 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2252 pFile->eFileLock, getpid()));
2253 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002254
2255 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002256 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002257 return SQLITE_OK;
2258 }
2259
2260 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002261 if (eFileLock==SHARED_LOCK) {
2262 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002263 return SQLITE_OK;
2264 }
2265
2266 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002267 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002268#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002269 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002270#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002271 return SQLITE_IOERR_UNLOCK;
2272 }else{
drh308c2a52010-05-14 11:30:18 +00002273 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002274 return SQLITE_OK;
2275 }
2276}
2277
2278/*
2279** Close a file.
2280*/
2281static int flockClose(sqlite3_file *id) {
2282 if( id ){
2283 flockUnlock(id, NO_LOCK);
2284 }
2285 return closeUnixFile(id);
2286}
2287
2288#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2289
2290/******************* End of the flock lock implementation *********************
2291******************************************************************************/
2292
2293/******************************************************************************
2294************************ Begin Named Semaphore Locking ************************
2295**
2296** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002297**
2298** Semaphore locking is like dot-lock and flock in that it really only
2299** supports EXCLUSIVE locking. Only a single process can read or write
2300** the database file at a time. This reduces potential concurrency, but
2301** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002302*/
2303#if OS_VXWORKS
2304
drh6b9d6dd2008-12-03 19:34:47 +00002305/*
2306** This routine checks if there is a RESERVED lock held on the specified
2307** file by this or any other process. If such a lock is held, set *pResOut
2308** to a non-zero value otherwise *pResOut is set to zero. The return value
2309** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2310*/
drh734c9862008-11-28 15:37:20 +00002311static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2312 int rc = SQLITE_OK;
2313 int reserved = 0;
2314 unixFile *pFile = (unixFile*)id;
2315
2316 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2317
2318 assert( pFile );
2319
2320 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002321 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002322 reserved = 1;
2323 }
2324
2325 /* Otherwise see if some other process holds it. */
2326 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002327 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002328 struct stat statBuf;
2329
2330 if( sem_trywait(pSem)==-1 ){
2331 int tErrno = errno;
2332 if( EAGAIN != tErrno ){
2333 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2334 pFile->lastErrno = tErrno;
2335 } else {
2336 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002337 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002338 }
2339 }else{
2340 /* we could have it if we want it */
2341 sem_post(pSem);
2342 }
2343 }
drh308c2a52010-05-14 11:30:18 +00002344 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002345
2346 *pResOut = reserved;
2347 return rc;
2348}
2349
drh6b9d6dd2008-12-03 19:34:47 +00002350/*
drh308c2a52010-05-14 11:30:18 +00002351** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002352** of the following:
2353**
2354** (1) SHARED_LOCK
2355** (2) RESERVED_LOCK
2356** (3) PENDING_LOCK
2357** (4) EXCLUSIVE_LOCK
2358**
2359** Sometimes when requesting one lock state, additional lock states
2360** are inserted in between. The locking might fail on one of the later
2361** transitions leaving the lock state different from what it started but
2362** still short of its goal. The following chart shows the allowed
2363** transitions and the inserted intermediate states:
2364**
2365** UNLOCKED -> SHARED
2366** SHARED -> RESERVED
2367** SHARED -> (PENDING) -> EXCLUSIVE
2368** RESERVED -> (PENDING) -> EXCLUSIVE
2369** PENDING -> EXCLUSIVE
2370**
2371** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2372** lock states in the sqlite3_file structure, but all locks SHARED or
2373** above are really EXCLUSIVE locks and exclude all other processes from
2374** access the file.
2375**
2376** This routine will only increase a lock. Use the sqlite3OsUnlock()
2377** routine to lower a locking level.
2378*/
drh308c2a52010-05-14 11:30:18 +00002379static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002380 unixFile *pFile = (unixFile*)id;
2381 int fd;
drh8af6c222010-05-14 12:43:01 +00002382 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002383 int rc = SQLITE_OK;
2384
2385 /* if we already have a lock, it is exclusive.
2386 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002387 if (pFile->eFileLock > NO_LOCK) {
2388 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002389 rc = SQLITE_OK;
2390 goto sem_end_lock;
2391 }
2392
2393 /* lock semaphore now but bail out when already locked. */
2394 if( sem_trywait(pSem)==-1 ){
2395 rc = SQLITE_BUSY;
2396 goto sem_end_lock;
2397 }
2398
2399 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002400 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002401
2402 sem_end_lock:
2403 return rc;
2404}
2405
drh6b9d6dd2008-12-03 19:34:47 +00002406/*
drh308c2a52010-05-14 11:30:18 +00002407** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002408** must be either NO_LOCK or SHARED_LOCK.
2409**
2410** If the locking level of the file descriptor is already at or below
2411** the requested locking level, this routine is a no-op.
2412*/
drh308c2a52010-05-14 11:30:18 +00002413static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002414 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002415 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002416
2417 assert( pFile );
2418 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002419 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2420 pFile->eFileLock, getpid()));
2421 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002422
2423 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002424 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002425 return SQLITE_OK;
2426 }
2427
2428 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002429 if (eFileLock==SHARED_LOCK) {
2430 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002431 return SQLITE_OK;
2432 }
2433
2434 /* no, really unlock. */
2435 if ( sem_post(pSem)==-1 ) {
2436 int rc, tErrno = errno;
2437 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2438 if( IS_LOCK_ERROR(rc) ){
2439 pFile->lastErrno = tErrno;
2440 }
2441 return rc;
2442 }
drh308c2a52010-05-14 11:30:18 +00002443 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002444 return SQLITE_OK;
2445}
2446
2447/*
2448 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002449 */
drh734c9862008-11-28 15:37:20 +00002450static int semClose(sqlite3_file *id) {
2451 if( id ){
2452 unixFile *pFile = (unixFile*)id;
2453 semUnlock(id, NO_LOCK);
2454 assert( pFile );
2455 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002456 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002457 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002458 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002459 }
2460 return SQLITE_OK;
2461}
2462
2463#endif /* OS_VXWORKS */
2464/*
2465** Named semaphore locking is only available on VxWorks.
2466**
2467*************** End of the named semaphore lock implementation ****************
2468******************************************************************************/
2469
2470
2471/******************************************************************************
2472*************************** Begin AFP Locking *********************************
2473**
2474** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2475** on Apple Macintosh computers - both OS9 and OSX.
2476**
2477** Third-party implementations of AFP are available. But this code here
2478** only works on OSX.
2479*/
2480
drhd2cb50b2009-01-09 21:41:17 +00002481#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002482/*
2483** The afpLockingContext structure contains all afp lock specific state
2484*/
drhbfe66312006-10-03 17:40:40 +00002485typedef struct afpLockingContext afpLockingContext;
2486struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002487 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002488 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002489};
2490
2491struct ByteRangeLockPB2
2492{
2493 unsigned long long offset; /* offset to first byte to lock */
2494 unsigned long long length; /* nbr of bytes to lock */
2495 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2496 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2497 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2498 int fd; /* file desc to assoc this lock with */
2499};
2500
drhfd131da2007-08-07 17:13:03 +00002501#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002502
drh6b9d6dd2008-12-03 19:34:47 +00002503/*
2504** This is a utility for setting or clearing a bit-range lock on an
2505** AFP filesystem.
2506**
2507** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2508*/
2509static int afpSetLock(
2510 const char *path, /* Name of the file to be locked or unlocked */
2511 unixFile *pFile, /* Open file descriptor on path */
2512 unsigned long long offset, /* First byte to be locked */
2513 unsigned long long length, /* Number of bytes to lock */
2514 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002515){
drh6b9d6dd2008-12-03 19:34:47 +00002516 struct ByteRangeLockPB2 pb;
2517 int err;
drhbfe66312006-10-03 17:40:40 +00002518
2519 pb.unLockFlag = setLockFlag ? 0 : 1;
2520 pb.startEndFlag = 0;
2521 pb.offset = offset;
2522 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002523 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002524
drh308c2a52010-05-14 11:30:18 +00002525 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002526 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002527 offset, length));
drhbfe66312006-10-03 17:40:40 +00002528 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2529 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002530 int rc;
2531 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002532 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2533 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002534#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2535 rc = SQLITE_BUSY;
2536#else
drh734c9862008-11-28 15:37:20 +00002537 rc = sqliteErrorFromPosixError(tErrno,
2538 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002539#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002540 if( IS_LOCK_ERROR(rc) ){
2541 pFile->lastErrno = tErrno;
2542 }
2543 return rc;
drhbfe66312006-10-03 17:40:40 +00002544 } else {
aswift5b1a2562008-08-22 00:22:35 +00002545 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002546 }
2547}
2548
drh6b9d6dd2008-12-03 19:34:47 +00002549/*
2550** This routine checks if there is a RESERVED lock held on the specified
2551** file by this or any other process. If such a lock is held, set *pResOut
2552** to a non-zero value otherwise *pResOut is set to zero. The return value
2553** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2554*/
danielk1977e339d652008-06-28 11:23:00 +00002555static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002556 int rc = SQLITE_OK;
2557 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002558 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002559 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002560
aswift5b1a2562008-08-22 00:22:35 +00002561 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2562
2563 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002564 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002565 if( context->reserved ){
2566 *pResOut = 1;
2567 return SQLITE_OK;
2568 }
drh8af6c222010-05-14 12:43:01 +00002569 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002570
2571 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002572 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002573 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002574 }
2575
2576 /* Otherwise see if some other process holds it.
2577 */
aswift5b1a2562008-08-22 00:22:35 +00002578 if( !reserved ){
2579 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002580 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002581 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002582 /* if we succeeded in taking the reserved lock, unlock it to restore
2583 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002584 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002585 } else {
2586 /* if we failed to get the lock then someone else must have it */
2587 reserved = 1;
2588 }
2589 if( IS_LOCK_ERROR(lrc) ){
2590 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002591 }
2592 }
drhbfe66312006-10-03 17:40:40 +00002593
drh7ed97b92010-01-20 13:07:21 +00002594 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002595 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002596
2597 *pResOut = reserved;
2598 return rc;
drhbfe66312006-10-03 17:40:40 +00002599}
2600
drh6b9d6dd2008-12-03 19:34:47 +00002601/*
drh308c2a52010-05-14 11:30:18 +00002602** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002603** of the following:
2604**
2605** (1) SHARED_LOCK
2606** (2) RESERVED_LOCK
2607** (3) PENDING_LOCK
2608** (4) EXCLUSIVE_LOCK
2609**
2610** Sometimes when requesting one lock state, additional lock states
2611** are inserted in between. The locking might fail on one of the later
2612** transitions leaving the lock state different from what it started but
2613** still short of its goal. The following chart shows the allowed
2614** transitions and the inserted intermediate states:
2615**
2616** UNLOCKED -> SHARED
2617** SHARED -> RESERVED
2618** SHARED -> (PENDING) -> EXCLUSIVE
2619** RESERVED -> (PENDING) -> EXCLUSIVE
2620** PENDING -> EXCLUSIVE
2621**
2622** This routine will only increase a lock. Use the sqlite3OsUnlock()
2623** routine to lower a locking level.
2624*/
drh308c2a52010-05-14 11:30:18 +00002625static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002626 int rc = SQLITE_OK;
2627 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002628 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002629 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002630
2631 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002632 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2633 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002634 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002635
drhbfe66312006-10-03 17:40:40 +00002636 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002637 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002638 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002639 */
drh308c2a52010-05-14 11:30:18 +00002640 if( pFile->eFileLock>=eFileLock ){
2641 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2642 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002643 return SQLITE_OK;
2644 }
2645
2646 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002647 ** (1) We never move from unlocked to anything higher than shared lock.
2648 ** (2) SQLite never explicitly requests a pendig lock.
2649 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002650 */
drh308c2a52010-05-14 11:30:18 +00002651 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2652 assert( eFileLock!=PENDING_LOCK );
2653 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002654
drh8af6c222010-05-14 12:43:01 +00002655 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002656 */
drh6c7d5c52008-11-21 20:32:33 +00002657 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002658 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002659
2660 /* If some thread using this PID has a lock via a different unixFile*
2661 ** handle that precludes the requested lock, return BUSY.
2662 */
drh8af6c222010-05-14 12:43:01 +00002663 if( (pFile->eFileLock!=pInode->eFileLock &&
2664 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002665 ){
2666 rc = SQLITE_BUSY;
2667 goto afp_end_lock;
2668 }
2669
2670 /* If a SHARED lock is requested, and some thread using this PID already
2671 ** has a SHARED or RESERVED lock, then increment reference counts and
2672 ** return SQLITE_OK.
2673 */
drh308c2a52010-05-14 11:30:18 +00002674 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002675 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002676 assert( eFileLock==SHARED_LOCK );
2677 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002678 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002679 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002680 pInode->nShared++;
2681 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002682 goto afp_end_lock;
2683 }
drhbfe66312006-10-03 17:40:40 +00002684
2685 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002686 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2687 ** be released.
2688 */
drh308c2a52010-05-14 11:30:18 +00002689 if( eFileLock==SHARED_LOCK
2690 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002691 ){
2692 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002693 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002694 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002695 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002696 goto afp_end_lock;
2697 }
2698 }
2699
2700 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002701 ** operating system calls for the specified lock.
2702 */
drh308c2a52010-05-14 11:30:18 +00002703 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002704 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002705 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002706
drh8af6c222010-05-14 12:43:01 +00002707 assert( pInode->nShared==0 );
2708 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002709
2710 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002711 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002712 /* note that the quality of the randomness doesn't matter that much */
2713 lk = random();
drh8af6c222010-05-14 12:43:01 +00002714 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002715 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002716 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002717 if( IS_LOCK_ERROR(lrc1) ){
2718 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002719 }
aswift5b1a2562008-08-22 00:22:35 +00002720 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002721 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002722
aswift5b1a2562008-08-22 00:22:35 +00002723 if( IS_LOCK_ERROR(lrc1) ) {
2724 pFile->lastErrno = lrc1Errno;
2725 rc = lrc1;
2726 goto afp_end_lock;
2727 } else if( IS_LOCK_ERROR(lrc2) ){
2728 rc = lrc2;
2729 goto afp_end_lock;
2730 } else if( lrc1 != SQLITE_OK ) {
2731 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002732 } else {
drh308c2a52010-05-14 11:30:18 +00002733 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002734 pInode->nLock++;
2735 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002736 }
drh8af6c222010-05-14 12:43:01 +00002737 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002738 /* We are trying for an exclusive lock but another thread in this
2739 ** same process is still holding a shared lock. */
2740 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002741 }else{
2742 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2743 ** assumed that there is a SHARED or greater lock on the file
2744 ** already.
2745 */
2746 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002747 assert( 0!=pFile->eFileLock );
2748 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002749 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002750 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002751 if( !failed ){
2752 context->reserved = 1;
2753 }
drhbfe66312006-10-03 17:40:40 +00002754 }
drh308c2a52010-05-14 11:30:18 +00002755 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002756 /* Acquire an EXCLUSIVE lock */
2757
2758 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002759 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002760 */
drh6b9d6dd2008-12-03 19:34:47 +00002761 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002762 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002763 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002764 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002765 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002766 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002767 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002768 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002769 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2770 ** a critical I/O error
2771 */
2772 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2773 SQLITE_IOERR_LOCK;
2774 goto afp_end_lock;
2775 }
2776 }else{
aswift5b1a2562008-08-22 00:22:35 +00002777 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002778 }
2779 }
aswift5b1a2562008-08-22 00:22:35 +00002780 if( failed ){
2781 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002782 }
2783 }
2784
2785 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002786 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002787 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002788 }else if( eFileLock==EXCLUSIVE_LOCK ){
2789 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002790 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002791 }
2792
2793afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002794 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002795 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2796 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002797 return rc;
2798}
2799
2800/*
drh308c2a52010-05-14 11:30:18 +00002801** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002802** must be either NO_LOCK or SHARED_LOCK.
2803**
2804** If the locking level of the file descriptor is already at or below
2805** the requested locking level, this routine is a no-op.
2806*/
drh308c2a52010-05-14 11:30:18 +00002807static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002808 int rc = SQLITE_OK;
2809 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002810 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002811 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2812 int skipShared = 0;
2813#ifdef SQLITE_TEST
2814 int h = pFile->h;
2815#endif
drhbfe66312006-10-03 17:40:40 +00002816
2817 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002818 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002819 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002820 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002821
drh308c2a52010-05-14 11:30:18 +00002822 assert( eFileLock<=SHARED_LOCK );
2823 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002824 return SQLITE_OK;
2825 }
drh6c7d5c52008-11-21 20:32:33 +00002826 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002827 pInode = pFile->pInode;
2828 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002829 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002830 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002831 SimulateIOErrorBenign(1);
2832 SimulateIOError( h=(-1) )
2833 SimulateIOErrorBenign(0);
2834
2835#ifndef NDEBUG
2836 /* When reducing a lock such that other processes can start
2837 ** reading the database file again, make sure that the
2838 ** transaction counter was updated if any part of the database
2839 ** file changed. If the transaction counter is not updated,
2840 ** other connections to the same file might not realize that
2841 ** the file has changed and hence might not know to flush their
2842 ** cache. The use of a stale cache can lead to database corruption.
2843 */
2844 assert( pFile->inNormalWrite==0
2845 || pFile->dbUpdate==0
2846 || pFile->transCntrChng==1 );
2847 pFile->inNormalWrite = 0;
2848#endif
aswiftaebf4132008-11-21 00:10:35 +00002849
drh308c2a52010-05-14 11:30:18 +00002850 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002851 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002852 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002853 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002854 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002855 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2856 } else {
2857 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002858 }
2859 }
drh308c2a52010-05-14 11:30:18 +00002860 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002861 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002862 }
drh308c2a52010-05-14 11:30:18 +00002863 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002864 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2865 if( !rc ){
2866 context->reserved = 0;
2867 }
aswiftaebf4132008-11-21 00:10:35 +00002868 }
drh8af6c222010-05-14 12:43:01 +00002869 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2870 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002871 }
aswiftaebf4132008-11-21 00:10:35 +00002872 }
drh308c2a52010-05-14 11:30:18 +00002873 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002874
drh7ed97b92010-01-20 13:07:21 +00002875 /* Decrement the shared lock counter. Release the lock using an
2876 ** OS call only when all threads in this same process have released
2877 ** the lock.
2878 */
drh8af6c222010-05-14 12:43:01 +00002879 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2880 pInode->nShared--;
2881 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002882 SimulateIOErrorBenign(1);
2883 SimulateIOError( h=(-1) )
2884 SimulateIOErrorBenign(0);
2885 if( !skipShared ){
2886 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2887 }
2888 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002889 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002890 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002891 }
2892 }
2893 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002894 pInode->nLock--;
2895 assert( pInode->nLock>=0 );
2896 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002897 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002898 }
2899 }
drhbfe66312006-10-03 17:40:40 +00002900 }
drh7ed97b92010-01-20 13:07:21 +00002901
drh6c7d5c52008-11-21 20:32:33 +00002902 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002903 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002904 return rc;
2905}
2906
2907/*
drh339eb0b2008-03-07 15:34:11 +00002908** Close a file & cleanup AFP specific locking context
2909*/
danielk1977e339d652008-06-28 11:23:00 +00002910static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002911 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002912 if( id ){
2913 unixFile *pFile = (unixFile*)id;
2914 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002915 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002916 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002917 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002918 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002919 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002920 ** the last lock is cleared.
2921 */
dan08da86a2009-08-21 17:18:03 +00002922 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002923 }
danb0ac3e32010-06-16 10:55:42 +00002924 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002925 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002926 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002927 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002928 }
drh7ed97b92010-01-20 13:07:21 +00002929 return rc;
drhbfe66312006-10-03 17:40:40 +00002930}
2931
drhd2cb50b2009-01-09 21:41:17 +00002932#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002933/*
2934** The code above is the AFP lock implementation. The code is specific
2935** to MacOSX and does not work on other unix platforms. No alternative
2936** is available. If you don't compile for a mac, then the "unix-afp"
2937** VFS is not available.
2938**
2939********************* End of the AFP lock implementation **********************
2940******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002941
drh7ed97b92010-01-20 13:07:21 +00002942/******************************************************************************
2943*************************** Begin NFS Locking ********************************/
2944
2945#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2946/*
drh308c2a52010-05-14 11:30:18 +00002947 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002948 ** must be either NO_LOCK or SHARED_LOCK.
2949 **
2950 ** If the locking level of the file descriptor is already at or below
2951 ** the requested locking level, this routine is a no-op.
2952 */
drh308c2a52010-05-14 11:30:18 +00002953static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002954 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002955}
2956
2957#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2958/*
2959** The code above is the NFS lock implementation. The code is specific
2960** to MacOSX and does not work on other unix platforms. No alternative
2961** is available.
2962**
2963********************* End of the NFS lock implementation **********************
2964******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002965
2966/******************************************************************************
2967**************** Non-locking sqlite3_file methods *****************************
2968**
2969** The next division contains implementations for all methods of the
2970** sqlite3_file object other than the locking methods. The locking
2971** methods were defined in divisions above (one locking method per
2972** division). Those methods that are common to all locking modes
2973** are gather together into this division.
2974*/
drhbfe66312006-10-03 17:40:40 +00002975
2976/*
drh734c9862008-11-28 15:37:20 +00002977** Seek to the offset passed as the second argument, then read cnt
2978** bytes into pBuf. Return the number of bytes actually read.
2979**
2980** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2981** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2982** one system to another. Since SQLite does not define USE_PREAD
2983** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2984** See tickets #2741 and #2681.
2985**
2986** To avoid stomping the errno value on a failed read the lastErrno value
2987** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002988*/
drh734c9862008-11-28 15:37:20 +00002989static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2990 int got;
drh58024642011-11-07 18:16:00 +00002991 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00002992#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002993 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002994#endif
drh734c9862008-11-28 15:37:20 +00002995 TIMER_START;
drh58024642011-11-07 18:16:00 +00002996 do{
drh734c9862008-11-28 15:37:20 +00002997#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00002998 got = osPread(id->h, pBuf, cnt, offset);
2999 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003000#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003001 got = osPread64(id->h, pBuf, cnt, offset);
3002 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003003#else
drh58024642011-11-07 18:16:00 +00003004 newOffset = lseek(id->h, offset, SEEK_SET);
3005 SimulateIOError( newOffset-- );
3006 if( newOffset!=offset ){
3007 if( newOffset == -1 ){
3008 ((unixFile*)id)->lastErrno = errno;
3009 }else{
3010 ((unixFile*)id)->lastErrno = 0;
3011 }
3012 return -1;
drh734c9862008-11-28 15:37:20 +00003013 }
drh58024642011-11-07 18:16:00 +00003014 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003015#endif
drh58024642011-11-07 18:16:00 +00003016 if( got==cnt ) break;
3017 if( got<0 ){
3018 if( errno==EINTR ){ got = 1; continue; }
3019 prior = 0;
3020 ((unixFile*)id)->lastErrno = errno;
3021 break;
3022 }else if( got>0 ){
3023 cnt -= got;
3024 offset += got;
3025 prior += got;
3026 pBuf = (void*)(got + (char*)pBuf);
3027 }
3028 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003029 TIMER_END;
drh58024642011-11-07 18:16:00 +00003030 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3031 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3032 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003033}
3034
3035/*
drh734c9862008-11-28 15:37:20 +00003036** Read data from a file into a buffer. Return SQLITE_OK if all
3037** bytes were read successfully and SQLITE_IOERR if anything goes
3038** wrong.
drh339eb0b2008-03-07 15:34:11 +00003039*/
drh734c9862008-11-28 15:37:20 +00003040static int unixRead(
3041 sqlite3_file *id,
3042 void *pBuf,
3043 int amt,
3044 sqlite3_int64 offset
3045){
dan08da86a2009-08-21 17:18:03 +00003046 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003047 int got;
3048 assert( id );
drh08c6d442009-02-09 17:34:07 +00003049
dan08da86a2009-08-21 17:18:03 +00003050 /* If this is a database file (not a journal, master-journal or temp
3051 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003052#if 0
dane946c392009-08-22 11:39:46 +00003053 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003054 || offset>=PENDING_BYTE+512
3055 || offset+amt<=PENDING_BYTE
3056 );
dan7c246102010-04-12 19:00:29 +00003057#endif
drh08c6d442009-02-09 17:34:07 +00003058
dan08da86a2009-08-21 17:18:03 +00003059 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003060 if( got==amt ){
3061 return SQLITE_OK;
3062 }else if( got<0 ){
3063 /* lastErrno set by seekAndRead */
3064 return SQLITE_IOERR_READ;
3065 }else{
dan08da86a2009-08-21 17:18:03 +00003066 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003067 /* Unread parts of the buffer must be zero-filled */
3068 memset(&((char*)pBuf)[got], 0, amt-got);
3069 return SQLITE_IOERR_SHORT_READ;
3070 }
3071}
3072
3073/*
3074** Seek to the offset in id->offset then read cnt bytes into pBuf.
3075** Return the number of bytes actually read. Update the offset.
3076**
3077** To avoid stomping the errno value on a failed write the lastErrno value
3078** is set before returning.
3079*/
3080static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3081 int got;
drh7ed97b92010-01-20 13:07:21 +00003082#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003083 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003084#endif
drh734c9862008-11-28 15:37:20 +00003085 TIMER_START;
3086#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003087 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003088#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003089 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003090#else
drhbd1e50c2011-08-19 14:54:12 +00003091 do{
3092 newOffset = lseek(id->h, offset, SEEK_SET);
3093 SimulateIOError( newOffset-- );
3094 if( newOffset!=offset ){
3095 if( newOffset == -1 ){
3096 ((unixFile*)id)->lastErrno = errno;
3097 }else{
3098 ((unixFile*)id)->lastErrno = 0;
3099 }
3100 return -1;
drh734c9862008-11-28 15:37:20 +00003101 }
drhbd1e50c2011-08-19 14:54:12 +00003102 got = osWrite(id->h, pBuf, cnt);
3103 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003104#endif
3105 TIMER_END;
3106 if( got<0 ){
3107 ((unixFile*)id)->lastErrno = errno;
3108 }
3109
drh308c2a52010-05-14 11:30:18 +00003110 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003111 return got;
3112}
3113
3114
3115/*
3116** Write data from a buffer into a file. Return SQLITE_OK on success
3117** or some other error code on failure.
3118*/
3119static int unixWrite(
3120 sqlite3_file *id,
3121 const void *pBuf,
3122 int amt,
3123 sqlite3_int64 offset
3124){
dan08da86a2009-08-21 17:18:03 +00003125 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003126 int wrote = 0;
3127 assert( id );
3128 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003129
dan08da86a2009-08-21 17:18:03 +00003130 /* If this is a database file (not a journal, master-journal or temp
3131 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003132#if 0
dane946c392009-08-22 11:39:46 +00003133 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003134 || offset>=PENDING_BYTE+512
3135 || offset+amt<=PENDING_BYTE
3136 );
dan7c246102010-04-12 19:00:29 +00003137#endif
drh08c6d442009-02-09 17:34:07 +00003138
drh8f941bc2009-01-14 23:03:40 +00003139#ifndef NDEBUG
3140 /* If we are doing a normal write to a database file (as opposed to
3141 ** doing a hot-journal rollback or a write to some file other than a
3142 ** normal database file) then record the fact that the database
3143 ** has changed. If the transaction counter is modified, record that
3144 ** fact too.
3145 */
dan08da86a2009-08-21 17:18:03 +00003146 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003147 pFile->dbUpdate = 1; /* The database has been modified */
3148 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003149 int rc;
drh8f941bc2009-01-14 23:03:40 +00003150 char oldCntr[4];
3151 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003152 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003153 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003154 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003155 pFile->transCntrChng = 1; /* The transaction counter has changed */
3156 }
3157 }
3158 }
3159#endif
3160
dan08da86a2009-08-21 17:18:03 +00003161 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003162 amt -= wrote;
3163 offset += wrote;
3164 pBuf = &((char*)pBuf)[wrote];
3165 }
3166 SimulateIOError(( wrote=(-1), amt=1 ));
3167 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003168
drh734c9862008-11-28 15:37:20 +00003169 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003170 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003171 /* lastErrno set by seekAndWrite */
3172 return SQLITE_IOERR_WRITE;
3173 }else{
dan08da86a2009-08-21 17:18:03 +00003174 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003175 return SQLITE_FULL;
3176 }
3177 }
dan6e09d692010-07-27 18:34:15 +00003178
drh734c9862008-11-28 15:37:20 +00003179 return SQLITE_OK;
3180}
3181
3182#ifdef SQLITE_TEST
3183/*
3184** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003185** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003186*/
3187int sqlite3_sync_count = 0;
3188int sqlite3_fullsync_count = 0;
3189#endif
3190
3191/*
drh89240432009-03-25 01:06:01 +00003192** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003193** Others do no. To be safe, we will stick with the (slightly slower)
3194** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003195** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003196*/
drh20f8e132011-08-31 21:01:55 +00003197#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003198# define fdatasync fsync
3199#endif
3200
3201/*
3202** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3203** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3204** only available on Mac OS X. But that could change.
3205*/
3206#ifdef F_FULLFSYNC
3207# define HAVE_FULLFSYNC 1
3208#else
3209# define HAVE_FULLFSYNC 0
3210#endif
3211
3212
3213/*
3214** The fsync() system call does not work as advertised on many
3215** unix systems. The following procedure is an attempt to make
3216** it work better.
3217**
3218** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3219** for testing when we want to run through the test suite quickly.
3220** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3221** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3222** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003223**
3224** SQLite sets the dataOnly flag if the size of the file is unchanged.
3225** The idea behind dataOnly is that it should only write the file content
3226** to disk, not the inode. We only set dataOnly if the file size is
3227** unchanged since the file size is part of the inode. However,
3228** Ted Ts'o tells us that fdatasync() will also write the inode if the
3229** file size has changed. The only real difference between fdatasync()
3230** and fsync(), Ted tells us, is that fdatasync() will not flush the
3231** inode if the mtime or owner or other inode attributes have changed.
3232** We only care about the file size, not the other file attributes, so
3233** as far as SQLite is concerned, an fdatasync() is always adequate.
3234** So, we always use fdatasync() if it is available, regardless of
3235** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003236*/
3237static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003238 int rc;
drh734c9862008-11-28 15:37:20 +00003239
3240 /* The following "ifdef/elif/else/" block has the same structure as
3241 ** the one below. It is replicated here solely to avoid cluttering
3242 ** up the real code with the UNUSED_PARAMETER() macros.
3243 */
3244#ifdef SQLITE_NO_SYNC
3245 UNUSED_PARAMETER(fd);
3246 UNUSED_PARAMETER(fullSync);
3247 UNUSED_PARAMETER(dataOnly);
3248#elif HAVE_FULLFSYNC
3249 UNUSED_PARAMETER(dataOnly);
3250#else
3251 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003252 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003253#endif
3254
3255 /* Record the number of times that we do a normal fsync() and
3256 ** FULLSYNC. This is used during testing to verify that this procedure
3257 ** gets called with the correct arguments.
3258 */
3259#ifdef SQLITE_TEST
3260 if( fullSync ) sqlite3_fullsync_count++;
3261 sqlite3_sync_count++;
3262#endif
3263
3264 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3265 ** no-op
3266 */
3267#ifdef SQLITE_NO_SYNC
3268 rc = SQLITE_OK;
3269#elif HAVE_FULLFSYNC
3270 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003271 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003272 }else{
3273 rc = 1;
3274 }
3275 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003276 ** It shouldn't be possible for fullfsync to fail on the local
3277 ** file system (on OSX), so failure indicates that FULLFSYNC
3278 ** isn't supported for this file system. So, attempt an fsync
3279 ** and (for now) ignore the overhead of a superfluous fcntl call.
3280 ** It'd be better to detect fullfsync support once and avoid
3281 ** the fcntl call every time sync is called.
3282 */
drh734c9862008-11-28 15:37:20 +00003283 if( rc ) rc = fsync(fd);
3284
drh7ed97b92010-01-20 13:07:21 +00003285#elif defined(__APPLE__)
3286 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3287 ** so currently we default to the macro that redefines fdatasync to fsync
3288 */
3289 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003290#else
drh0b647ff2009-03-21 14:41:04 +00003291 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003292#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003293 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003294 rc = fsync(fd);
3295 }
drh0b647ff2009-03-21 14:41:04 +00003296#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003297#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3298
3299 if( OS_VXWORKS && rc!= -1 ){
3300 rc = 0;
3301 }
chw97185482008-11-17 08:05:31 +00003302 return rc;
drhbfe66312006-10-03 17:40:40 +00003303}
3304
drh734c9862008-11-28 15:37:20 +00003305/*
drh0059eae2011-08-08 23:48:40 +00003306** Open a file descriptor to the directory containing file zFilename.
3307** If successful, *pFd is set to the opened file descriptor and
3308** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3309** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3310** value.
3311**
drh90315a22011-08-10 01:52:12 +00003312** The directory file descriptor is used for only one thing - to
3313** fsync() a directory to make sure file creation and deletion events
3314** are flushed to disk. Such fsyncs are not needed on newer
3315** journaling filesystems, but are required on older filesystems.
3316**
3317** This routine can be overridden using the xSetSysCall interface.
3318** The ability to override this routine was added in support of the
3319** chromium sandbox. Opening a directory is a security risk (we are
3320** told) so making it overrideable allows the chromium sandbox to
3321** replace this routine with a harmless no-op. To make this routine
3322** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3323** *pFd set to a negative number.
3324**
drh0059eae2011-08-08 23:48:40 +00003325** If SQLITE_OK is returned, the caller is responsible for closing
3326** the file descriptor *pFd using close().
3327*/
3328static int openDirectory(const char *zFilename, int *pFd){
3329 int ii;
3330 int fd = -1;
3331 char zDirname[MAX_PATHNAME+1];
3332
3333 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3334 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3335 if( ii>0 ){
3336 zDirname[ii] = '\0';
3337 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3338 if( fd>=0 ){
3339#ifdef FD_CLOEXEC
3340 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3341#endif
3342 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3343 }
3344 }
3345 *pFd = fd;
3346 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3347}
3348
3349/*
drh734c9862008-11-28 15:37:20 +00003350** Make sure all writes to a particular file are committed to disk.
3351**
3352** If dataOnly==0 then both the file itself and its metadata (file
3353** size, access time, etc) are synced. If dataOnly!=0 then only the
3354** file data is synced.
3355**
3356** Under Unix, also make sure that the directory entry for the file
3357** has been created by fsync-ing the directory that contains the file.
3358** If we do not do this and we encounter a power failure, the directory
3359** entry for the journal might not exist after we reboot. The next
3360** SQLite to access the file will not know that the journal exists (because
3361** the directory entry for the journal was never created) and the transaction
3362** will not roll back - possibly leading to database corruption.
3363*/
3364static int unixSync(sqlite3_file *id, int flags){
3365 int rc;
3366 unixFile *pFile = (unixFile*)id;
3367
3368 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3369 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3370
3371 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3372 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3373 || (flags&0x0F)==SQLITE_SYNC_FULL
3374 );
3375
3376 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3377 ** line is to test that doing so does not cause any problems.
3378 */
3379 SimulateDiskfullError( return SQLITE_FULL );
3380
3381 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003382 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003383 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3384 SimulateIOError( rc=1 );
3385 if( rc ){
3386 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003387 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003388 }
drh0059eae2011-08-08 23:48:40 +00003389
3390 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003391 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3392 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003393 */
3394 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3395 int dirfd;
3396 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003397 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003398 rc = osOpenDirectory(pFile->zPath, &dirfd);
3399 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003400 full_fsync(dirfd, 0, 0);
3401 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003402 }else if( rc==SQLITE_CANTOPEN ){
3403 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003404 }
drh0059eae2011-08-08 23:48:40 +00003405 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003406 }
3407 return rc;
3408}
3409
3410/*
3411** Truncate an open file to a specified size
3412*/
3413static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003414 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003415 int rc;
dan6e09d692010-07-27 18:34:15 +00003416 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003417 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003418
3419 /* If the user has configured a chunk-size for this file, truncate the
3420 ** file so that it consists of an integer number of chunks (i.e. the
3421 ** actual file size after the operation may be larger than the requested
3422 ** size).
3423 */
3424 if( pFile->szChunk ){
3425 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3426 }
3427
drhff812312011-02-23 13:33:46 +00003428 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003429 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003430 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003431 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003432 }else{
drh3313b142009-11-06 04:13:18 +00003433#ifndef NDEBUG
3434 /* If we are doing a normal write to a database file (as opposed to
3435 ** doing a hot-journal rollback or a write to some file other than a
3436 ** normal database file) and we truncate the file to zero length,
3437 ** that effectively updates the change counter. This might happen
3438 ** when restoring a database using the backup API from a zero-length
3439 ** source.
3440 */
dan6e09d692010-07-27 18:34:15 +00003441 if( pFile->inNormalWrite && nByte==0 ){
3442 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003443 }
3444#endif
3445
drh734c9862008-11-28 15:37:20 +00003446 return SQLITE_OK;
3447 }
3448}
3449
3450/*
3451** Determine the current size of a file in bytes
3452*/
3453static int unixFileSize(sqlite3_file *id, i64 *pSize){
3454 int rc;
3455 struct stat buf;
3456 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003457 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003458 SimulateIOError( rc=1 );
3459 if( rc!=0 ){
3460 ((unixFile*)id)->lastErrno = errno;
3461 return SQLITE_IOERR_FSTAT;
3462 }
3463 *pSize = buf.st_size;
3464
drh8af6c222010-05-14 12:43:01 +00003465 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003466 ** writes a single byte into that file in order to work around a bug
3467 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3468 ** layers, we need to report this file size as zero even though it is
3469 ** really 1. Ticket #3260.
3470 */
3471 if( *pSize==1 ) *pSize = 0;
3472
3473
3474 return SQLITE_OK;
3475}
3476
drhd2cb50b2009-01-09 21:41:17 +00003477#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003478/*
3479** Handler for proxy-locking file-control verbs. Defined below in the
3480** proxying locking division.
3481*/
3482static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003483#endif
drh715ff302008-12-03 22:32:44 +00003484
dan502019c2010-07-28 14:26:17 +00003485/*
3486** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003487** file-control operation. Enlarge the database to nBytes in size
3488** (rounded up to the next chunk-size). If the database is already
3489** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003490*/
3491static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003492 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003493 i64 nSize; /* Required file size */
3494 struct stat buf; /* Used to hold return values of fstat() */
3495
drh99ab3b12011-03-02 15:09:07 +00003496 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003497
3498 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3499 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003500
dan502019c2010-07-28 14:26:17 +00003501#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003502 /* The code below is handling the return value of osFallocate()
3503 ** correctly. posix_fallocate() is defined to "returns zero on success,
3504 ** or an error number on failure". See the manpage for details. */
3505 int err;
drhff812312011-02-23 13:33:46 +00003506 do{
dan661d71a2011-03-30 19:08:03 +00003507 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3508 }while( err==EINTR );
3509 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003510#else
3511 /* If the OS does not have posix_fallocate(), fake it. First use
3512 ** ftruncate() to set the file size, then write a single byte to
3513 ** the last byte in each block within the extended region. This
3514 ** is the same technique used by glibc to implement posix_fallocate()
3515 ** on systems that do not have a real fallocate() system call.
3516 */
3517 int nBlk = buf.st_blksize; /* File-system block size */
3518 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003519
drhff812312011-02-23 13:33:46 +00003520 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003521 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003522 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003523 }
3524 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003525 while( iWrite<nSize ){
3526 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3527 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003528 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003529 }
dan502019c2010-07-28 14:26:17 +00003530#endif
3531 }
3532 }
3533
3534 return SQLITE_OK;
3535}
danielk1977ad94b582007-08-20 06:44:22 +00003536
danielk1977e3026632004-06-22 11:29:02 +00003537/*
drhf12b3f62011-12-21 14:42:29 +00003538** If *pArg is inititially negative then this is a query. Set *pArg to
3539** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3540**
3541** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3542*/
3543static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3544 if( *pArg<0 ){
3545 *pArg = (pFile->ctrlFlags & mask)!=0;
3546 }else if( (*pArg)==0 ){
3547 pFile->ctrlFlags &= ~mask;
3548 }else{
3549 pFile->ctrlFlags |= mask;
3550 }
3551}
3552
3553/*
drh9e33c2c2007-08-31 18:34:59 +00003554** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003555*/
drhcc6bb3e2007-08-31 16:11:35 +00003556static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003557 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003558 switch( op ){
3559 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003560 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003561 return SQLITE_OK;
3562 }
drh7708e972008-11-29 00:56:52 +00003563 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003564 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003565 return SQLITE_OK;
3566 }
dan6e09d692010-07-27 18:34:15 +00003567 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003568 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003569 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003570 }
drh9ff27ec2010-05-19 19:26:05 +00003571 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003572 int rc;
3573 SimulateIOErrorBenign(1);
3574 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3575 SimulateIOErrorBenign(0);
3576 return rc;
drhf0b190d2011-07-26 16:03:07 +00003577 }
3578 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003579 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3580 return SQLITE_OK;
3581 }
drhcb15f352011-12-23 01:04:17 +00003582 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3583 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003584 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003585 }
drhde60fc22011-12-14 17:53:36 +00003586 case SQLITE_FCNTL_VFSNAME: {
3587 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3588 return SQLITE_OK;
3589 }
drh8f941bc2009-01-14 23:03:40 +00003590#ifndef NDEBUG
3591 /* The pager calls this method to signal that it has done
3592 ** a rollback and that the database is therefore unchanged and
3593 ** it hence it is OK for the transaction change counter to be
3594 ** unchanged.
3595 */
3596 case SQLITE_FCNTL_DB_UNCHANGED: {
3597 ((unixFile*)id)->dbUpdate = 0;
3598 return SQLITE_OK;
3599 }
3600#endif
drhd2cb50b2009-01-09 21:41:17 +00003601#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003602 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003603 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003604 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003605 }
drhd2cb50b2009-01-09 21:41:17 +00003606#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003607 }
drh0b52b7d2011-01-26 19:46:22 +00003608 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003609}
3610
3611/*
danielk1977a3d4c882007-03-23 10:08:38 +00003612** Return the sector size in bytes of the underlying block device for
3613** the specified file. This is almost always 512 bytes, but may be
3614** larger for some devices.
3615**
3616** SQLite code assumes this function cannot fail. It also assumes that
3617** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003618** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003619** same for both.
3620*/
drh1da88f02011-12-17 16:09:16 +00003621static int unixSectorSize(sqlite3_file *pFile){
drh8942d412012-01-02 18:20:14 +00003622 (void)pFile;
3623 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003624}
3625
danielk197790949c22007-08-17 16:50:38 +00003626/*
drhf12b3f62011-12-21 14:42:29 +00003627** Return the device characteristics for the file.
3628**
drhcb15f352011-12-23 01:04:17 +00003629** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3630** However, that choice is contraversial since technically the underlying
3631** file system does not always provide powersafe overwrites. (In other
3632** words, after a power-loss event, parts of the file that were never
3633** written might end up being altered.) However, non-PSOW behavior is very,
3634** very rare. And asserting PSOW makes a large reduction in the amount
3635** of required I/O for journaling, since a lot of padding is eliminated.
3636** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3637** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003638*/
drhf12b3f62011-12-21 14:42:29 +00003639static int unixDeviceCharacteristics(sqlite3_file *id){
3640 unixFile *p = (unixFile*)id;
drhcb15f352011-12-23 01:04:17 +00003641 if( p->ctrlFlags & UNIXFILE_PSOW ){
3642 return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3643 }else{
3644 return 0;
3645 }
danielk197762079062007-08-15 17:08:46 +00003646}
3647
drhd9e5c4f2010-05-12 18:01:39 +00003648#ifndef SQLITE_OMIT_WAL
3649
3650
3651/*
drhd91c68f2010-05-14 14:52:25 +00003652** Object used to represent an shared memory buffer.
3653**
3654** When multiple threads all reference the same wal-index, each thread
3655** has its own unixShm object, but they all point to a single instance
3656** of this unixShmNode object. In other words, each wal-index is opened
3657** only once per process.
3658**
3659** Each unixShmNode object is connected to a single unixInodeInfo object.
3660** We could coalesce this object into unixInodeInfo, but that would mean
3661** every open file that does not use shared memory (in other words, most
3662** open files) would have to carry around this extra information. So
3663** the unixInodeInfo object contains a pointer to this unixShmNode object
3664** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003665**
3666** unixMutexHeld() must be true when creating or destroying
3667** this object or while reading or writing the following fields:
3668**
3669** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003670**
3671** The following fields are read-only after the object is created:
3672**
3673** fid
3674** zFilename
3675**
drhd91c68f2010-05-14 14:52:25 +00003676** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003677** unixMutexHeld() is true when reading or writing any other field
3678** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003679*/
drhd91c68f2010-05-14 14:52:25 +00003680struct unixShmNode {
3681 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003682 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003683 char *zFilename; /* Name of the mmapped file */
3684 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003685 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003686 u16 nRegion; /* Size of array apRegion */
3687 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003688 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003689 int nRef; /* Number of unixShm objects pointing to this */
3690 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003691#ifdef SQLITE_DEBUG
3692 u8 exclMask; /* Mask of exclusive locks held */
3693 u8 sharedMask; /* Mask of shared locks held */
3694 u8 nextShmId; /* Next available unixShm.id value */
3695#endif
3696};
3697
3698/*
drhd9e5c4f2010-05-12 18:01:39 +00003699** Structure used internally by this VFS to record the state of an
3700** open shared memory connection.
3701**
drhd91c68f2010-05-14 14:52:25 +00003702** The following fields are initialized when this object is created and
3703** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003704**
drhd91c68f2010-05-14 14:52:25 +00003705** unixShm.pFile
3706** unixShm.id
3707**
3708** All other fields are read/write. The unixShm.pFile->mutex must be held
3709** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003710*/
3711struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003712 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3713 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003714 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003715 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003716 u16 sharedMask; /* Mask of shared locks held */
3717 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003718};
3719
3720/*
drhd9e5c4f2010-05-12 18:01:39 +00003721** Constants used for locking
3722*/
drhbd9676c2010-06-23 17:58:38 +00003723#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003724#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003725
drhd9e5c4f2010-05-12 18:01:39 +00003726/*
drh73b64e42010-05-30 19:55:15 +00003727** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003728**
3729** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3730** otherwise.
3731*/
3732static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003733 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3734 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003735 int ofst, /* First byte of the locking range */
3736 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003737){
3738 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003739 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003740
drhd91c68f2010-05-14 14:52:25 +00003741 /* Access to the unixShmNode object is serialized by the caller */
3742 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003743
drh73b64e42010-05-30 19:55:15 +00003744 /* Shared locks never span more than one byte */
3745 assert( n==1 || lockType!=F_RDLCK );
3746
3747 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003748 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003749
drh3cb93392011-03-12 18:10:44 +00003750 if( pShmNode->h>=0 ){
3751 /* Initialize the locking parameters */
3752 memset(&f, 0, sizeof(f));
3753 f.l_type = lockType;
3754 f.l_whence = SEEK_SET;
3755 f.l_start = ofst;
3756 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003757
drh3cb93392011-03-12 18:10:44 +00003758 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3759 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3760 }
drhd9e5c4f2010-05-12 18:01:39 +00003761
3762 /* Update the global lock state and do debug tracing */
3763#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003764 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003765 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003766 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003767 if( rc==SQLITE_OK ){
3768 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003769 OSTRACE(("unlock %d ok", ofst));
3770 pShmNode->exclMask &= ~mask;
3771 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003772 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003773 OSTRACE(("read-lock %d ok", ofst));
3774 pShmNode->exclMask &= ~mask;
3775 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003776 }else{
3777 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003778 OSTRACE(("write-lock %d ok", ofst));
3779 pShmNode->exclMask |= mask;
3780 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003781 }
3782 }else{
3783 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003784 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003785 }else if( lockType==F_RDLCK ){
3786 OSTRACE(("read-lock failed"));
3787 }else{
3788 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003789 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003790 }
3791 }
drh20e1f082010-05-31 16:10:12 +00003792 OSTRACE((" - afterwards %03x,%03x\n",
3793 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003794 }
drhd9e5c4f2010-05-12 18:01:39 +00003795#endif
3796
3797 return rc;
3798}
3799
drhd9e5c4f2010-05-12 18:01:39 +00003800
3801/*
drhd91c68f2010-05-14 14:52:25 +00003802** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003803**
3804** This is not a VFS shared-memory method; it is a utility function called
3805** by VFS shared-memory methods.
3806*/
drhd91c68f2010-05-14 14:52:25 +00003807static void unixShmPurge(unixFile *pFd){
3808 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003809 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003810 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003811 int i;
drhd91c68f2010-05-14 14:52:25 +00003812 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003813 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003814 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003815 if( p->h>=0 ){
3816 munmap(p->apRegion[i], p->szRegion);
3817 }else{
3818 sqlite3_free(p->apRegion[i]);
3819 }
dan13a3cb82010-06-11 19:04:21 +00003820 }
dan18801912010-06-14 14:07:50 +00003821 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003822 if( p->h>=0 ){
3823 robust_close(pFd, p->h, __LINE__);
3824 p->h = -1;
3825 }
drhd91c68f2010-05-14 14:52:25 +00003826 p->pInode->pShmNode = 0;
3827 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003828 }
3829}
3830
3831/*
danda9fe0c2010-07-13 18:44:03 +00003832** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003833** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003834**
drh7234c6d2010-06-19 15:10:09 +00003835** The file used to implement shared-memory is in the same directory
3836** as the open database file and has the same name as the open database
3837** file with the "-shm" suffix added. For example, if the database file
3838** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003839** for shared memory will be called "/home/user1/config.db-shm".
3840**
3841** Another approach to is to use files in /dev/shm or /dev/tmp or an
3842** some other tmpfs mount. But if a file in a different directory
3843** from the database file is used, then differing access permissions
3844** or a chroot() might cause two different processes on the same
3845** database to end up using different files for shared memory -
3846** meaning that their memory would not really be shared - resulting
3847** in database corruption. Nevertheless, this tmpfs file usage
3848** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3849** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3850** option results in an incompatible build of SQLite; builds of SQLite
3851** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3852** same database file at the same time, database corruption will likely
3853** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3854** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003855**
3856** When opening a new shared-memory file, if no other instances of that
3857** file are currently open, in this process or in other processes, then
3858** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003859**
3860** If the original database file (pDbFd) is using the "unix-excl" VFS
3861** that means that an exclusive lock is held on the database file and
3862** that no other processes are able to read or write the database. In
3863** that case, we do not really need shared memory. No shared memory
3864** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003865*/
danda9fe0c2010-07-13 18:44:03 +00003866static int unixOpenSharedMemory(unixFile *pDbFd){
3867 struct unixShm *p = 0; /* The connection to be opened */
3868 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3869 int rc; /* Result code */
3870 unixInodeInfo *pInode; /* The inode of fd */
3871 char *zShmFilename; /* Name of the file used for SHM */
3872 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003873
danda9fe0c2010-07-13 18:44:03 +00003874 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003875 p = sqlite3_malloc( sizeof(*p) );
3876 if( p==0 ) return SQLITE_NOMEM;
3877 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003878 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003879
danda9fe0c2010-07-13 18:44:03 +00003880 /* Check to see if a unixShmNode object already exists. Reuse an existing
3881 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003882 */
3883 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003884 pInode = pDbFd->pInode;
3885 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003886 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003887 struct stat sStat; /* fstat() info for database file */
3888
3889 /* Call fstat() to figure out the permissions on the database file. If
3890 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00003891 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00003892 */
drh3cb93392011-03-12 18:10:44 +00003893 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003894 rc = SQLITE_IOERR_FSTAT;
3895 goto shm_open_err;
3896 }
3897
drha4ced192010-07-15 18:32:40 +00003898#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00003899 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00003900#else
drh52bcde02012-01-03 14:50:45 +00003901 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003902#endif
drh7234c6d2010-06-19 15:10:09 +00003903 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003904 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003905 rc = SQLITE_NOMEM;
3906 goto shm_open_err;
3907 }
drh9cb5a0d2012-01-05 21:19:54 +00003908 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00003909 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003910#ifdef SQLITE_SHM_DIRECTORY
3911 sqlite3_snprintf(nShmFilename, zShmFilename,
3912 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3913 (u32)sStat.st_ino, (u32)sStat.st_dev);
3914#else
drh7234c6d2010-06-19 15:10:09 +00003915 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003916 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003917#endif
drhd91c68f2010-05-14 14:52:25 +00003918 pShmNode->h = -1;
3919 pDbFd->pInode->pShmNode = pShmNode;
3920 pShmNode->pInode = pDbFd->pInode;
3921 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3922 if( pShmNode->mutex==0 ){
3923 rc = SQLITE_NOMEM;
3924 goto shm_open_err;
3925 }
drhd9e5c4f2010-05-12 18:01:39 +00003926
drh3cb93392011-03-12 18:10:44 +00003927 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003928 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003929 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003930 openFlags = O_RDONLY;
3931 pShmNode->isReadonly = 1;
3932 }
3933 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003934 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00003935 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3936 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003937 }
drhac7c3ac2012-02-11 19:23:48 +00003938
3939 /* If this process is running as root, make sure that the SHM file
3940 ** is owned by the same user that owns the original database. Otherwise,
3941 ** the original owner will not be able to connect. If this process is
drh3ee34842012-02-11 21:21:17 +00003942 ** not root, the following fchown() will fail, but we don't care. The
3943 ** if(){..} and the UNIXFILE_CHOWN flag are purely to silence compiler
3944 ** warnings.
drhac7c3ac2012-02-11 19:23:48 +00003945 */
drh23c4b972012-02-11 23:55:15 +00003946 if( osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid)==0 ){
drh3ee34842012-02-11 21:21:17 +00003947 pDbFd->ctrlFlags |= UNIXFILE_CHOWN;
3948 }
drh3cb93392011-03-12 18:10:44 +00003949
3950 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003951 ** If not, truncate the file to zero length.
3952 */
3953 rc = SQLITE_OK;
3954 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3955 if( robust_ftruncate(pShmNode->h, 0) ){
3956 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003957 }
3958 }
drh66dfec8b2011-06-01 20:01:49 +00003959 if( rc==SQLITE_OK ){
3960 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3961 }
3962 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003963 }
drhd9e5c4f2010-05-12 18:01:39 +00003964 }
3965
drhd91c68f2010-05-14 14:52:25 +00003966 /* Make the new connection a child of the unixShmNode */
3967 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003968#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003969 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003970#endif
drhd91c68f2010-05-14 14:52:25 +00003971 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003972 pDbFd->pShm = p;
3973 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003974
3975 /* The reference count on pShmNode has already been incremented under
3976 ** the cover of the unixEnterMutex() mutex and the pointer from the
3977 ** new (struct unixShm) object to the pShmNode has been set. All that is
3978 ** left to do is to link the new object into the linked list starting
3979 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3980 ** mutex.
3981 */
3982 sqlite3_mutex_enter(pShmNode->mutex);
3983 p->pNext = pShmNode->pFirst;
3984 pShmNode->pFirst = p;
3985 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003986 return SQLITE_OK;
3987
3988 /* Jump here on any error */
3989shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003990 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003991 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003992 unixLeaveMutex();
3993 return rc;
3994}
3995
3996/*
danda9fe0c2010-07-13 18:44:03 +00003997** This function is called to obtain a pointer to region iRegion of the
3998** shared-memory associated with the database file fd. Shared-memory regions
3999** are numbered starting from zero. Each shared-memory region is szRegion
4000** bytes in size.
4001**
4002** If an error occurs, an error code is returned and *pp is set to NULL.
4003**
4004** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4005** region has not been allocated (by any client, including one running in a
4006** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4007** bExtend is non-zero and the requested shared-memory region has not yet
4008** been allocated, it is allocated by this function.
4009**
4010** If the shared-memory region has already been allocated or is allocated by
4011** this call as described above, then it is mapped into this processes
4012** address space (if it is not already), *pp is set to point to the mapped
4013** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004014*/
danda9fe0c2010-07-13 18:44:03 +00004015static int unixShmMap(
4016 sqlite3_file *fd, /* Handle open on database file */
4017 int iRegion, /* Region to retrieve */
4018 int szRegion, /* Size of regions */
4019 int bExtend, /* True to extend file if necessary */
4020 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004021){
danda9fe0c2010-07-13 18:44:03 +00004022 unixFile *pDbFd = (unixFile*)fd;
4023 unixShm *p;
4024 unixShmNode *pShmNode;
4025 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004026
danda9fe0c2010-07-13 18:44:03 +00004027 /* If the shared-memory file has not yet been opened, open it now. */
4028 if( pDbFd->pShm==0 ){
4029 rc = unixOpenSharedMemory(pDbFd);
4030 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004031 }
drhd9e5c4f2010-05-12 18:01:39 +00004032
danda9fe0c2010-07-13 18:44:03 +00004033 p = pDbFd->pShm;
4034 pShmNode = p->pShmNode;
4035 sqlite3_mutex_enter(pShmNode->mutex);
4036 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004037 assert( pShmNode->pInode==pDbFd->pInode );
4038 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4039 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004040
4041 if( pShmNode->nRegion<=iRegion ){
4042 char **apNew; /* New apRegion[] array */
4043 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4044 struct stat sStat; /* Used by fstat() */
4045
4046 pShmNode->szRegion = szRegion;
4047
drh3cb93392011-03-12 18:10:44 +00004048 if( pShmNode->h>=0 ){
4049 /* The requested region is not mapped into this processes address space.
4050 ** Check to see if it has been allocated (i.e. if the wal-index file is
4051 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004052 */
drh3cb93392011-03-12 18:10:44 +00004053 if( osFstat(pShmNode->h, &sStat) ){
4054 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004055 goto shmpage_out;
4056 }
drh3cb93392011-03-12 18:10:44 +00004057
4058 if( sStat.st_size<nByte ){
4059 /* The requested memory region does not exist. If bExtend is set to
4060 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4061 **
4062 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4063 ** the requested memory region.
4064 */
4065 if( !bExtend ) goto shmpage_out;
4066 if( robust_ftruncate(pShmNode->h, nByte) ){
4067 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4068 pShmNode->zFilename);
4069 goto shmpage_out;
4070 }
4071 }
danda9fe0c2010-07-13 18:44:03 +00004072 }
4073
4074 /* Map the requested memory region into this processes address space. */
4075 apNew = (char **)sqlite3_realloc(
4076 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4077 );
4078 if( !apNew ){
4079 rc = SQLITE_IOERR_NOMEM;
4080 goto shmpage_out;
4081 }
4082 pShmNode->apRegion = apNew;
4083 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004084 void *pMem;
4085 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004086 pMem = mmap(0, szRegion,
4087 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004088 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4089 );
4090 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004091 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004092 goto shmpage_out;
4093 }
4094 }else{
4095 pMem = sqlite3_malloc(szRegion);
4096 if( pMem==0 ){
4097 rc = SQLITE_NOMEM;
4098 goto shmpage_out;
4099 }
4100 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004101 }
4102 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4103 pShmNode->nRegion++;
4104 }
4105 }
4106
4107shmpage_out:
4108 if( pShmNode->nRegion>iRegion ){
4109 *pp = pShmNode->apRegion[iRegion];
4110 }else{
4111 *pp = 0;
4112 }
drh66dfec8b2011-06-01 20:01:49 +00004113 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004114 sqlite3_mutex_leave(pShmNode->mutex);
4115 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004116}
4117
4118/*
drhd9e5c4f2010-05-12 18:01:39 +00004119** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004120**
4121** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4122** different here than in posix. In xShmLock(), one can go from unlocked
4123** to shared and back or from unlocked to exclusive and back. But one may
4124** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004125*/
4126static int unixShmLock(
4127 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004128 int ofst, /* First lock to acquire or release */
4129 int n, /* Number of locks to acquire or release */
4130 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004131){
drh73b64e42010-05-30 19:55:15 +00004132 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4133 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4134 unixShm *pX; /* For looping over all siblings */
4135 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4136 int rc = SQLITE_OK; /* Result code */
4137 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004138
drhd91c68f2010-05-14 14:52:25 +00004139 assert( pShmNode==pDbFd->pInode->pShmNode );
4140 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004141 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004142 assert( n>=1 );
4143 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4144 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4145 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4146 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4147 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004148 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4149 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004150
drhc99597c2010-05-31 01:41:15 +00004151 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004152 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004153 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004154 if( flags & SQLITE_SHM_UNLOCK ){
4155 u16 allMask = 0; /* Mask of locks held by siblings */
4156
4157 /* See if any siblings hold this same lock */
4158 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4159 if( pX==p ) continue;
4160 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4161 allMask |= pX->sharedMask;
4162 }
4163
4164 /* Unlock the system-level locks */
4165 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004166 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004167 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004168 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004169 }
drh73b64e42010-05-30 19:55:15 +00004170
4171 /* Undo the local locks */
4172 if( rc==SQLITE_OK ){
4173 p->exclMask &= ~mask;
4174 p->sharedMask &= ~mask;
4175 }
4176 }else if( flags & SQLITE_SHM_SHARED ){
4177 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4178
4179 /* Find out which shared locks are already held by sibling connections.
4180 ** If any sibling already holds an exclusive lock, go ahead and return
4181 ** SQLITE_BUSY.
4182 */
4183 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004184 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004185 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004186 break;
4187 }
4188 allShared |= pX->sharedMask;
4189 }
4190
4191 /* Get shared locks at the system level, if necessary */
4192 if( rc==SQLITE_OK ){
4193 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004194 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004195 }else{
drh73b64e42010-05-30 19:55:15 +00004196 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004197 }
drhd9e5c4f2010-05-12 18:01:39 +00004198 }
drh73b64e42010-05-30 19:55:15 +00004199
4200 /* Get the local shared locks */
4201 if( rc==SQLITE_OK ){
4202 p->sharedMask |= mask;
4203 }
4204 }else{
4205 /* Make sure no sibling connections hold locks that will block this
4206 ** lock. If any do, return SQLITE_BUSY right away.
4207 */
4208 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004209 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4210 rc = SQLITE_BUSY;
4211 break;
4212 }
4213 }
4214
4215 /* Get the exclusive locks at the system level. Then if successful
4216 ** also mark the local connection as being locked.
4217 */
4218 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004219 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004220 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004221 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004222 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004223 }
drhd9e5c4f2010-05-12 18:01:39 +00004224 }
4225 }
drhd91c68f2010-05-14 14:52:25 +00004226 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004227 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4228 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004229 return rc;
4230}
4231
drh286a2882010-05-20 23:51:06 +00004232/*
4233** Implement a memory barrier or memory fence on shared memory.
4234**
4235** All loads and stores begun before the barrier must complete before
4236** any load or store begun after the barrier.
4237*/
4238static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004239 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004240){
drhff828942010-06-26 21:34:06 +00004241 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004242 unixEnterMutex();
4243 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004244}
4245
dan18801912010-06-14 14:07:50 +00004246/*
danda9fe0c2010-07-13 18:44:03 +00004247** Close a connection to shared-memory. Delete the underlying
4248** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004249**
4250** If there is no shared memory associated with the connection then this
4251** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004252*/
danda9fe0c2010-07-13 18:44:03 +00004253static int unixShmUnmap(
4254 sqlite3_file *fd, /* The underlying database file */
4255 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004256){
danda9fe0c2010-07-13 18:44:03 +00004257 unixShm *p; /* The connection to be closed */
4258 unixShmNode *pShmNode; /* The underlying shared-memory file */
4259 unixShm **pp; /* For looping over sibling connections */
4260 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004261
danda9fe0c2010-07-13 18:44:03 +00004262 pDbFd = (unixFile*)fd;
4263 p = pDbFd->pShm;
4264 if( p==0 ) return SQLITE_OK;
4265 pShmNode = p->pShmNode;
4266
4267 assert( pShmNode==pDbFd->pInode->pShmNode );
4268 assert( pShmNode->pInode==pDbFd->pInode );
4269
4270 /* Remove connection p from the set of connections associated
4271 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004272 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004273 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4274 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004275
danda9fe0c2010-07-13 18:44:03 +00004276 /* Free the connection p */
4277 sqlite3_free(p);
4278 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004279 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004280
4281 /* If pShmNode->nRef has reached 0, then close the underlying
4282 ** shared-memory file, too */
4283 unixEnterMutex();
4284 assert( pShmNode->nRef>0 );
4285 pShmNode->nRef--;
4286 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004287 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004288 unixShmPurge(pDbFd);
4289 }
4290 unixLeaveMutex();
4291
4292 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004293}
drh286a2882010-05-20 23:51:06 +00004294
danda9fe0c2010-07-13 18:44:03 +00004295
drhd9e5c4f2010-05-12 18:01:39 +00004296#else
drh6b017cc2010-06-14 18:01:46 +00004297# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004298# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004299# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004300# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004301#endif /* #ifndef SQLITE_OMIT_WAL */
4302
drh734c9862008-11-28 15:37:20 +00004303/*
4304** Here ends the implementation of all sqlite3_file methods.
4305**
4306********************** End sqlite3_file Methods *******************************
4307******************************************************************************/
4308
4309/*
drh6b9d6dd2008-12-03 19:34:47 +00004310** This division contains definitions of sqlite3_io_methods objects that
4311** implement various file locking strategies. It also contains definitions
4312** of "finder" functions. A finder-function is used to locate the appropriate
4313** sqlite3_io_methods object for a particular database file. The pAppData
4314** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4315** the correct finder-function for that VFS.
4316**
4317** Most finder functions return a pointer to a fixed sqlite3_io_methods
4318** object. The only interesting finder-function is autolockIoFinder, which
4319** looks at the filesystem type and tries to guess the best locking
4320** strategy from that.
4321**
drh1875f7a2008-12-08 18:19:17 +00004322** For finder-funtion F, two objects are created:
4323**
4324** (1) The real finder-function named "FImpt()".
4325**
dane946c392009-08-22 11:39:46 +00004326** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004327**
4328**
4329** A pointer to the F pointer is used as the pAppData value for VFS
4330** objects. We have to do this instead of letting pAppData point
4331** directly at the finder-function since C90 rules prevent a void*
4332** from be cast into a function pointer.
4333**
drh6b9d6dd2008-12-03 19:34:47 +00004334**
drh7708e972008-11-29 00:56:52 +00004335** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004336**
drh7708e972008-11-29 00:56:52 +00004337** * A constant sqlite3_io_methods object call METHOD that has locking
4338** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4339**
4340** * An I/O method finder function called FINDER that returns a pointer
4341** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004342*/
drhd9e5c4f2010-05-12 18:01:39 +00004343#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004344static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004345 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004346 CLOSE, /* xClose */ \
4347 unixRead, /* xRead */ \
4348 unixWrite, /* xWrite */ \
4349 unixTruncate, /* xTruncate */ \
4350 unixSync, /* xSync */ \
4351 unixFileSize, /* xFileSize */ \
4352 LOCK, /* xLock */ \
4353 UNLOCK, /* xUnlock */ \
4354 CKLOCK, /* xCheckReservedLock */ \
4355 unixFileControl, /* xFileControl */ \
4356 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004357 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004358 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004359 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004360 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004361 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004362}; \
drh0c2694b2009-09-03 16:23:44 +00004363static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4364 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004365 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004366} \
drh0c2694b2009-09-03 16:23:44 +00004367static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004368 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004369
4370/*
4371** Here are all of the sqlite3_io_methods objects for each of the
4372** locking strategies. Functions that return pointers to these methods
4373** are also created.
4374*/
4375IOMETHODS(
4376 posixIoFinder, /* Finder function name */
4377 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004378 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004379 unixClose, /* xClose method */
4380 unixLock, /* xLock method */
4381 unixUnlock, /* xUnlock method */
4382 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004383)
drh7708e972008-11-29 00:56:52 +00004384IOMETHODS(
4385 nolockIoFinder, /* Finder function name */
4386 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004387 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004388 nolockClose, /* xClose method */
4389 nolockLock, /* xLock method */
4390 nolockUnlock, /* xUnlock method */
4391 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004392)
drh7708e972008-11-29 00:56:52 +00004393IOMETHODS(
4394 dotlockIoFinder, /* Finder function name */
4395 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004396 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004397 dotlockClose, /* xClose method */
4398 dotlockLock, /* xLock method */
4399 dotlockUnlock, /* xUnlock method */
4400 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004401)
drh7708e972008-11-29 00:56:52 +00004402
chw78a13182009-04-07 05:35:03 +00004403#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004404IOMETHODS(
4405 flockIoFinder, /* Finder function name */
4406 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004407 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004408 flockClose, /* xClose method */
4409 flockLock, /* xLock method */
4410 flockUnlock, /* xUnlock method */
4411 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004412)
drh7708e972008-11-29 00:56:52 +00004413#endif
4414
drh6c7d5c52008-11-21 20:32:33 +00004415#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004416IOMETHODS(
4417 semIoFinder, /* Finder function name */
4418 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004419 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004420 semClose, /* xClose method */
4421 semLock, /* xLock method */
4422 semUnlock, /* xUnlock method */
4423 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004424)
aswiftaebf4132008-11-21 00:10:35 +00004425#endif
drh7708e972008-11-29 00:56:52 +00004426
drhd2cb50b2009-01-09 21:41:17 +00004427#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004428IOMETHODS(
4429 afpIoFinder, /* Finder function name */
4430 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004431 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004432 afpClose, /* xClose method */
4433 afpLock, /* xLock method */
4434 afpUnlock, /* xUnlock method */
4435 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004436)
drh715ff302008-12-03 22:32:44 +00004437#endif
4438
4439/*
4440** The proxy locking method is a "super-method" in the sense that it
4441** opens secondary file descriptors for the conch and lock files and
4442** it uses proxy, dot-file, AFP, and flock() locking methods on those
4443** secondary files. For this reason, the division that implements
4444** proxy locking is located much further down in the file. But we need
4445** to go ahead and define the sqlite3_io_methods and finder function
4446** for proxy locking here. So we forward declare the I/O methods.
4447*/
drhd2cb50b2009-01-09 21:41:17 +00004448#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004449static int proxyClose(sqlite3_file*);
4450static int proxyLock(sqlite3_file*, int);
4451static int proxyUnlock(sqlite3_file*, int);
4452static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004453IOMETHODS(
4454 proxyIoFinder, /* Finder function name */
4455 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004456 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004457 proxyClose, /* xClose method */
4458 proxyLock, /* xLock method */
4459 proxyUnlock, /* xUnlock method */
4460 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004461)
aswiftaebf4132008-11-21 00:10:35 +00004462#endif
drh7708e972008-11-29 00:56:52 +00004463
drh7ed97b92010-01-20 13:07:21 +00004464/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4465#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4466IOMETHODS(
4467 nfsIoFinder, /* Finder function name */
4468 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004469 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004470 unixClose, /* xClose method */
4471 unixLock, /* xLock method */
4472 nfsUnlock, /* xUnlock method */
4473 unixCheckReservedLock /* xCheckReservedLock method */
4474)
4475#endif
drh7708e972008-11-29 00:56:52 +00004476
drhd2cb50b2009-01-09 21:41:17 +00004477#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004478/*
drh6b9d6dd2008-12-03 19:34:47 +00004479** This "finder" function attempts to determine the best locking strategy
4480** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004481** object that implements that strategy.
4482**
4483** This is for MacOSX only.
4484*/
drh1875f7a2008-12-08 18:19:17 +00004485static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004486 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004487 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004488){
4489 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004490 const char *zFilesystem; /* Filesystem type name */
4491 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004492 } aMap[] = {
4493 { "hfs", &posixIoMethods },
4494 { "ufs", &posixIoMethods },
4495 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004496 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004497 { "webdav", &nolockIoMethods },
4498 { 0, 0 }
4499 };
4500 int i;
4501 struct statfs fsInfo;
4502 struct flock lockInfo;
4503
4504 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004505 /* If filePath==NULL that means we are dealing with a transient file
4506 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004507 return &nolockIoMethods;
4508 }
4509 if( statfs(filePath, &fsInfo) != -1 ){
4510 if( fsInfo.f_flags & MNT_RDONLY ){
4511 return &nolockIoMethods;
4512 }
4513 for(i=0; aMap[i].zFilesystem; i++){
4514 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4515 return aMap[i].pMethods;
4516 }
4517 }
4518 }
4519
4520 /* Default case. Handles, amongst others, "nfs".
4521 ** Test byte-range lock using fcntl(). If the call succeeds,
4522 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004523 */
drh7708e972008-11-29 00:56:52 +00004524 lockInfo.l_len = 1;
4525 lockInfo.l_start = 0;
4526 lockInfo.l_whence = SEEK_SET;
4527 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004528 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004529 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4530 return &nfsIoMethods;
4531 } else {
4532 return &posixIoMethods;
4533 }
drh7708e972008-11-29 00:56:52 +00004534 }else{
4535 return &dotlockIoMethods;
4536 }
4537}
drh0c2694b2009-09-03 16:23:44 +00004538static const sqlite3_io_methods
4539 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004540
drhd2cb50b2009-01-09 21:41:17 +00004541#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004542
chw78a13182009-04-07 05:35:03 +00004543#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4544/*
4545** This "finder" function attempts to determine the best locking strategy
4546** for the database file "filePath". It then returns the sqlite3_io_methods
4547** object that implements that strategy.
4548**
4549** This is for VXWorks only.
4550*/
4551static const sqlite3_io_methods *autolockIoFinderImpl(
4552 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004553 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004554){
4555 struct flock lockInfo;
4556
4557 if( !filePath ){
4558 /* If filePath==NULL that means we are dealing with a transient file
4559 ** that does not need to be locked. */
4560 return &nolockIoMethods;
4561 }
4562
4563 /* Test if fcntl() is supported and use POSIX style locks.
4564 ** Otherwise fall back to the named semaphore method.
4565 */
4566 lockInfo.l_len = 1;
4567 lockInfo.l_start = 0;
4568 lockInfo.l_whence = SEEK_SET;
4569 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004570 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004571 return &posixIoMethods;
4572 }else{
4573 return &semIoMethods;
4574 }
4575}
drh0c2694b2009-09-03 16:23:44 +00004576static const sqlite3_io_methods
4577 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004578
4579#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4580
drh7708e972008-11-29 00:56:52 +00004581/*
4582** An abstract type for a pointer to a IO method finder function:
4583*/
drh0c2694b2009-09-03 16:23:44 +00004584typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004585
aswiftaebf4132008-11-21 00:10:35 +00004586
drh734c9862008-11-28 15:37:20 +00004587/****************************************************************************
4588**************************** sqlite3_vfs methods ****************************
4589**
4590** This division contains the implementation of methods on the
4591** sqlite3_vfs object.
4592*/
4593
danielk1977a3d4c882007-03-23 10:08:38 +00004594/*
danielk1977e339d652008-06-28 11:23:00 +00004595** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004596*/
4597static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004598 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004599 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004600 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004601 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004602 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004603){
drh7708e972008-11-29 00:56:52 +00004604 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004605 unixFile *pNew = (unixFile *)pId;
4606 int rc = SQLITE_OK;
4607
drh8af6c222010-05-14 12:43:01 +00004608 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004609
dan00157392010-10-05 11:33:15 +00004610 /* Usually the path zFilename should not be a relative pathname. The
4611 ** exception is when opening the proxy "conch" file in builds that
4612 ** include the special Apple locking styles.
4613 */
dan00157392010-10-05 11:33:15 +00004614#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004615 assert( zFilename==0 || zFilename[0]=='/'
4616 || pVfs->pAppData==(void*)&autolockIoFinder );
4617#else
4618 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004619#endif
dan00157392010-10-05 11:33:15 +00004620
drhb07028f2011-10-14 21:49:18 +00004621 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004622 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004623
drh308c2a52010-05-14 11:30:18 +00004624 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004625 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004626 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004627 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004628 pNew->ctrlFlags = (u8)ctrlFlags;
4629 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4630 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004631 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004632 }
drha7e61d82011-03-12 17:02:57 +00004633 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004634 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004635 }
drh339eb0b2008-03-07 15:34:11 +00004636
drh6c7d5c52008-11-21 20:32:33 +00004637#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004638 pNew->pId = vxworksFindFileId(zFilename);
4639 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004640 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004641 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004642 }
4643#endif
4644
drhc02a43a2012-01-10 23:18:38 +00004645 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004646 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004647 }else{
drh0c2694b2009-09-03 16:23:44 +00004648 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004649#if SQLITE_ENABLE_LOCKING_STYLE
4650 /* Cache zFilename in the locking context (AFP and dotlock override) for
4651 ** proxyLock activation is possible (remote proxy is based on db name)
4652 ** zFilename remains valid until file is closed, to support */
4653 pNew->lockingContext = (void*)zFilename;
4654#endif
drhda0e7682008-07-30 15:27:54 +00004655 }
danielk1977e339d652008-06-28 11:23:00 +00004656
drh7ed97b92010-01-20 13:07:21 +00004657 if( pLockingStyle == &posixIoMethods
4658#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4659 || pLockingStyle == &nfsIoMethods
4660#endif
4661 ){
drh7708e972008-11-29 00:56:52 +00004662 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004663 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004664 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004665 /* If an error occured in findInodeInfo(), close the file descriptor
4666 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004667 ** in two scenarios:
4668 **
4669 ** (a) A call to fstat() failed.
4670 ** (b) A malloc failed.
4671 **
4672 ** Scenario (b) may only occur if the process is holding no other
4673 ** file descriptors open on the same file. If there were other file
4674 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004675 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004676 ** handle h - as it is guaranteed that no posix locks will be released
4677 ** by doing so.
4678 **
4679 ** If scenario (a) caused the error then things are not so safe. The
4680 ** implicit assumption here is that if fstat() fails, things are in
4681 ** such bad shape that dropping a lock or two doesn't matter much.
4682 */
drh0e9365c2011-03-02 02:08:13 +00004683 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004684 h = -1;
4685 }
drh7708e972008-11-29 00:56:52 +00004686 unixLeaveMutex();
4687 }
danielk1977e339d652008-06-28 11:23:00 +00004688
drhd2cb50b2009-01-09 21:41:17 +00004689#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004690 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004691 /* AFP locking uses the file path so it needs to be included in
4692 ** the afpLockingContext.
4693 */
4694 afpLockingContext *pCtx;
4695 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4696 if( pCtx==0 ){
4697 rc = SQLITE_NOMEM;
4698 }else{
4699 /* NB: zFilename exists and remains valid until the file is closed
4700 ** according to requirement F11141. So we do not need to make a
4701 ** copy of the filename. */
4702 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004703 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004704 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004705 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004706 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004707 if( rc!=SQLITE_OK ){
4708 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004709 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004710 h = -1;
4711 }
drh7708e972008-11-29 00:56:52 +00004712 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004713 }
drh7708e972008-11-29 00:56:52 +00004714 }
4715#endif
danielk1977e339d652008-06-28 11:23:00 +00004716
drh7708e972008-11-29 00:56:52 +00004717 else if( pLockingStyle == &dotlockIoMethods ){
4718 /* Dotfile locking uses the file path so it needs to be included in
4719 ** the dotlockLockingContext
4720 */
4721 char *zLockFile;
4722 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004723 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004724 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004725 zLockFile = (char *)sqlite3_malloc(nFilename);
4726 if( zLockFile==0 ){
4727 rc = SQLITE_NOMEM;
4728 }else{
4729 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004730 }
drh7708e972008-11-29 00:56:52 +00004731 pNew->lockingContext = zLockFile;
4732 }
danielk1977e339d652008-06-28 11:23:00 +00004733
drh6c7d5c52008-11-21 20:32:33 +00004734#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004735 else if( pLockingStyle == &semIoMethods ){
4736 /* Named semaphore locking uses the file path so it needs to be
4737 ** included in the semLockingContext
4738 */
4739 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004740 rc = findInodeInfo(pNew, &pNew->pInode);
4741 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4742 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004743 int n;
drh2238dcc2009-08-27 17:56:20 +00004744 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004745 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004746 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004747 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004748 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4749 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004750 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004751 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004752 }
chw97185482008-11-17 08:05:31 +00004753 }
drh7708e972008-11-29 00:56:52 +00004754 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004755 }
drh7708e972008-11-29 00:56:52 +00004756#endif
aswift5b1a2562008-08-22 00:22:35 +00004757
4758 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004759#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004760 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004761 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004762 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004763 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004764 isDelete = 0;
4765 }
drhc02a43a2012-01-10 23:18:38 +00004766 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004767#endif
danielk1977e339d652008-06-28 11:23:00 +00004768 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004769 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004770 }else{
drh7708e972008-11-29 00:56:52 +00004771 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004772 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004773 }
danielk1977e339d652008-06-28 11:23:00 +00004774 return rc;
drh054889e2005-11-30 03:20:31 +00004775}
drh9c06c952005-11-26 00:25:00 +00004776
danielk1977ad94b582007-08-20 06:44:22 +00004777/*
drh8b3cf822010-06-01 21:02:51 +00004778** Return the name of a directory in which to put temporary files.
4779** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004780*/
drh7234c6d2010-06-19 15:10:09 +00004781static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004782 static const char *azDirs[] = {
4783 0,
aswiftaebf4132008-11-21 00:10:35 +00004784 0,
danielk197717b90b52008-06-06 11:11:25 +00004785 "/var/tmp",
4786 "/usr/tmp",
4787 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004788 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004789 };
drh8b3cf822010-06-01 21:02:51 +00004790 unsigned int i;
4791 struct stat buf;
4792 const char *zDir = 0;
4793
4794 azDirs[0] = sqlite3_temp_directory;
4795 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004796 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004797 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004798 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004799 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004800 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004801 break;
4802 }
4803 return zDir;
4804}
4805
4806/*
4807** Create a temporary file name in zBuf. zBuf must be allocated
4808** by the calling process and must be big enough to hold at least
4809** pVfs->mxPathname bytes.
4810*/
4811static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004812 static const unsigned char zChars[] =
4813 "abcdefghijklmnopqrstuvwxyz"
4814 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4815 "0123456789";
drh41022642008-11-21 00:24:42 +00004816 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004817 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004818
4819 /* It's odd to simulate an io-error here, but really this is just
4820 ** using the io-error infrastructure to test that SQLite handles this
4821 ** function failing.
4822 */
4823 SimulateIOError( return SQLITE_IOERR );
4824
drh7234c6d2010-06-19 15:10:09 +00004825 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004826 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004827
4828 /* Check that the output buffer is large enough for the temporary file
4829 ** name. If it is not, return SQLITE_ERROR.
4830 */
drhc02a43a2012-01-10 23:18:38 +00004831 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004832 return SQLITE_ERROR;
4833 }
4834
4835 do{
drhc02a43a2012-01-10 23:18:38 +00004836 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004837 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004838 sqlite3_randomness(15, &zBuf[j]);
4839 for(i=0; i<15; i++, j++){
4840 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4841 }
4842 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00004843 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00004844 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004845 return SQLITE_OK;
4846}
4847
drhd2cb50b2009-01-09 21:41:17 +00004848#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004849/*
4850** Routine to transform a unixFile into a proxy-locking unixFile.
4851** Implementation in the proxy-lock division, but used by unixOpen()
4852** if SQLITE_PREFER_PROXY_LOCKING is defined.
4853*/
4854static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004855#endif
drhc66d5b62008-12-03 22:48:32 +00004856
dan08da86a2009-08-21 17:18:03 +00004857/*
4858** Search for an unused file descriptor that was opened on the database
4859** file (not a journal or master-journal file) identified by pathname
4860** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4861** argument to this function.
4862**
4863** Such a file descriptor may exist if a database connection was closed
4864** but the associated file descriptor could not be closed because some
4865** other file descriptor open on the same file is holding a file-lock.
4866** Refer to comments in the unixClose() function and the lengthy comment
4867** describing "Posix Advisory Locking" at the start of this file for
4868** further details. Also, ticket #4018.
4869**
4870** If a suitable file descriptor is found, then it is returned. If no
4871** such file descriptor is located, -1 is returned.
4872*/
dane946c392009-08-22 11:39:46 +00004873static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4874 UnixUnusedFd *pUnused = 0;
4875
4876 /* Do not search for an unused file descriptor on vxworks. Not because
4877 ** vxworks would not benefit from the change (it might, we're not sure),
4878 ** but because no way to test it is currently available. It is better
4879 ** not to risk breaking vxworks support for the sake of such an obscure
4880 ** feature. */
4881#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004882 struct stat sStat; /* Results of stat() call */
4883
4884 /* A stat() call may fail for various reasons. If this happens, it is
4885 ** almost certain that an open() call on the same path will also fail.
4886 ** For this reason, if an error occurs in the stat() call here, it is
4887 ** ignored and -1 is returned. The caller will try to open a new file
4888 ** descriptor on the same path, fail, and return an error to SQLite.
4889 **
4890 ** Even if a subsequent open() call does succeed, the consequences of
4891 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004892 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004893 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004894
4895 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004896 pInode = inodeList;
4897 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4898 || pInode->fileId.ino!=sStat.st_ino) ){
4899 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004900 }
drh8af6c222010-05-14 12:43:01 +00004901 if( pInode ){
dane946c392009-08-22 11:39:46 +00004902 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004903 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004904 pUnused = *pp;
4905 if( pUnused ){
4906 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004907 }
4908 }
4909 unixLeaveMutex();
4910 }
dane946c392009-08-22 11:39:46 +00004911#endif /* if !OS_VXWORKS */
4912 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004913}
danielk197717b90b52008-06-06 11:11:25 +00004914
4915/*
danddb0ac42010-07-14 14:48:58 +00004916** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004917** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004918** and a value suitable for passing as the third argument to open(2) is
4919** written to *pMode. If an IO error occurs, an SQLite error code is
4920** returned and the value of *pMode is not modified.
4921**
drh8c815d12012-02-13 20:16:37 +00004922** In most cases cases, this routine sets *pMode to 0, which will become
4923** an indication to robust_open() to create the file using
4924** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
4925** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00004926** this function queries the file-system for the permissions on the
4927** corresponding database file and sets *pMode to this value. Whenever
4928** possible, WAL and journal files are created using the same permissions
4929** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004930**
4931** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4932** original filename is unavailable. But 8_3_NAMES is only used for
4933** FAT filesystems and permissions do not matter there, so just use
4934** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004935*/
4936static int findCreateFileMode(
4937 const char *zPath, /* Path of file (possibly) being created */
4938 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00004939 mode_t *pMode, /* OUT: Permissions to open file with */
4940 uid_t *pUid, /* OUT: uid to set on the file */
4941 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00004942){
4943 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00004944 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00004945 *pUid = 0;
4946 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00004947 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004948 char zDb[MAX_PATHNAME+1]; /* Database file path */
4949 int nDb; /* Number of valid bytes in zDb */
4950 struct stat sStat; /* Output of stat() on database file */
4951
dana0c989d2010-11-05 18:07:37 +00004952 /* zPath is a path to a WAL or journal file. The following block derives
4953 ** the path to the associated database file from zPath. This block handles
4954 ** the following naming conventions:
4955 **
4956 ** "<path to db>-journal"
4957 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004958 ** "<path to db>-journalNN"
4959 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004960 **
drhd337c5b2011-10-20 18:23:35 +00004961 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004962 ** used by the test_multiplex.c module.
4963 */
4964 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004965#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004966 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004967 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004968#else
4969 while( zPath[nDb]!='-' ){
4970 assert( nDb>0 );
4971 assert( zPath[nDb]!='\n' );
4972 nDb--;
4973 }
4974#endif
danddb0ac42010-07-14 14:48:58 +00004975 memcpy(zDb, zPath, nDb);
4976 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004977
drh58384f12011-07-28 00:14:45 +00004978 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004979 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00004980 *pUid = sStat.st_uid;
4981 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00004982 }else{
4983 rc = SQLITE_IOERR_FSTAT;
4984 }
4985 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4986 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004987 }
4988 return rc;
4989}
4990
4991/*
danielk1977ad94b582007-08-20 06:44:22 +00004992** Open the file zPath.
4993**
danielk1977b4b47412007-08-17 15:53:36 +00004994** Previously, the SQLite OS layer used three functions in place of this
4995** one:
4996**
4997** sqlite3OsOpenReadWrite();
4998** sqlite3OsOpenReadOnly();
4999** sqlite3OsOpenExclusive();
5000**
5001** These calls correspond to the following combinations of flags:
5002**
5003** ReadWrite() -> (READWRITE | CREATE)
5004** ReadOnly() -> (READONLY)
5005** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5006**
5007** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5008** true, the file was configured to be automatically deleted when the
5009** file handle closed. To achieve the same effect using this new
5010** interface, add the DELETEONCLOSE flag to those specified above for
5011** OpenExclusive().
5012*/
5013static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005014 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5015 const char *zPath, /* Pathname of file to be opened */
5016 sqlite3_file *pFile, /* The file descriptor to be filled in */
5017 int flags, /* Input flags to control the opening */
5018 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005019){
dan08da86a2009-08-21 17:18:03 +00005020 unixFile *p = (unixFile *)pFile;
5021 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005022 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005023 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005024 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005025 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005026 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005027
5028 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5029 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5030 int isCreate = (flags & SQLITE_OPEN_CREATE);
5031 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5032 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005033#if SQLITE_ENABLE_LOCKING_STYLE
5034 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5035#endif
drh3d4435b2011-08-26 20:55:50 +00005036#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5037 struct statfs fsInfo;
5038#endif
danielk1977b4b47412007-08-17 15:53:36 +00005039
danielk1977fee2d252007-08-18 10:59:19 +00005040 /* If creating a master or main-file journal, this function will open
5041 ** a file-descriptor on the directory too. The first time unixSync()
5042 ** is called the directory file descriptor will be fsync()ed and close()d.
5043 */
drh0059eae2011-08-08 23:48:40 +00005044 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005045 eType==SQLITE_OPEN_MASTER_JOURNAL
5046 || eType==SQLITE_OPEN_MAIN_JOURNAL
5047 || eType==SQLITE_OPEN_WAL
5048 ));
danielk1977fee2d252007-08-18 10:59:19 +00005049
danielk197717b90b52008-06-06 11:11:25 +00005050 /* If argument zPath is a NULL pointer, this function is required to open
5051 ** a temporary file. Use this buffer to store the file name in.
5052 */
drhc02a43a2012-01-10 23:18:38 +00005053 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005054 const char *zName = zPath;
5055
danielk1977fee2d252007-08-18 10:59:19 +00005056 /* Check the following statements are true:
5057 **
5058 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5059 ** (b) if CREATE is set, then READWRITE must also be set, and
5060 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005061 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005062 */
danielk1977b4b47412007-08-17 15:53:36 +00005063 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005064 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005065 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005066 assert(isDelete==0 || isCreate);
5067
danddb0ac42010-07-14 14:48:58 +00005068 /* The main DB, main journal, WAL file and master journal are never
5069 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005070 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5071 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5072 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005073 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005074
danielk1977fee2d252007-08-18 10:59:19 +00005075 /* Assert that the upper layer has set one of the "file-type" flags. */
5076 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5077 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5078 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005079 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005080 );
5081
dan08da86a2009-08-21 17:18:03 +00005082 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005083
dan08da86a2009-08-21 17:18:03 +00005084 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005085 UnixUnusedFd *pUnused;
5086 pUnused = findReusableFd(zName, flags);
5087 if( pUnused ){
5088 fd = pUnused->fd;
5089 }else{
dan6aa657f2009-08-24 18:57:58 +00005090 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005091 if( !pUnused ){
5092 return SQLITE_NOMEM;
5093 }
5094 }
5095 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005096
5097 /* Database filenames are double-zero terminated if they are not
5098 ** URIs with parameters. Hence, they can always be passed into
5099 ** sqlite3_uri_parameter(). */
5100 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5101
dan08da86a2009-08-21 17:18:03 +00005102 }else if( !zName ){
5103 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005104 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005105 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005106 if( rc!=SQLITE_OK ){
5107 return rc;
5108 }
5109 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005110
5111 /* Generated temporary filenames are always double-zero terminated
5112 ** for use by sqlite3_uri_parameter(). */
5113 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005114 }
5115
dan08da86a2009-08-21 17:18:03 +00005116 /* Determine the value of the flags parameter passed to POSIX function
5117 ** open(). These must be calculated even if open() is not called, as
5118 ** they may be stored as part of the file handle and used by the
5119 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005120 if( isReadonly ) openFlags |= O_RDONLY;
5121 if( isReadWrite ) openFlags |= O_RDWR;
5122 if( isCreate ) openFlags |= O_CREAT;
5123 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5124 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005125
danielk1977b4b47412007-08-17 15:53:36 +00005126 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005127 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005128 uid_t uid; /* Userid for the file */
5129 gid_t gid; /* Groupid for the file */
5130 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005131 if( rc!=SQLITE_OK ){
5132 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005133 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005134 return rc;
5135 }
drhad4f1e52011-03-04 15:43:57 +00005136 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005137 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005138 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5139 /* Failed to open the file for read/write access. Try read-only. */
5140 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005141 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005142 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005143 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005144 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005145 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005146 }
5147 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005148 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005149 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005150 }
drhac7c3ac2012-02-11 19:23:48 +00005151
5152 /* If this process is running as root and if creating a new rollback
5153 ** journal or WAL file, set the ownership of the journal or WAL to be
5154 ** the same as the original database. If we are not running as root,
drh3ee34842012-02-11 21:21:17 +00005155 ** then the fchown() call will fail, but that's ok. The "if(){}" and
5156 ** the setting of the UNIXFILE_CHOWN flag are purely to silence compiler
5157 ** warnings from gcc.
drhac7c3ac2012-02-11 19:23:48 +00005158 */
5159 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh23c4b972012-02-11 23:55:15 +00005160 if( osFchown(fd, uid, gid)==0 ){ p->ctrlFlags |= UNIXFILE_CHOWN; }
drhac7c3ac2012-02-11 19:23:48 +00005161 }
danielk1977b4b47412007-08-17 15:53:36 +00005162 }
dan08da86a2009-08-21 17:18:03 +00005163 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005164 if( pOutFlags ){
5165 *pOutFlags = flags;
5166 }
5167
dane946c392009-08-22 11:39:46 +00005168 if( p->pUnused ){
5169 p->pUnused->fd = fd;
5170 p->pUnused->flags = flags;
5171 }
5172
danielk1977b4b47412007-08-17 15:53:36 +00005173 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005174#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005175 zPath = zName;
5176#else
drh036ac7f2011-08-08 23:18:05 +00005177 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005178#endif
danielk1977b4b47412007-08-17 15:53:36 +00005179 }
drh41022642008-11-21 00:24:42 +00005180#if SQLITE_ENABLE_LOCKING_STYLE
5181 else{
dan08da86a2009-08-21 17:18:03 +00005182 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005183 }
5184#endif
5185
danielk1977e339d652008-06-28 11:23:00 +00005186#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005187 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005188#endif
5189
drhda0e7682008-07-30 15:27:54 +00005190 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005191
drh7ed97b92010-01-20 13:07:21 +00005192
5193#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005194 if( fstatfs(fd, &fsInfo) == -1 ){
5195 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005196 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005197 return SQLITE_IOERR_ACCESS;
5198 }
5199 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5200 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5201 }
5202#endif
drhc02a43a2012-01-10 23:18:38 +00005203
5204 /* Set up appropriate ctrlFlags */
5205 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5206 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5207 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5208 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5209 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5210
drh7ed97b92010-01-20 13:07:21 +00005211#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005212#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005213 isAutoProxy = 1;
5214#endif
5215 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005216 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5217 int useProxy = 0;
5218
dan08da86a2009-08-21 17:18:03 +00005219 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5220 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005221 if( envforce!=NULL ){
5222 useProxy = atoi(envforce)>0;
5223 }else{
aswiftaebf4132008-11-21 00:10:35 +00005224 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005225 /* In theory, the close(fd) call is sub-optimal. If the file opened
5226 ** with fd is a database file, and there are other connections open
5227 ** on that file that are currently holding advisory locks on it,
5228 ** then the call to close() will cancel those locks. In practice,
5229 ** we're assuming that statfs() doesn't fail very often. At least
5230 ** not while other file descriptors opened by the same process on
5231 ** the same file are working. */
5232 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005233 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005234 rc = SQLITE_IOERR_ACCESS;
5235 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005236 }
5237 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5238 }
5239 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005240 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005241 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005242 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005243 if( rc!=SQLITE_OK ){
5244 /* Use unixClose to clean up the resources added in fillInUnixFile
5245 ** and clear all the structure's references. Specifically,
5246 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5247 */
5248 unixClose(pFile);
5249 return rc;
5250 }
aswiftaebf4132008-11-21 00:10:35 +00005251 }
dane946c392009-08-22 11:39:46 +00005252 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005253 }
5254 }
5255#endif
5256
drhc02a43a2012-01-10 23:18:38 +00005257 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5258
dane946c392009-08-22 11:39:46 +00005259open_finished:
5260 if( rc!=SQLITE_OK ){
5261 sqlite3_free(p->pUnused);
5262 }
5263 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005264}
5265
dane946c392009-08-22 11:39:46 +00005266
danielk1977b4b47412007-08-17 15:53:36 +00005267/*
danielk1977fee2d252007-08-18 10:59:19 +00005268** Delete the file at zPath. If the dirSync argument is true, fsync()
5269** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005270*/
drh6b9d6dd2008-12-03 19:34:47 +00005271static int unixDelete(
5272 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5273 const char *zPath, /* Name of file to be deleted */
5274 int dirSync /* If true, fsync() directory after deleting file */
5275){
danielk1977fee2d252007-08-18 10:59:19 +00005276 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005277 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005278 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005279 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005280 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005281 }
danielk1977d39fa702008-10-16 13:27:40 +00005282#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005283 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005284 int fd;
drh90315a22011-08-10 01:52:12 +00005285 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005286 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005287#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005288 if( fsync(fd)==-1 )
5289#else
5290 if( fsync(fd) )
5291#endif
5292 {
dane18d4952011-02-21 11:46:24 +00005293 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005294 }
drh0e9365c2011-03-02 02:08:13 +00005295 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005296 }else if( rc==SQLITE_CANTOPEN ){
5297 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005298 }
5299 }
danielk1977d138dd82008-10-15 16:02:48 +00005300#endif
danielk1977fee2d252007-08-18 10:59:19 +00005301 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005302}
5303
danielk197790949c22007-08-17 16:50:38 +00005304/*
5305** Test the existance of or access permissions of file zPath. The
5306** test performed depends on the value of flags:
5307**
5308** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5309** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5310** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5311**
5312** Otherwise return 0.
5313*/
danielk1977861f7452008-06-05 11:39:11 +00005314static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005315 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5316 const char *zPath, /* Path of the file to examine */
5317 int flags, /* What do we want to learn about the zPath file? */
5318 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005319){
rse25c0d1a2007-09-20 08:38:14 +00005320 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005321 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005322 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005323 switch( flags ){
5324 case SQLITE_ACCESS_EXISTS:
5325 amode = F_OK;
5326 break;
5327 case SQLITE_ACCESS_READWRITE:
5328 amode = W_OK|R_OK;
5329 break;
drh50d3f902007-08-27 21:10:36 +00005330 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005331 amode = R_OK;
5332 break;
5333
5334 default:
5335 assert(!"Invalid flags argument");
5336 }
drh99ab3b12011-03-02 15:09:07 +00005337 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005338 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5339 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005340 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005341 *pResOut = 0;
5342 }
5343 }
danielk1977861f7452008-06-05 11:39:11 +00005344 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005345}
5346
danielk1977b4b47412007-08-17 15:53:36 +00005347
5348/*
5349** Turn a relative pathname into a full pathname. The relative path
5350** is stored as a nul-terminated string in the buffer pointed to by
5351** zPath.
5352**
5353** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5354** (in this case, MAX_PATHNAME bytes). The full-path is written to
5355** this buffer before returning.
5356*/
danielk1977adfb9b02007-09-17 07:02:56 +00005357static int unixFullPathname(
5358 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5359 const char *zPath, /* Possibly relative input path */
5360 int nOut, /* Size of output buffer in bytes */
5361 char *zOut /* Output buffer */
5362){
danielk1977843e65f2007-09-01 16:16:15 +00005363
5364 /* It's odd to simulate an io-error here, but really this is just
5365 ** using the io-error infrastructure to test that SQLite handles this
5366 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005367 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005368 */
5369 SimulateIOError( return SQLITE_ERROR );
5370
drh153c62c2007-08-24 03:51:33 +00005371 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005372 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005373
drh3c7f2dc2007-12-06 13:26:20 +00005374 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005375 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005376 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005377 }else{
5378 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005379 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005380 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005381 }
drhea678832008-12-10 19:26:22 +00005382 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005383 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005384 }
5385 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005386}
5387
drh0ccebe72005-06-07 22:22:50 +00005388
drh761df872006-12-21 01:29:22 +00005389#ifndef SQLITE_OMIT_LOAD_EXTENSION
5390/*
5391** Interfaces for opening a shared library, finding entry points
5392** within the shared library, and closing the shared library.
5393*/
5394#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005395static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5396 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005397 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5398}
danielk197795c8a542007-09-01 06:51:27 +00005399
5400/*
5401** SQLite calls this function immediately after a call to unixDlSym() or
5402** unixDlOpen() fails (returns a null pointer). If a more detailed error
5403** message is available, it is written to zBufOut. If no error message
5404** is available, zBufOut is left unmodified and SQLite uses a default
5405** error message.
5406*/
danielk1977397d65f2008-11-19 11:35:39 +00005407static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005408 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005409 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005410 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005411 zErr = dlerror();
5412 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005413 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005414 }
drh6c7d5c52008-11-21 20:32:33 +00005415 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005416}
drh1875f7a2008-12-08 18:19:17 +00005417static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5418 /*
5419 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5420 ** cast into a pointer to a function. And yet the library dlsym() routine
5421 ** returns a void* which is really a pointer to a function. So how do we
5422 ** use dlsym() with -pedantic-errors?
5423 **
5424 ** Variable x below is defined to be a pointer to a function taking
5425 ** parameters void* and const char* and returning a pointer to a function.
5426 ** We initialize x by assigning it a pointer to the dlsym() function.
5427 ** (That assignment requires a cast.) Then we call the function that
5428 ** x points to.
5429 **
5430 ** This work-around is unlikely to work correctly on any system where
5431 ** you really cannot cast a function pointer into void*. But then, on the
5432 ** other hand, dlsym() will not work on such a system either, so we have
5433 ** not really lost anything.
5434 */
5435 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005436 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005437 x = (void(*(*)(void*,const char*))(void))dlsym;
5438 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005439}
danielk1977397d65f2008-11-19 11:35:39 +00005440static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5441 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005442 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005443}
danielk1977b4b47412007-08-17 15:53:36 +00005444#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5445 #define unixDlOpen 0
5446 #define unixDlError 0
5447 #define unixDlSym 0
5448 #define unixDlClose 0
5449#endif
5450
5451/*
danielk197790949c22007-08-17 16:50:38 +00005452** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005453*/
danielk1977397d65f2008-11-19 11:35:39 +00005454static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5455 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005456 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005457
drhbbd42a62004-05-22 17:41:58 +00005458 /* We have to initialize zBuf to prevent valgrind from reporting
5459 ** errors. The reports issued by valgrind are incorrect - we would
5460 ** prefer that the randomness be increased by making use of the
5461 ** uninitialized space in zBuf - but valgrind errors tend to worry
5462 ** some users. Rather than argue, it seems easier just to initialize
5463 ** the whole array and silence valgrind, even if that means less randomness
5464 ** in the random seed.
5465 **
5466 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005467 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005468 ** tests repeatable.
5469 */
danielk1977b4b47412007-08-17 15:53:36 +00005470 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005471#if !defined(SQLITE_TEST)
5472 {
drhc18b4042012-02-10 03:10:27 +00005473 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005474 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005475 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005476 time_t t;
5477 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005478 memcpy(zBuf, &t, sizeof(t));
5479 pid = getpid();
5480 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005481 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005482 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005483 }else{
drhc18b4042012-02-10 03:10:27 +00005484 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005485 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005486 }
drhbbd42a62004-05-22 17:41:58 +00005487 }
5488#endif
drh72cbd072008-10-14 17:58:38 +00005489 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005490}
5491
danielk1977b4b47412007-08-17 15:53:36 +00005492
drhbbd42a62004-05-22 17:41:58 +00005493/*
5494** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005495** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005496** The return value is the number of microseconds of sleep actually
5497** requested from the underlying operating system, a number which
5498** might be greater than or equal to the argument, but not less
5499** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005500*/
danielk1977397d65f2008-11-19 11:35:39 +00005501static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005502#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005503 struct timespec sp;
5504
5505 sp.tv_sec = microseconds / 1000000;
5506 sp.tv_nsec = (microseconds % 1000000) * 1000;
5507 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005508 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005509 return microseconds;
5510#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005511 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005512 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005513 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005514#else
danielk1977b4b47412007-08-17 15:53:36 +00005515 int seconds = (microseconds+999999)/1000000;
5516 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005517 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005518 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005519#endif
drh88f474a2006-01-02 20:00:12 +00005520}
5521
5522/*
drh6b9d6dd2008-12-03 19:34:47 +00005523** The following variable, if set to a non-zero value, is interpreted as
5524** the number of seconds since 1970 and is used to set the result of
5525** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005526*/
5527#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005528int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005529#endif
5530
5531/*
drhb7e8ea22010-05-03 14:32:30 +00005532** Find the current time (in Universal Coordinated Time). Write into *piNow
5533** the current time and date as a Julian Day number times 86_400_000. In
5534** other words, write into *piNow the number of milliseconds since the Julian
5535** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5536** proleptic Gregorian calendar.
5537**
drh31702252011-10-12 23:13:43 +00005538** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5539** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005540*/
5541static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5542 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005543 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005544#if defined(NO_GETTOD)
5545 time_t t;
5546 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005547 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005548#elif OS_VXWORKS
5549 struct timespec sNow;
5550 clock_gettime(CLOCK_REALTIME, &sNow);
5551 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5552#else
5553 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005554 if( gettimeofday(&sNow, 0)==0 ){
5555 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5556 }else{
5557 rc = SQLITE_ERROR;
5558 }
drhb7e8ea22010-05-03 14:32:30 +00005559#endif
5560
5561#ifdef SQLITE_TEST
5562 if( sqlite3_current_time ){
5563 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5564 }
5565#endif
5566 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005567 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005568}
5569
5570/*
drhbbd42a62004-05-22 17:41:58 +00005571** Find the current time (in Universal Coordinated Time). Write the
5572** current time and date as a Julian Day number into *prNow and
5573** return 0. Return 1 if the time and date cannot be found.
5574*/
danielk1977397d65f2008-11-19 11:35:39 +00005575static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005576 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005577 int rc;
drhff828942010-06-26 21:34:06 +00005578 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005579 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005580 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005581 return rc;
drhbbd42a62004-05-22 17:41:58 +00005582}
danielk1977b4b47412007-08-17 15:53:36 +00005583
drh6b9d6dd2008-12-03 19:34:47 +00005584/*
5585** We added the xGetLastError() method with the intention of providing
5586** better low-level error messages when operating-system problems come up
5587** during SQLite operation. But so far, none of that has been implemented
5588** in the core. So this routine is never called. For now, it is merely
5589** a place-holder.
5590*/
danielk1977397d65f2008-11-19 11:35:39 +00005591static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5592 UNUSED_PARAMETER(NotUsed);
5593 UNUSED_PARAMETER(NotUsed2);
5594 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005595 return 0;
5596}
5597
drhf2424c52010-04-26 00:04:55 +00005598
5599/*
drh734c9862008-11-28 15:37:20 +00005600************************ End of sqlite3_vfs methods ***************************
5601******************************************************************************/
5602
drh715ff302008-12-03 22:32:44 +00005603/******************************************************************************
5604************************** Begin Proxy Locking ********************************
5605**
5606** Proxy locking is a "uber-locking-method" in this sense: It uses the
5607** other locking methods on secondary lock files. Proxy locking is a
5608** meta-layer over top of the primitive locking implemented above. For
5609** this reason, the division that implements of proxy locking is deferred
5610** until late in the file (here) after all of the other I/O methods have
5611** been defined - so that the primitive locking methods are available
5612** as services to help with the implementation of proxy locking.
5613**
5614****
5615**
5616** The default locking schemes in SQLite use byte-range locks on the
5617** database file to coordinate safe, concurrent access by multiple readers
5618** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5619** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5620** as POSIX read & write locks over fixed set of locations (via fsctl),
5621** on AFP and SMB only exclusive byte-range locks are available via fsctl
5622** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5623** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5624** address in the shared range is taken for a SHARED lock, the entire
5625** shared range is taken for an EXCLUSIVE lock):
5626**
5627** PENDING_BYTE 0x40000000
5628** RESERVED_BYTE 0x40000001
5629** SHARED_RANGE 0x40000002 -> 0x40000200
5630**
5631** This works well on the local file system, but shows a nearly 100x
5632** slowdown in read performance on AFP because the AFP client disables
5633** the read cache when byte-range locks are present. Enabling the read
5634** cache exposes a cache coherency problem that is present on all OS X
5635** supported network file systems. NFS and AFP both observe the
5636** close-to-open semantics for ensuring cache coherency
5637** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5638** address the requirements for concurrent database access by multiple
5639** readers and writers
5640** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5641**
5642** To address the performance and cache coherency issues, proxy file locking
5643** changes the way database access is controlled by limiting access to a
5644** single host at a time and moving file locks off of the database file
5645** and onto a proxy file on the local file system.
5646**
5647**
5648** Using proxy locks
5649** -----------------
5650**
5651** C APIs
5652**
5653** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5654** <proxy_path> | ":auto:");
5655** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5656**
5657**
5658** SQL pragmas
5659**
5660** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5661** PRAGMA [database.]lock_proxy_file
5662**
5663** Specifying ":auto:" means that if there is a conch file with a matching
5664** host ID in it, the proxy path in the conch file will be used, otherwise
5665** a proxy path based on the user's temp dir
5666** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5667** actual proxy file name is generated from the name and path of the
5668** database file. For example:
5669**
5670** For database path "/Users/me/foo.db"
5671** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5672**
5673** Once a lock proxy is configured for a database connection, it can not
5674** be removed, however it may be switched to a different proxy path via
5675** the above APIs (assuming the conch file is not being held by another
5676** connection or process).
5677**
5678**
5679** How proxy locking works
5680** -----------------------
5681**
5682** Proxy file locking relies primarily on two new supporting files:
5683**
5684** * conch file to limit access to the database file to a single host
5685** at a time
5686**
5687** * proxy file to act as a proxy for the advisory locks normally
5688** taken on the database
5689**
5690** The conch file - to use a proxy file, sqlite must first "hold the conch"
5691** by taking an sqlite-style shared lock on the conch file, reading the
5692** contents and comparing the host's unique host ID (see below) and lock
5693** proxy path against the values stored in the conch. The conch file is
5694** stored in the same directory as the database file and the file name
5695** is patterned after the database file name as ".<databasename>-conch".
5696** If the conch file does not exist, or it's contents do not match the
5697** host ID and/or proxy path, then the lock is escalated to an exclusive
5698** lock and the conch file contents is updated with the host ID and proxy
5699** path and the lock is downgraded to a shared lock again. If the conch
5700** is held by another process (with a shared lock), the exclusive lock
5701** will fail and SQLITE_BUSY is returned.
5702**
5703** The proxy file - a single-byte file used for all advisory file locks
5704** normally taken on the database file. This allows for safe sharing
5705** of the database file for multiple readers and writers on the same
5706** host (the conch ensures that they all use the same local lock file).
5707**
drh715ff302008-12-03 22:32:44 +00005708** Requesting the lock proxy does not immediately take the conch, it is
5709** only taken when the first request to lock database file is made.
5710** This matches the semantics of the traditional locking behavior, where
5711** opening a connection to a database file does not take a lock on it.
5712** The shared lock and an open file descriptor are maintained until
5713** the connection to the database is closed.
5714**
5715** The proxy file and the lock file are never deleted so they only need
5716** to be created the first time they are used.
5717**
5718** Configuration options
5719** ---------------------
5720**
5721** SQLITE_PREFER_PROXY_LOCKING
5722**
5723** Database files accessed on non-local file systems are
5724** automatically configured for proxy locking, lock files are
5725** named automatically using the same logic as
5726** PRAGMA lock_proxy_file=":auto:"
5727**
5728** SQLITE_PROXY_DEBUG
5729**
5730** Enables the logging of error messages during host id file
5731** retrieval and creation
5732**
drh715ff302008-12-03 22:32:44 +00005733** LOCKPROXYDIR
5734**
5735** Overrides the default directory used for lock proxy files that
5736** are named automatically via the ":auto:" setting
5737**
5738** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5739**
5740** Permissions to use when creating a directory for storing the
5741** lock proxy files, only used when LOCKPROXYDIR is not set.
5742**
5743**
5744** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5745** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5746** force proxy locking to be used for every database file opened, and 0
5747** will force automatic proxy locking to be disabled for all database
5748** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5749** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5750*/
5751
5752/*
5753** Proxy locking is only available on MacOSX
5754*/
drhd2cb50b2009-01-09 21:41:17 +00005755#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005756
drh715ff302008-12-03 22:32:44 +00005757/*
5758** The proxyLockingContext has the path and file structures for the remote
5759** and local proxy files in it
5760*/
5761typedef struct proxyLockingContext proxyLockingContext;
5762struct proxyLockingContext {
5763 unixFile *conchFile; /* Open conch file */
5764 char *conchFilePath; /* Name of the conch file */
5765 unixFile *lockProxy; /* Open proxy lock file */
5766 char *lockProxyPath; /* Name of the proxy lock file */
5767 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005768 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005769 void *oldLockingContext; /* Original lockingcontext to restore on close */
5770 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5771};
5772
drh7ed97b92010-01-20 13:07:21 +00005773/*
5774** The proxy lock file path for the database at dbPath is written into lPath,
5775** which must point to valid, writable memory large enough for a maxLen length
5776** file path.
drh715ff302008-12-03 22:32:44 +00005777*/
drh715ff302008-12-03 22:32:44 +00005778static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5779 int len;
5780 int dbLen;
5781 int i;
5782
5783#ifdef LOCKPROXYDIR
5784 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5785#else
5786# ifdef _CS_DARWIN_USER_TEMP_DIR
5787 {
drh7ed97b92010-01-20 13:07:21 +00005788 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005789 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5790 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005791 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005792 }
drh7ed97b92010-01-20 13:07:21 +00005793 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005794 }
5795# else
5796 len = strlcpy(lPath, "/tmp/", maxLen);
5797# endif
5798#endif
5799
5800 if( lPath[len-1]!='/' ){
5801 len = strlcat(lPath, "/", maxLen);
5802 }
5803
5804 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005805 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005806 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005807 char c = dbPath[i];
5808 lPath[i+len] = (c=='/')?'_':c;
5809 }
5810 lPath[i+len]='\0';
5811 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005812 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005813 return SQLITE_OK;
5814}
5815
drh7ed97b92010-01-20 13:07:21 +00005816/*
5817 ** Creates the lock file and any missing directories in lockPath
5818 */
5819static int proxyCreateLockPath(const char *lockPath){
5820 int i, len;
5821 char buf[MAXPATHLEN];
5822 int start = 0;
5823
5824 assert(lockPath!=NULL);
5825 /* try to create all the intermediate directories */
5826 len = (int)strlen(lockPath);
5827 buf[0] = lockPath[0];
5828 for( i=1; i<len; i++ ){
5829 if( lockPath[i] == '/' && (i - start > 0) ){
5830 /* only mkdir if leaf dir != "." or "/" or ".." */
5831 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5832 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5833 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005834 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005835 int err=errno;
5836 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005837 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005838 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005839 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005840 return err;
5841 }
5842 }
5843 }
5844 start=i+1;
5845 }
5846 buf[i] = lockPath[i];
5847 }
drh308c2a52010-05-14 11:30:18 +00005848 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005849 return 0;
5850}
5851
drh715ff302008-12-03 22:32:44 +00005852/*
5853** Create a new VFS file descriptor (stored in memory obtained from
5854** sqlite3_malloc) and open the file named "path" in the file descriptor.
5855**
5856** The caller is responsible not only for closing the file descriptor
5857** but also for freeing the memory associated with the file descriptor.
5858*/
drh7ed97b92010-01-20 13:07:21 +00005859static int proxyCreateUnixFile(
5860 const char *path, /* path for the new unixFile */
5861 unixFile **ppFile, /* unixFile created and returned by ref */
5862 int islockfile /* if non zero missing dirs will be created */
5863) {
5864 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005865 unixFile *pNew;
5866 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005867 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005868 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005869 int terrno = 0;
5870 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005871
drh7ed97b92010-01-20 13:07:21 +00005872 /* 1. first try to open/create the file
5873 ** 2. if that fails, and this is a lock file (not-conch), try creating
5874 ** the parent directories and then try again.
5875 ** 3. if that fails, try to open the file read-only
5876 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5877 */
5878 pUnused = findReusableFd(path, openFlags);
5879 if( pUnused ){
5880 fd = pUnused->fd;
5881 }else{
5882 pUnused = sqlite3_malloc(sizeof(*pUnused));
5883 if( !pUnused ){
5884 return SQLITE_NOMEM;
5885 }
5886 }
5887 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00005888 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005889 terrno = errno;
5890 if( fd<0 && errno==ENOENT && islockfile ){
5891 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00005892 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005893 }
5894 }
5895 }
5896 if( fd<0 ){
5897 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00005898 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005899 terrno = errno;
5900 }
5901 if( fd<0 ){
5902 if( islockfile ){
5903 return SQLITE_BUSY;
5904 }
5905 switch (terrno) {
5906 case EACCES:
5907 return SQLITE_PERM;
5908 case EIO:
5909 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5910 default:
drh9978c972010-02-23 17:36:32 +00005911 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005912 }
5913 }
5914
5915 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5916 if( pNew==NULL ){
5917 rc = SQLITE_NOMEM;
5918 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005919 }
5920 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005921 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005922 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005923 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005924 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005925 pUnused->fd = fd;
5926 pUnused->flags = openFlags;
5927 pNew->pUnused = pUnused;
5928
drhc02a43a2012-01-10 23:18:38 +00005929 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00005930 if( rc==SQLITE_OK ){
5931 *ppFile = pNew;
5932 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005933 }
drh7ed97b92010-01-20 13:07:21 +00005934end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005935 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005936 sqlite3_free(pNew);
5937 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005938 return rc;
5939}
5940
drh7ed97b92010-01-20 13:07:21 +00005941#ifdef SQLITE_TEST
5942/* simulate multiple hosts by creating unique hostid file paths */
5943int sqlite3_hostid_num = 0;
5944#endif
5945
5946#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5947
drh0ab216a2010-07-02 17:10:40 +00005948/* Not always defined in the headers as it ought to be */
5949extern int gethostuuid(uuid_t id, const struct timespec *wait);
5950
drh7ed97b92010-01-20 13:07:21 +00005951/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5952** bytes of writable memory.
5953*/
5954static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005955 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5956 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005957#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5958 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005959 {
5960 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5961 if( gethostuuid(pHostID, &timeout) ){
5962 int err = errno;
5963 if( pError ){
5964 *pError = err;
5965 }
5966 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005967 }
drh7ed97b92010-01-20 13:07:21 +00005968 }
drh3d4435b2011-08-26 20:55:50 +00005969#else
5970 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005971#endif
drh7ed97b92010-01-20 13:07:21 +00005972#ifdef SQLITE_TEST
5973 /* simulate multiple hosts by creating unique hostid file paths */
5974 if( sqlite3_hostid_num != 0){
5975 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5976 }
5977#endif
5978
5979 return SQLITE_OK;
5980}
5981
5982/* The conch file contains the header, host id and lock file path
5983 */
5984#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5985#define PROXY_HEADERLEN 1 /* conch file header length */
5986#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5987#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5988
5989/*
5990** Takes an open conch file, copies the contents to a new path and then moves
5991** it back. The newly created file's file descriptor is assigned to the
5992** conch file structure and finally the original conch file descriptor is
5993** closed. Returns zero if successful.
5994*/
5995static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5996 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5997 unixFile *conchFile = pCtx->conchFile;
5998 char tPath[MAXPATHLEN];
5999 char buf[PROXY_MAXCONCHLEN];
6000 char *cPath = pCtx->conchFilePath;
6001 size_t readLen = 0;
6002 size_t pathLen = 0;
6003 char errmsg[64] = "";
6004 int fd = -1;
6005 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006006 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006007
6008 /* create a new path by replace the trailing '-conch' with '-break' */
6009 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6010 if( pathLen>MAXPATHLEN || pathLen<6 ||
6011 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006012 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006013 goto end_breaklock;
6014 }
6015 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006016 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006017 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006018 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006019 goto end_breaklock;
6020 }
6021 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006022 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006023 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006024 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006025 goto end_breaklock;
6026 }
drhe562be52011-03-02 18:01:10 +00006027 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006028 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006029 goto end_breaklock;
6030 }
6031 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006032 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006033 goto end_breaklock;
6034 }
6035 rc = 0;
6036 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006037 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006038 conchFile->h = fd;
6039 conchFile->openFlags = O_RDWR | O_CREAT;
6040
6041end_breaklock:
6042 if( rc ){
6043 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006044 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006045 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006046 }
6047 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6048 }
6049 return rc;
6050}
6051
6052/* Take the requested lock on the conch file and break a stale lock if the
6053** host id matches.
6054*/
6055static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6056 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6057 unixFile *conchFile = pCtx->conchFile;
6058 int rc = SQLITE_OK;
6059 int nTries = 0;
6060 struct timespec conchModTime;
6061
drh3d4435b2011-08-26 20:55:50 +00006062 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006063 do {
6064 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6065 nTries ++;
6066 if( rc==SQLITE_BUSY ){
6067 /* If the lock failed (busy):
6068 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6069 * 2nd try: fail if the mod time changed or host id is different, wait
6070 * 10 sec and try again
6071 * 3rd try: break the lock unless the mod time has changed.
6072 */
6073 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006074 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006075 pFile->lastErrno = errno;
6076 return SQLITE_IOERR_LOCK;
6077 }
6078
6079 if( nTries==1 ){
6080 conchModTime = buf.st_mtimespec;
6081 usleep(500000); /* wait 0.5 sec and try the lock again*/
6082 continue;
6083 }
6084
6085 assert( nTries>1 );
6086 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6087 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6088 return SQLITE_BUSY;
6089 }
6090
6091 if( nTries==2 ){
6092 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006093 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006094 if( len<0 ){
6095 pFile->lastErrno = errno;
6096 return SQLITE_IOERR_LOCK;
6097 }
6098 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6099 /* don't break the lock if the host id doesn't match */
6100 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6101 return SQLITE_BUSY;
6102 }
6103 }else{
6104 /* don't break the lock on short read or a version mismatch */
6105 return SQLITE_BUSY;
6106 }
6107 usleep(10000000); /* wait 10 sec and try the lock again */
6108 continue;
6109 }
6110
6111 assert( nTries==3 );
6112 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6113 rc = SQLITE_OK;
6114 if( lockType==EXCLUSIVE_LOCK ){
6115 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6116 }
6117 if( !rc ){
6118 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6119 }
6120 }
6121 }
6122 } while( rc==SQLITE_BUSY && nTries<3 );
6123
6124 return rc;
6125}
6126
6127/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006128** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6129** lockPath means that the lockPath in the conch file will be used if the
6130** host IDs match, or a new lock path will be generated automatically
6131** and written to the conch file.
6132*/
6133static int proxyTakeConch(unixFile *pFile){
6134 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6135
drh7ed97b92010-01-20 13:07:21 +00006136 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006137 return SQLITE_OK;
6138 }else{
6139 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006140 uuid_t myHostID;
6141 int pError = 0;
6142 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006143 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006144 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006145 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006146 int createConch = 0;
6147 int hostIdMatch = 0;
6148 int readLen = 0;
6149 int tryOldLockPath = 0;
6150 int forceNewLockPath = 0;
6151
drh308c2a52010-05-14 11:30:18 +00006152 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6153 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006154
drh7ed97b92010-01-20 13:07:21 +00006155 rc = proxyGetHostID(myHostID, &pError);
6156 if( (rc&0xff)==SQLITE_IOERR ){
6157 pFile->lastErrno = pError;
6158 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006159 }
drh7ed97b92010-01-20 13:07:21 +00006160 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006161 if( rc!=SQLITE_OK ){
6162 goto end_takeconch;
6163 }
drh7ed97b92010-01-20 13:07:21 +00006164 /* read the existing conch file */
6165 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6166 if( readLen<0 ){
6167 /* I/O error: lastErrno set by seekAndRead */
6168 pFile->lastErrno = conchFile->lastErrno;
6169 rc = SQLITE_IOERR_READ;
6170 goto end_takeconch;
6171 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6172 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6173 /* a short read or version format mismatch means we need to create a new
6174 ** conch file.
6175 */
6176 createConch = 1;
6177 }
6178 /* if the host id matches and the lock path already exists in the conch
6179 ** we'll try to use the path there, if we can't open that path, we'll
6180 ** retry with a new auto-generated path
6181 */
6182 do { /* in case we need to try again for an :auto: named lock file */
6183
6184 if( !createConch && !forceNewLockPath ){
6185 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6186 PROXY_HOSTIDLEN);
6187 /* if the conch has data compare the contents */
6188 if( !pCtx->lockProxyPath ){
6189 /* for auto-named local lock file, just check the host ID and we'll
6190 ** use the local lock file path that's already in there
6191 */
6192 if( hostIdMatch ){
6193 size_t pathLen = (readLen - PROXY_PATHINDEX);
6194
6195 if( pathLen>=MAXPATHLEN ){
6196 pathLen=MAXPATHLEN-1;
6197 }
6198 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6199 lockPath[pathLen] = 0;
6200 tempLockPath = lockPath;
6201 tryOldLockPath = 1;
6202 /* create a copy of the lock path if the conch is taken */
6203 goto end_takeconch;
6204 }
6205 }else if( hostIdMatch
6206 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6207 readLen-PROXY_PATHINDEX)
6208 ){
6209 /* conch host and lock path match */
6210 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006211 }
drh7ed97b92010-01-20 13:07:21 +00006212 }
6213
6214 /* if the conch isn't writable and doesn't match, we can't take it */
6215 if( (conchFile->openFlags&O_RDWR) == 0 ){
6216 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006217 goto end_takeconch;
6218 }
drh7ed97b92010-01-20 13:07:21 +00006219
6220 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006221 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006222 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6223 tempLockPath = lockPath;
6224 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006225 }
drh7ed97b92010-01-20 13:07:21 +00006226
6227 /* update conch with host and path (this will fail if other process
6228 ** has a shared lock already), if the host id matches, use the big
6229 ** stick.
drh715ff302008-12-03 22:32:44 +00006230 */
drh7ed97b92010-01-20 13:07:21 +00006231 futimes(conchFile->h, NULL);
6232 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006233 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006234 /* We are trying for an exclusive lock but another thread in this
6235 ** same process is still holding a shared lock. */
6236 rc = SQLITE_BUSY;
6237 } else {
6238 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006239 }
drh715ff302008-12-03 22:32:44 +00006240 }else{
drh7ed97b92010-01-20 13:07:21 +00006241 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006242 }
drh7ed97b92010-01-20 13:07:21 +00006243 if( rc==SQLITE_OK ){
6244 char writeBuffer[PROXY_MAXCONCHLEN];
6245 int writeSize = 0;
6246
6247 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6248 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6249 if( pCtx->lockProxyPath!=NULL ){
6250 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6251 }else{
6252 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6253 }
6254 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006255 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006256 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6257 fsync(conchFile->h);
6258 /* If we created a new conch file (not just updated the contents of a
6259 ** valid conch file), try to match the permissions of the database
6260 */
6261 if( rc==SQLITE_OK && createConch ){
6262 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006263 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006264 if( err==0 ){
6265 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6266 S_IROTH|S_IWOTH);
6267 /* try to match the database file R/W permissions, ignore failure */
6268#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006269 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006270#else
drhff812312011-02-23 13:33:46 +00006271 do{
drhe562be52011-03-02 18:01:10 +00006272 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006273 }while( rc==(-1) && errno==EINTR );
6274 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006275 int code = errno;
6276 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6277 cmode, code, strerror(code));
6278 } else {
6279 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6280 }
6281 }else{
6282 int code = errno;
6283 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6284 err, code, strerror(code));
6285#endif
6286 }
drh715ff302008-12-03 22:32:44 +00006287 }
6288 }
drh7ed97b92010-01-20 13:07:21 +00006289 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6290
6291 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006292 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006293 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006294 int fd;
drh7ed97b92010-01-20 13:07:21 +00006295 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006296 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006297 }
6298 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006299 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006300 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006301 if( fd>=0 ){
6302 pFile->h = fd;
6303 }else{
drh9978c972010-02-23 17:36:32 +00006304 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006305 during locking */
6306 }
6307 }
6308 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6309 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6310 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6311 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6312 /* we couldn't create the proxy lock file with the old lock file path
6313 ** so try again via auto-naming
6314 */
6315 forceNewLockPath = 1;
6316 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006317 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006318 }
6319 }
6320 if( rc==SQLITE_OK ){
6321 /* Need to make a copy of path if we extracted the value
6322 ** from the conch file or the path was allocated on the stack
6323 */
6324 if( tempLockPath ){
6325 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6326 if( !pCtx->lockProxyPath ){
6327 rc = SQLITE_NOMEM;
6328 }
6329 }
6330 }
6331 if( rc==SQLITE_OK ){
6332 pCtx->conchHeld = 1;
6333
6334 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6335 afpLockingContext *afpCtx;
6336 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6337 afpCtx->dbPath = pCtx->lockProxyPath;
6338 }
6339 } else {
6340 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6341 }
drh308c2a52010-05-14 11:30:18 +00006342 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6343 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006344 return rc;
drh308c2a52010-05-14 11:30:18 +00006345 } while (1); /* in case we need to retry the :auto: lock file -
6346 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006347 }
6348}
6349
6350/*
6351** If pFile holds a lock on a conch file, then release that lock.
6352*/
6353static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006354 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006355 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6356 unixFile *conchFile; /* Name of the conch file */
6357
6358 pCtx = (proxyLockingContext *)pFile->lockingContext;
6359 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006360 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006361 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006362 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006363 if( pCtx->conchHeld>0 ){
6364 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6365 }
drh715ff302008-12-03 22:32:44 +00006366 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006367 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6368 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006369 return rc;
6370}
6371
6372/*
6373** Given the name of a database file, compute the name of its conch file.
6374** Store the conch filename in memory obtained from sqlite3_malloc().
6375** Make *pConchPath point to the new name. Return SQLITE_OK on success
6376** or SQLITE_NOMEM if unable to obtain memory.
6377**
6378** The caller is responsible for ensuring that the allocated memory
6379** space is eventually freed.
6380**
6381** *pConchPath is set to NULL if a memory allocation error occurs.
6382*/
6383static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6384 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006385 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006386 char *conchPath; /* buffer in which to construct conch name */
6387
6388 /* Allocate space for the conch filename and initialize the name to
6389 ** the name of the original database file. */
6390 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6391 if( conchPath==0 ){
6392 return SQLITE_NOMEM;
6393 }
6394 memcpy(conchPath, dbPath, len+1);
6395
6396 /* now insert a "." before the last / character */
6397 for( i=(len-1); i>=0; i-- ){
6398 if( conchPath[i]=='/' ){
6399 i++;
6400 break;
6401 }
6402 }
6403 conchPath[i]='.';
6404 while ( i<len ){
6405 conchPath[i+1]=dbPath[i];
6406 i++;
6407 }
6408
6409 /* append the "-conch" suffix to the file */
6410 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006411 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006412
6413 return SQLITE_OK;
6414}
6415
6416
6417/* Takes a fully configured proxy locking-style unix file and switches
6418** the local lock file path
6419*/
6420static int switchLockProxyPath(unixFile *pFile, const char *path) {
6421 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6422 char *oldPath = pCtx->lockProxyPath;
6423 int rc = SQLITE_OK;
6424
drh308c2a52010-05-14 11:30:18 +00006425 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006426 return SQLITE_BUSY;
6427 }
6428
6429 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6430 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6431 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6432 return SQLITE_OK;
6433 }else{
6434 unixFile *lockProxy = pCtx->lockProxy;
6435 pCtx->lockProxy=NULL;
6436 pCtx->conchHeld = 0;
6437 if( lockProxy!=NULL ){
6438 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6439 if( rc ) return rc;
6440 sqlite3_free(lockProxy);
6441 }
6442 sqlite3_free(oldPath);
6443 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6444 }
6445
6446 return rc;
6447}
6448
6449/*
6450** pFile is a file that has been opened by a prior xOpen call. dbPath
6451** is a string buffer at least MAXPATHLEN+1 characters in size.
6452**
6453** This routine find the filename associated with pFile and writes it
6454** int dbPath.
6455*/
6456static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006457#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006458 if( pFile->pMethod == &afpIoMethods ){
6459 /* afp style keeps a reference to the db path in the filePath field
6460 ** of the struct */
drhea678832008-12-10 19:26:22 +00006461 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006462 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6463 } else
drh715ff302008-12-03 22:32:44 +00006464#endif
6465 if( pFile->pMethod == &dotlockIoMethods ){
6466 /* dot lock style uses the locking context to store the dot lock
6467 ** file path */
6468 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6469 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6470 }else{
6471 /* all other styles use the locking context to store the db file path */
6472 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006473 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006474 }
6475 return SQLITE_OK;
6476}
6477
6478/*
6479** Takes an already filled in unix file and alters it so all file locking
6480** will be performed on the local proxy lock file. The following fields
6481** are preserved in the locking context so that they can be restored and
6482** the unix structure properly cleaned up at close time:
6483** ->lockingContext
6484** ->pMethod
6485*/
6486static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6487 proxyLockingContext *pCtx;
6488 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6489 char *lockPath=NULL;
6490 int rc = SQLITE_OK;
6491
drh308c2a52010-05-14 11:30:18 +00006492 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006493 return SQLITE_BUSY;
6494 }
6495 proxyGetDbPathForUnixFile(pFile, dbPath);
6496 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6497 lockPath=NULL;
6498 }else{
6499 lockPath=(char *)path;
6500 }
6501
drh308c2a52010-05-14 11:30:18 +00006502 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6503 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006504
6505 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6506 if( pCtx==0 ){
6507 return SQLITE_NOMEM;
6508 }
6509 memset(pCtx, 0, sizeof(*pCtx));
6510
6511 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6512 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006513 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6514 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6515 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6516 ** (c) the file system is read-only, then enable no-locking access.
6517 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6518 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6519 */
6520 struct statfs fsInfo;
6521 struct stat conchInfo;
6522 int goLockless = 0;
6523
drh99ab3b12011-03-02 15:09:07 +00006524 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006525 int err = errno;
6526 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6527 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6528 }
6529 }
6530 if( goLockless ){
6531 pCtx->conchHeld = -1; /* read only FS/ lockless */
6532 rc = SQLITE_OK;
6533 }
6534 }
drh715ff302008-12-03 22:32:44 +00006535 }
6536 if( rc==SQLITE_OK && lockPath ){
6537 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6538 }
6539
6540 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006541 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6542 if( pCtx->dbPath==NULL ){
6543 rc = SQLITE_NOMEM;
6544 }
6545 }
6546 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006547 /* all memory is allocated, proxys are created and assigned,
6548 ** switch the locking context and pMethod then return.
6549 */
drh715ff302008-12-03 22:32:44 +00006550 pCtx->oldLockingContext = pFile->lockingContext;
6551 pFile->lockingContext = pCtx;
6552 pCtx->pOldMethod = pFile->pMethod;
6553 pFile->pMethod = &proxyIoMethods;
6554 }else{
6555 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006556 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006557 sqlite3_free(pCtx->conchFile);
6558 }
drhd56b1212010-08-11 06:14:15 +00006559 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006560 sqlite3_free(pCtx->conchFilePath);
6561 sqlite3_free(pCtx);
6562 }
drh308c2a52010-05-14 11:30:18 +00006563 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6564 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006565 return rc;
6566}
6567
6568
6569/*
6570** This routine handles sqlite3_file_control() calls that are specific
6571** to proxy locking.
6572*/
6573static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6574 switch( op ){
6575 case SQLITE_GET_LOCKPROXYFILE: {
6576 unixFile *pFile = (unixFile*)id;
6577 if( pFile->pMethod == &proxyIoMethods ){
6578 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6579 proxyTakeConch(pFile);
6580 if( pCtx->lockProxyPath ){
6581 *(const char **)pArg = pCtx->lockProxyPath;
6582 }else{
6583 *(const char **)pArg = ":auto: (not held)";
6584 }
6585 } else {
6586 *(const char **)pArg = NULL;
6587 }
6588 return SQLITE_OK;
6589 }
6590 case SQLITE_SET_LOCKPROXYFILE: {
6591 unixFile *pFile = (unixFile*)id;
6592 int rc = SQLITE_OK;
6593 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6594 if( pArg==NULL || (const char *)pArg==0 ){
6595 if( isProxyStyle ){
6596 /* turn off proxy locking - not supported */
6597 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6598 }else{
6599 /* turn off proxy locking - already off - NOOP */
6600 rc = SQLITE_OK;
6601 }
6602 }else{
6603 const char *proxyPath = (const char *)pArg;
6604 if( isProxyStyle ){
6605 proxyLockingContext *pCtx =
6606 (proxyLockingContext*)pFile->lockingContext;
6607 if( !strcmp(pArg, ":auto:")
6608 || (pCtx->lockProxyPath &&
6609 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6610 ){
6611 rc = SQLITE_OK;
6612 }else{
6613 rc = switchLockProxyPath(pFile, proxyPath);
6614 }
6615 }else{
6616 /* turn on proxy file locking */
6617 rc = proxyTransformUnixFile(pFile, proxyPath);
6618 }
6619 }
6620 return rc;
6621 }
6622 default: {
6623 assert( 0 ); /* The call assures that only valid opcodes are sent */
6624 }
6625 }
6626 /*NOTREACHED*/
6627 return SQLITE_ERROR;
6628}
6629
6630/*
6631** Within this division (the proxying locking implementation) the procedures
6632** above this point are all utilities. The lock-related methods of the
6633** proxy-locking sqlite3_io_method object follow.
6634*/
6635
6636
6637/*
6638** This routine checks if there is a RESERVED lock held on the specified
6639** file by this or any other process. If such a lock is held, set *pResOut
6640** to a non-zero value otherwise *pResOut is set to zero. The return value
6641** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6642*/
6643static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6644 unixFile *pFile = (unixFile*)id;
6645 int rc = proxyTakeConch(pFile);
6646 if( rc==SQLITE_OK ){
6647 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006648 if( pCtx->conchHeld>0 ){
6649 unixFile *proxy = pCtx->lockProxy;
6650 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6651 }else{ /* conchHeld < 0 is lockless */
6652 pResOut=0;
6653 }
drh715ff302008-12-03 22:32:44 +00006654 }
6655 return rc;
6656}
6657
6658/*
drh308c2a52010-05-14 11:30:18 +00006659** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006660** of the following:
6661**
6662** (1) SHARED_LOCK
6663** (2) RESERVED_LOCK
6664** (3) PENDING_LOCK
6665** (4) EXCLUSIVE_LOCK
6666**
6667** Sometimes when requesting one lock state, additional lock states
6668** are inserted in between. The locking might fail on one of the later
6669** transitions leaving the lock state different from what it started but
6670** still short of its goal. The following chart shows the allowed
6671** transitions and the inserted intermediate states:
6672**
6673** UNLOCKED -> SHARED
6674** SHARED -> RESERVED
6675** SHARED -> (PENDING) -> EXCLUSIVE
6676** RESERVED -> (PENDING) -> EXCLUSIVE
6677** PENDING -> EXCLUSIVE
6678**
6679** This routine will only increase a lock. Use the sqlite3OsUnlock()
6680** routine to lower a locking level.
6681*/
drh308c2a52010-05-14 11:30:18 +00006682static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006683 unixFile *pFile = (unixFile*)id;
6684 int rc = proxyTakeConch(pFile);
6685 if( rc==SQLITE_OK ){
6686 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006687 if( pCtx->conchHeld>0 ){
6688 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006689 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6690 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006691 }else{
6692 /* conchHeld < 0 is lockless */
6693 }
drh715ff302008-12-03 22:32:44 +00006694 }
6695 return rc;
6696}
6697
6698
6699/*
drh308c2a52010-05-14 11:30:18 +00006700** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006701** must be either NO_LOCK or SHARED_LOCK.
6702**
6703** If the locking level of the file descriptor is already at or below
6704** the requested locking level, this routine is a no-op.
6705*/
drh308c2a52010-05-14 11:30:18 +00006706static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006707 unixFile *pFile = (unixFile*)id;
6708 int rc = proxyTakeConch(pFile);
6709 if( rc==SQLITE_OK ){
6710 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006711 if( pCtx->conchHeld>0 ){
6712 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006713 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6714 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006715 }else{
6716 /* conchHeld < 0 is lockless */
6717 }
drh715ff302008-12-03 22:32:44 +00006718 }
6719 return rc;
6720}
6721
6722/*
6723** Close a file that uses proxy locks.
6724*/
6725static int proxyClose(sqlite3_file *id) {
6726 if( id ){
6727 unixFile *pFile = (unixFile*)id;
6728 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6729 unixFile *lockProxy = pCtx->lockProxy;
6730 unixFile *conchFile = pCtx->conchFile;
6731 int rc = SQLITE_OK;
6732
6733 if( lockProxy ){
6734 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6735 if( rc ) return rc;
6736 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6737 if( rc ) return rc;
6738 sqlite3_free(lockProxy);
6739 pCtx->lockProxy = 0;
6740 }
6741 if( conchFile ){
6742 if( pCtx->conchHeld ){
6743 rc = proxyReleaseConch(pFile);
6744 if( rc ) return rc;
6745 }
6746 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6747 if( rc ) return rc;
6748 sqlite3_free(conchFile);
6749 }
drhd56b1212010-08-11 06:14:15 +00006750 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006751 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006752 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006753 /* restore the original locking context and pMethod then close it */
6754 pFile->lockingContext = pCtx->oldLockingContext;
6755 pFile->pMethod = pCtx->pOldMethod;
6756 sqlite3_free(pCtx);
6757 return pFile->pMethod->xClose(id);
6758 }
6759 return SQLITE_OK;
6760}
6761
6762
6763
drhd2cb50b2009-01-09 21:41:17 +00006764#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006765/*
6766** The proxy locking style is intended for use with AFP filesystems.
6767** And since AFP is only supported on MacOSX, the proxy locking is also
6768** restricted to MacOSX.
6769**
6770**
6771******************* End of the proxy lock implementation **********************
6772******************************************************************************/
6773
drh734c9862008-11-28 15:37:20 +00006774/*
danielk1977e339d652008-06-28 11:23:00 +00006775** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006776**
6777** This routine registers all VFS implementations for unix-like operating
6778** systems. This routine, and the sqlite3_os_end() routine that follows,
6779** should be the only routines in this file that are visible from other
6780** files.
drh6b9d6dd2008-12-03 19:34:47 +00006781**
6782** This routine is called once during SQLite initialization and by a
6783** single thread. The memory allocation and mutex subsystems have not
6784** necessarily been initialized when this routine is called, and so they
6785** should not be used.
drh153c62c2007-08-24 03:51:33 +00006786*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006787int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006788 /*
6789 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006790 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6791 ** to the "finder" function. (pAppData is a pointer to a pointer because
6792 ** silly C90 rules prohibit a void* from being cast to a function pointer
6793 ** and so we have to go through the intermediate pointer to avoid problems
6794 ** when compiling with -pedantic-errors on GCC.)
6795 **
6796 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006797 ** finder-function. The finder-function returns a pointer to the
6798 ** sqlite_io_methods object that implements the desired locking
6799 ** behaviors. See the division above that contains the IOMETHODS
6800 ** macro for addition information on finder-functions.
6801 **
6802 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6803 ** object. But the "autolockIoFinder" available on MacOSX does a little
6804 ** more than that; it looks at the filesystem type that hosts the
6805 ** database file and tries to choose an locking method appropriate for
6806 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006807 */
drh7708e972008-11-29 00:56:52 +00006808 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006809 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006810 sizeof(unixFile), /* szOsFile */ \
6811 MAX_PATHNAME, /* mxPathname */ \
6812 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006813 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006814 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006815 unixOpen, /* xOpen */ \
6816 unixDelete, /* xDelete */ \
6817 unixAccess, /* xAccess */ \
6818 unixFullPathname, /* xFullPathname */ \
6819 unixDlOpen, /* xDlOpen */ \
6820 unixDlError, /* xDlError */ \
6821 unixDlSym, /* xDlSym */ \
6822 unixDlClose, /* xDlClose */ \
6823 unixRandomness, /* xRandomness */ \
6824 unixSleep, /* xSleep */ \
6825 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006826 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006827 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006828 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006829 unixGetSystemCall, /* xGetSystemCall */ \
6830 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006831 }
6832
drh6b9d6dd2008-12-03 19:34:47 +00006833 /*
6834 ** All default VFSes for unix are contained in the following array.
6835 **
6836 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6837 ** by the SQLite core when the VFS is registered. So the following
6838 ** array cannot be const.
6839 */
danielk1977e339d652008-06-28 11:23:00 +00006840 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006841#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006842 UNIXVFS("unix", autolockIoFinder ),
6843#else
6844 UNIXVFS("unix", posixIoFinder ),
6845#endif
6846 UNIXVFS("unix-none", nolockIoFinder ),
6847 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006848 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006849#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006850 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006851#endif
6852#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006853 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006854#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006855 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006856#endif
chw78a13182009-04-07 05:35:03 +00006857#endif
drhd2cb50b2009-01-09 21:41:17 +00006858#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006859 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006860 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006861 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006862#endif
drh153c62c2007-08-24 03:51:33 +00006863 };
drh6b9d6dd2008-12-03 19:34:47 +00006864 unsigned int i; /* Loop counter */
6865
drh2aa5a002011-04-13 13:42:25 +00006866 /* Double-check that the aSyscall[] array has been constructed
6867 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh8c815d12012-02-13 20:16:37 +00006868 assert( ArraySize(aSyscall)==22 );
drh2aa5a002011-04-13 13:42:25 +00006869
drh6b9d6dd2008-12-03 19:34:47 +00006870 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006871 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006872 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006873 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006874 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006875}
danielk1977e339d652008-06-28 11:23:00 +00006876
6877/*
drh6b9d6dd2008-12-03 19:34:47 +00006878** Shutdown the operating system interface.
6879**
6880** Some operating systems might need to do some cleanup in this routine,
6881** to release dynamically allocated objects. But not on unix.
6882** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006883*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006884int sqlite3_os_end(void){
6885 return SQLITE_OK;
6886}
drhdce8bdb2007-08-16 13:01:44 +00006887
danielk197729bafea2008-06-26 10:41:19 +00006888#endif /* SQLITE_OS_UNIX */