blob: c0df66e8e07ecca54783d70a85011cf33546dd24 [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/*
drh5adc60b2012-04-14 13:25:11 +0000168** Default permissions when creating auto proxy dir
169*/
aswiftaebf4132008-11-21 00:10:35 +0000170#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
drhd3d8c042012-05-29 17:02:40 +0000230#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000231 /* 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 */
drha7e61d82011-03-12 17:02:57 +0000265
266/*
drh198bf392006-01-06 21:52:49 +0000267** Include code that is common to all os_*.c files
268*/
269#include "os_common.h"
270
271/*
drh0ccebe72005-06-07 22:22:50 +0000272** Define various macros that are missing from some systems.
273*/
drhbbd42a62004-05-22 17:41:58 +0000274#ifndef O_LARGEFILE
275# define O_LARGEFILE 0
276#endif
277#ifdef SQLITE_DISABLE_LFS
278# undef O_LARGEFILE
279# define O_LARGEFILE 0
280#endif
281#ifndef O_NOFOLLOW
282# define O_NOFOLLOW 0
283#endif
284#ifndef O_BINARY
285# define O_BINARY 0
286#endif
287
288/*
drh2b4b5962005-06-15 17:47:55 +0000289** The threadid macro resolves to the thread-id or to 0. Used for
290** testing and debugging only.
291*/
drhd677b3d2007-08-20 22:48:41 +0000292#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000293#define threadid pthread_self()
294#else
295#define threadid 0
296#endif
297
drh99ab3b12011-03-02 15:09:07 +0000298/*
drh9a3baf12011-04-25 18:01:27 +0000299** Different Unix systems declare open() in different ways. Same use
300** open(const char*,int,mode_t). Others use open(const char*,int,...).
301** The difference is important when using a pointer to the function.
302**
303** The safest way to deal with the problem is to always use this wrapper
304** which always has the same well-defined interface.
305*/
306static int posixOpen(const char *zFile, int flags, int mode){
307 return open(zFile, flags, mode);
308}
309
drhed466822012-05-31 13:10:49 +0000310/*
311** On some systems, calls to fchown() will trigger a message in a security
312** log if they come from non-root processes. So avoid calling fchown() if
313** we are not running as root.
314*/
315static int posixFchown(int fd, uid_t uid, gid_t gid){
316 return geteuid() ? 0 : fchown(fd,uid,gid);
317}
318
drh90315a22011-08-10 01:52:12 +0000319/* Forward reference */
320static int openDirectory(const char*, int*);
321
drh9a3baf12011-04-25 18:01:27 +0000322/*
drh99ab3b12011-03-02 15:09:07 +0000323** Many system calls are accessed through pointer-to-functions so that
324** they may be overridden at runtime to facilitate fault injection during
325** testing and sandboxing. The following array holds the names and pointers
326** to all overrideable system calls.
327*/
328static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000329 const char *zName; /* Name of the sytem call */
330 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
331 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000332} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000333 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
334#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000335
drh58ad5802011-03-23 22:02:23 +0000336 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000337#define osClose ((int(*)(int))aSyscall[1].pCurrent)
338
drh58ad5802011-03-23 22:02:23 +0000339 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000340#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
341
drh58ad5802011-03-23 22:02:23 +0000342 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000343#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
344
drh58ad5802011-03-23 22:02:23 +0000345 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000346#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
347
348/*
349** The DJGPP compiler environment looks mostly like Unix, but it
350** lacks the fcntl() system call. So redefine fcntl() to be something
351** that always succeeds. This means that locking does not occur under
352** DJGPP. But it is DOS - what did you expect?
353*/
354#ifdef __DJGPP__
355 { "fstat", 0, 0 },
356#define osFstat(a,b,c) 0
357#else
drh58ad5802011-03-23 22:02:23 +0000358 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000359#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
360#endif
361
drh58ad5802011-03-23 22:02:23 +0000362 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000363#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
364
drh58ad5802011-03-23 22:02:23 +0000365 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000366#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000367
drh58ad5802011-03-23 22:02:23 +0000368 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000369#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
370
drhd4a80312011-04-15 14:33:20 +0000371#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000372 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000373#else
drh58ad5802011-03-23 22:02:23 +0000374 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000375#endif
376#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
377
378#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000379 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000380#else
drh58ad5802011-03-23 22:02:23 +0000381 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000382#endif
383#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
384
drh58ad5802011-03-23 22:02:23 +0000385 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000386#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
387
drhd4a80312011-04-15 14:33:20 +0000388#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000389 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000390#else
drh58ad5802011-03-23 22:02:23 +0000391 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000392#endif
393#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
394 aSyscall[12].pCurrent)
395
396#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000397 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000400#endif
401#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
402 aSyscall[13].pCurrent)
403
drha6c47492011-04-11 18:35:09 +0000404#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000405 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000406#else
407 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000408#endif
drh2aa5a002011-04-13 13:42:25 +0000409#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000410
411#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000412 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000413#else
drh58ad5802011-03-23 22:02:23 +0000414 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000415#endif
dan0fd7d862011-03-29 10:04:23 +0000416#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000417
drh036ac7f2011-08-08 23:18:05 +0000418 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
419#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
420
drh90315a22011-08-10 01:52:12 +0000421 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
422#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
423
drh9ef6bc42011-11-04 02:24:02 +0000424 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
425#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
426
427 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
428#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
429
drhed466822012-05-31 13:10:49 +0000430 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000431#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000432
drh8c815d12012-02-13 20:16:37 +0000433 { "umask", (sqlite3_syscall_ptr)umask, 0 },
434#define osUmask ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
435
drhe562be52011-03-02 18:01:10 +0000436}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000437
438/*
439** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000440** "unix" VFSes. Return SQLITE_OK opon successfully updating the
441** system call pointer, or SQLITE_NOTFOUND if there is no configurable
442** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000443*/
444static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000445 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
446 const char *zName, /* Name of system call to override */
447 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000448){
drh58ad5802011-03-23 22:02:23 +0000449 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000450 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000451
452 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000453 if( zName==0 ){
454 /* If no zName is given, restore all system calls to their default
455 ** settings and return NULL
456 */
dan51438a72011-04-02 17:00:47 +0000457 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000458 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
459 if( aSyscall[i].pDefault ){
460 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000461 }
462 }
463 }else{
464 /* If zName is specified, operate on only the one system call
465 ** specified.
466 */
467 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
468 if( strcmp(zName, aSyscall[i].zName)==0 ){
469 if( aSyscall[i].pDefault==0 ){
470 aSyscall[i].pDefault = aSyscall[i].pCurrent;
471 }
drh1df30962011-03-02 19:06:42 +0000472 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000473 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
474 aSyscall[i].pCurrent = pNewFunc;
475 break;
476 }
477 }
478 }
479 return rc;
480}
481
drh1df30962011-03-02 19:06:42 +0000482/*
483** Return the value of a system call. Return NULL if zName is not a
484** recognized system call name. NULL is also returned if the system call
485** is currently undefined.
486*/
drh58ad5802011-03-23 22:02:23 +0000487static sqlite3_syscall_ptr unixGetSystemCall(
488 sqlite3_vfs *pNotUsed,
489 const char *zName
490){
491 unsigned int i;
492
493 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000494 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
495 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
496 }
497 return 0;
498}
499
500/*
501** Return the name of the first system call after zName. If zName==NULL
502** then return the name of the first system call. Return NULL if zName
503** is the last system call or if zName is not the name of a valid
504** system call.
505*/
506static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000507 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000508
509 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000510 if( zName ){
511 for(i=0; i<ArraySize(aSyscall)-1; i++){
512 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000513 }
514 }
dan0fd7d862011-03-29 10:04:23 +0000515 for(i++; i<ArraySize(aSyscall); i++){
516 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000517 }
518 return 0;
519}
520
drhad4f1e52011-03-04 15:43:57 +0000521/*
drh8c815d12012-02-13 20:16:37 +0000522** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000523** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000524**
525** If the file creation mode "m" is 0 then set it to the default for
526** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
527** 0644) as modified by the system umask. If m is not 0, then
528** make the file creation mode be exactly m ignoring the umask.
529**
530** The m parameter will be non-zero only when creating -wal, -journal,
531** and -shm files. We want those files to have *exactly* the same
532** permissions as their original database, unadulterated by the umask.
533** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
534** transaction crashes and leaves behind hot journals, then any
535** process that is able to write to the database will also be able to
536** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000537*/
drh8c815d12012-02-13 20:16:37 +0000538static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000539 int fd;
drh8c815d12012-02-13 20:16:37 +0000540 mode_t m2;
drhef595982012-02-13 20:28:15 +0000541 mode_t origM = 0;
drh8c815d12012-02-13 20:16:37 +0000542 if( m==0 ){
543 m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
544 }else{
545 m2 = m;
546 origM = osUmask(0);
547 }
drh5adc60b2012-04-14 13:25:11 +0000548 do{
549#if defined(O_CLOEXEC)
550 fd = osOpen(z,f|O_CLOEXEC,m2);
551#else
552 fd = osOpen(z,f,m2);
553#endif
554 }while( fd<0 && errno==EINTR );
drh8c815d12012-02-13 20:16:37 +0000555 if( m ){
556 osUmask(origM);
557 }
drh5adc60b2012-04-14 13:25:11 +0000558#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
559 if( fd>=0 ) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
560#endif
561 return fd;
drhad4f1e52011-03-04 15:43:57 +0000562}
danielk197713adf8a2004-06-03 16:08:41 +0000563
drh107886a2008-11-21 22:21:50 +0000564/*
dan9359c7b2009-08-21 08:29:10 +0000565** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000566** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000567** vxworksFileId objects used by this file, all of which may be
568** shared by multiple threads.
569**
570** Function unixMutexHeld() is used to assert() that the global mutex
571** is held when required. This function is only used as part of assert()
572** statements. e.g.
573**
574** unixEnterMutex()
575** assert( unixMutexHeld() );
576** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000577*/
578static void unixEnterMutex(void){
579 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
580}
581static void unixLeaveMutex(void){
582 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
583}
dan9359c7b2009-08-21 08:29:10 +0000584#ifdef SQLITE_DEBUG
585static int unixMutexHeld(void) {
586 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
587}
588#endif
drh107886a2008-11-21 22:21:50 +0000589
drh734c9862008-11-28 15:37:20 +0000590
drh30ddce62011-10-15 00:16:30 +0000591#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000592/*
593** Helper function for printing out trace information from debugging
594** binaries. This returns the string represetation of the supplied
595** integer lock-type.
596*/
drh308c2a52010-05-14 11:30:18 +0000597static const char *azFileLock(int eFileLock){
598 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000599 case NO_LOCK: return "NONE";
600 case SHARED_LOCK: return "SHARED";
601 case RESERVED_LOCK: return "RESERVED";
602 case PENDING_LOCK: return "PENDING";
603 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000604 }
605 return "ERROR";
606}
607#endif
608
609#ifdef SQLITE_LOCK_TRACE
610/*
611** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000612**
drh734c9862008-11-28 15:37:20 +0000613** This routine is used for troubleshooting locks on multithreaded
614** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
615** command-line option on the compiler. This code is normally
616** turned off.
617*/
618static int lockTrace(int fd, int op, struct flock *p){
619 char *zOpName, *zType;
620 int s;
621 int savedErrno;
622 if( op==F_GETLK ){
623 zOpName = "GETLK";
624 }else if( op==F_SETLK ){
625 zOpName = "SETLK";
626 }else{
drh99ab3b12011-03-02 15:09:07 +0000627 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000628 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
629 return s;
630 }
631 if( p->l_type==F_RDLCK ){
632 zType = "RDLCK";
633 }else if( p->l_type==F_WRLCK ){
634 zType = "WRLCK";
635 }else if( p->l_type==F_UNLCK ){
636 zType = "UNLCK";
637 }else{
638 assert( 0 );
639 }
640 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000641 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000642 savedErrno = errno;
643 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
644 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
645 (int)p->l_pid, s);
646 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
647 struct flock l2;
648 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000649 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000650 if( l2.l_type==F_RDLCK ){
651 zType = "RDLCK";
652 }else if( l2.l_type==F_WRLCK ){
653 zType = "WRLCK";
654 }else if( l2.l_type==F_UNLCK ){
655 zType = "UNLCK";
656 }else{
657 assert( 0 );
658 }
659 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
660 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
661 }
662 errno = savedErrno;
663 return s;
664}
drh99ab3b12011-03-02 15:09:07 +0000665#undef osFcntl
666#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000667#endif /* SQLITE_LOCK_TRACE */
668
drhff812312011-02-23 13:33:46 +0000669/*
670** Retry ftruncate() calls that fail due to EINTR
671*/
drhff812312011-02-23 13:33:46 +0000672static int robust_ftruncate(int h, sqlite3_int64 sz){
673 int rc;
drh99ab3b12011-03-02 15:09:07 +0000674 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000675 return rc;
676}
drh734c9862008-11-28 15:37:20 +0000677
678/*
679** This routine translates a standard POSIX errno code into something
680** useful to the clients of the sqlite3 functions. Specifically, it is
681** intended to translate a variety of "try again" errors into SQLITE_BUSY
682** and a variety of "please close the file descriptor NOW" errors into
683** SQLITE_IOERR
684**
685** Errors during initialization of locks, or file system support for locks,
686** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
687*/
688static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
689 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000690#if 0
691 /* At one point this code was not commented out. In theory, this branch
692 ** should never be hit, as this function should only be called after
693 ** a locking-related function (i.e. fcntl()) has returned non-zero with
694 ** the value of errno as the first argument. Since a system call has failed,
695 ** errno should be non-zero.
696 **
697 ** Despite this, if errno really is zero, we still don't want to return
698 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
699 ** propagated back to the caller. Commenting this branch out means errno==0
700 ** will be handled by the "default:" case below.
701 */
drh734c9862008-11-28 15:37:20 +0000702 case 0:
703 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000704#endif
705
drh734c9862008-11-28 15:37:20 +0000706 case EAGAIN:
707 case ETIMEDOUT:
708 case EBUSY:
709 case EINTR:
710 case ENOLCK:
711 /* random NFS retry error, unless during file system support
712 * introspection, in which it actually means what it says */
713 return SQLITE_BUSY;
714
715 case EACCES:
716 /* EACCES is like EAGAIN during locking operations, but not any other time*/
717 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000718 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
719 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
720 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000721 return SQLITE_BUSY;
722 }
723 /* else fall through */
724 case EPERM:
725 return SQLITE_PERM;
726
danea83bc62011-04-01 11:56:32 +0000727 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
728 ** this module never makes such a call. And the code in SQLite itself
729 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
730 ** this case is also commented out. If the system does set errno to EDEADLK,
731 ** the default SQLITE_IOERR_XXX code will be returned. */
732#if 0
drh734c9862008-11-28 15:37:20 +0000733 case EDEADLK:
734 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000735#endif
drh734c9862008-11-28 15:37:20 +0000736
737#if EOPNOTSUPP!=ENOTSUP
738 case EOPNOTSUPP:
739 /* something went terribly awry, unless during file system support
740 * introspection, in which it actually means what it says */
741#endif
742#ifdef ENOTSUP
743 case ENOTSUP:
744 /* invalid fd, unless during file system support introspection, in which
745 * it actually means what it says */
746#endif
747 case EIO:
748 case EBADF:
749 case EINVAL:
750 case ENOTCONN:
751 case ENODEV:
752 case ENXIO:
753 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000754#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000755 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000756#endif
drh734c9862008-11-28 15:37:20 +0000757 case ENOSYS:
758 /* these should force the client to close the file and reconnect */
759
760 default:
761 return sqliteIOErr;
762 }
763}
764
765
766
767/******************************************************************************
768****************** Begin Unique File ID Utility Used By VxWorks ***************
769**
770** On most versions of unix, we can get a unique ID for a file by concatenating
771** the device number and the inode number. But this does not work on VxWorks.
772** On VxWorks, a unique file id must be based on the canonical filename.
773**
774** A pointer to an instance of the following structure can be used as a
775** unique file ID in VxWorks. Each instance of this structure contains
776** a copy of the canonical filename. There is also a reference count.
777** The structure is reclaimed when the number of pointers to it drops to
778** zero.
779**
780** There are never very many files open at one time and lookups are not
781** a performance-critical path, so it is sufficient to put these
782** structures on a linked list.
783*/
784struct vxworksFileId {
785 struct vxworksFileId *pNext; /* Next in a list of them all */
786 int nRef; /* Number of references to this one */
787 int nName; /* Length of the zCanonicalName[] string */
788 char *zCanonicalName; /* Canonical filename */
789};
790
791#if OS_VXWORKS
792/*
drh9b35ea62008-11-29 02:20:26 +0000793** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000794** variable:
795*/
796static struct vxworksFileId *vxworksFileList = 0;
797
798/*
799** Simplify a filename into its canonical form
800** by making the following changes:
801**
802** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000803** * convert /./ into just /
804** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000805**
806** Changes are made in-place. Return the new name length.
807**
808** The original filename is in z[0..n-1]. Return the number of
809** characters in the simplified name.
810*/
811static int vxworksSimplifyName(char *z, int n){
812 int i, j;
813 while( n>1 && z[n-1]=='/' ){ n--; }
814 for(i=j=0; i<n; i++){
815 if( z[i]=='/' ){
816 if( z[i+1]=='/' ) continue;
817 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
818 i += 1;
819 continue;
820 }
821 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
822 while( j>0 && z[j-1]!='/' ){ j--; }
823 if( j>0 ){ j--; }
824 i += 2;
825 continue;
826 }
827 }
828 z[j++] = z[i];
829 }
830 z[j] = 0;
831 return j;
832}
833
834/*
835** Find a unique file ID for the given absolute pathname. Return
836** a pointer to the vxworksFileId object. This pointer is the unique
837** file ID.
838**
839** The nRef field of the vxworksFileId object is incremented before
840** the object is returned. A new vxworksFileId object is created
841** and added to the global list if necessary.
842**
843** If a memory allocation error occurs, return NULL.
844*/
845static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
846 struct vxworksFileId *pNew; /* search key and new file ID */
847 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
848 int n; /* Length of zAbsoluteName string */
849
850 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000851 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000852 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
853 if( pNew==0 ) return 0;
854 pNew->zCanonicalName = (char*)&pNew[1];
855 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
856 n = vxworksSimplifyName(pNew->zCanonicalName, n);
857
858 /* Search for an existing entry that matching the canonical name.
859 ** If found, increment the reference count and return a pointer to
860 ** the existing file ID.
861 */
862 unixEnterMutex();
863 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
864 if( pCandidate->nName==n
865 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
866 ){
867 sqlite3_free(pNew);
868 pCandidate->nRef++;
869 unixLeaveMutex();
870 return pCandidate;
871 }
872 }
873
874 /* No match was found. We will make a new file ID */
875 pNew->nRef = 1;
876 pNew->nName = n;
877 pNew->pNext = vxworksFileList;
878 vxworksFileList = pNew;
879 unixLeaveMutex();
880 return pNew;
881}
882
883/*
884** Decrement the reference count on a vxworksFileId object. Free
885** the object when the reference count reaches zero.
886*/
887static void vxworksReleaseFileId(struct vxworksFileId *pId){
888 unixEnterMutex();
889 assert( pId->nRef>0 );
890 pId->nRef--;
891 if( pId->nRef==0 ){
892 struct vxworksFileId **pp;
893 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
894 assert( *pp==pId );
895 *pp = pId->pNext;
896 sqlite3_free(pId);
897 }
898 unixLeaveMutex();
899}
900#endif /* OS_VXWORKS */
901/*************** End of Unique File ID Utility Used By VxWorks ****************
902******************************************************************************/
903
904
905/******************************************************************************
906*************************** Posix Advisory Locking ****************************
907**
drh9b35ea62008-11-29 02:20:26 +0000908** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000909** section 6.5.2.2 lines 483 through 490 specify that when a process
910** sets or clears a lock, that operation overrides any prior locks set
911** by the same process. It does not explicitly say so, but this implies
912** that it overrides locks set by the same process using a different
913** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000914**
915** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000916** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
917**
918** Suppose ./file1 and ./file2 are really the same file (because
919** one is a hard or symbolic link to the other) then if you set
920** an exclusive lock on fd1, then try to get an exclusive lock
921** on fd2, it works. I would have expected the second lock to
922** fail since there was already a lock on the file due to fd1.
923** But not so. Since both locks came from the same process, the
924** second overrides the first, even though they were on different
925** file descriptors opened on different file names.
926**
drh734c9862008-11-28 15:37:20 +0000927** This means that we cannot use POSIX locks to synchronize file access
928** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000929** to synchronize access for threads in separate processes, but not
930** threads within the same process.
931**
932** To work around the problem, SQLite has to manage file locks internally
933** on its own. Whenever a new database is opened, we have to find the
934** specific inode of the database file (the inode is determined by the
935** st_dev and st_ino fields of the stat structure that fstat() fills in)
936** and check for locks already existing on that inode. When locks are
937** created or removed, we have to look at our own internal record of the
938** locks to see if another thread has previously set a lock on that same
939** inode.
940**
drh9b35ea62008-11-29 02:20:26 +0000941** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
942** For VxWorks, we have to use the alternative unique ID system based on
943** canonical filename and implemented in the previous division.)
944**
danielk1977ad94b582007-08-20 06:44:22 +0000945** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000946** descriptor. It is now a structure that holds the integer file
947** descriptor and a pointer to a structure that describes the internal
948** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000949** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000950** point to the same locking structure. The locking structure keeps
951** a reference count (so we will know when to delete it) and a "cnt"
952** field that tells us its internal lock status. cnt==0 means the
953** file is unlocked. cnt==-1 means the file has an exclusive lock.
954** cnt>0 means there are cnt shared locks on the file.
955**
956** Any attempt to lock or unlock a file first checks the locking
957** structure. The fcntl() system call is only invoked to set a
958** POSIX lock if the internal lock structure transitions between
959** a locked and an unlocked state.
960**
drh734c9862008-11-28 15:37:20 +0000961** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000962**
963** If you close a file descriptor that points to a file that has locks,
964** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000965** released. To work around this problem, each unixInodeInfo object
966** maintains a count of the number of pending locks on tha inode.
967** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000968** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000969** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000970** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000971** be closed and that list is walked (and cleared) when the last lock
972** clears.
973**
drh9b35ea62008-11-29 02:20:26 +0000974** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000975**
drh9b35ea62008-11-29 02:20:26 +0000976** Many older versions of linux use the LinuxThreads library which is
977** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000978** A cannot be modified or overridden by a different thread B.
979** Only thread A can modify the lock. Locking behavior is correct
980** if the appliation uses the newer Native Posix Thread Library (NPTL)
981** on linux - with NPTL a lock created by thread A can override locks
982** in thread B. But there is no way to know at compile-time which
983** threading library is being used. So there is no way to know at
984** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000985** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000986** current process.
drh5fdae772004-06-29 03:29:00 +0000987**
drh8af6c222010-05-14 12:43:01 +0000988** SQLite used to support LinuxThreads. But support for LinuxThreads
989** was dropped beginning with version 3.7.0. SQLite will still work with
990** LinuxThreads provided that (1) there is no more than one connection
991** per database file in the same process and (2) database connections
992** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000993*/
994
995/*
996** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000997** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000998*/
999struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001000 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001001#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001002 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001003#else
drh107886a2008-11-21 22:21:50 +00001004 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001005#endif
1006};
1007
1008/*
drhbbd42a62004-05-22 17:41:58 +00001009** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001010** inode. Or, on LinuxThreads, there is one of these structures for
1011** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001012**
danielk1977ad94b582007-08-20 06:44:22 +00001013** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001014** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001015** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001016*/
drh8af6c222010-05-14 12:43:01 +00001017struct unixInodeInfo {
1018 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001019 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001020 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1021 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001022 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001023 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1024 int nLock; /* Number of outstanding file locks */
1025 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1026 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1027 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001028#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001029 unsigned long long sharedByte; /* for AFP simulated shared lock */
1030#endif
drh6c7d5c52008-11-21 20:32:33 +00001031#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001032 sem_t *pSem; /* Named POSIX semaphore */
1033 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001034#endif
drhbbd42a62004-05-22 17:41:58 +00001035};
1036
drhda0e7682008-07-30 15:27:54 +00001037/*
drh8af6c222010-05-14 12:43:01 +00001038** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001039*/
drhd91c68f2010-05-14 14:52:25 +00001040static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001041
drh5fdae772004-06-29 03:29:00 +00001042/*
dane18d4952011-02-21 11:46:24 +00001043**
1044** This function - unixLogError_x(), is only ever called via the macro
1045** unixLogError().
1046**
1047** It is invoked after an error occurs in an OS function and errno has been
1048** set. It logs a message using sqlite3_log() containing the current value of
1049** errno and, if possible, the human-readable equivalent from strerror() or
1050** strerror_r().
1051**
1052** The first argument passed to the macro should be the error code that
1053** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1054** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001055** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001056** if any.
1057*/
drh0e9365c2011-03-02 02:08:13 +00001058#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1059static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001060 int errcode, /* SQLite error code */
1061 const char *zFunc, /* Name of OS function that failed */
1062 const char *zPath, /* File path associated with error */
1063 int iLine /* Source line number where error occurred */
1064){
1065 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001066 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001067
1068 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1069 ** the strerror() function to obtain the human-readable error message
1070 ** equivalent to errno. Otherwise, use strerror_r().
1071 */
1072#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1073 char aErr[80];
1074 memset(aErr, 0, sizeof(aErr));
1075 zErr = aErr;
1076
1077 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001078 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001079 ** returns a pointer to a buffer containing the error message. That pointer
1080 ** may point to aErr[], or it may point to some static storage somewhere.
1081 ** Otherwise, assume that the system provides the POSIX version of
1082 ** strerror_r(), which always writes an error message into aErr[].
1083 **
1084 ** If the code incorrectly assumes that it is the POSIX version that is
1085 ** available, the error message will often be an empty string. Not a
1086 ** huge problem. Incorrectly concluding that the GNU version is available
1087 ** could lead to a segfault though.
1088 */
1089#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1090 zErr =
1091# endif
drh0e9365c2011-03-02 02:08:13 +00001092 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001093
1094#elif SQLITE_THREADSAFE
1095 /* This is a threadsafe build, but strerror_r() is not available. */
1096 zErr = "";
1097#else
1098 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001099 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001100#endif
1101
1102 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001103 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001104 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001105 "os_unix.c:%d: (%d) %s(%s) - %s",
1106 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001107 );
1108
1109 return errcode;
1110}
1111
drh0e9365c2011-03-02 02:08:13 +00001112/*
1113** Close a file descriptor.
1114**
1115** We assume that close() almost always works, since it is only in a
1116** very sick application or on a very sick platform that it might fail.
1117** If it does fail, simply leak the file descriptor, but do log the
1118** error.
1119**
1120** Note that it is not safe to retry close() after EINTR since the
1121** file descriptor might have already been reused by another thread.
1122** So we don't even try to recover from an EINTR. Just log the error
1123** and move on.
1124*/
1125static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001126 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001127 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1128 pFile ? pFile->zPath : 0, lineno);
1129 }
1130}
dane18d4952011-02-21 11:46:24 +00001131
1132/*
danb0ac3e32010-06-16 10:55:42 +00001133** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001134*/
drh0e9365c2011-03-02 02:08:13 +00001135static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001136 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001137 UnixUnusedFd *p;
1138 UnixUnusedFd *pNext;
1139 for(p=pInode->pUnused; p; p=pNext){
1140 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001141 robust_close(pFile, p->fd, __LINE__);
1142 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001143 }
drh0e9365c2011-03-02 02:08:13 +00001144 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001145}
1146
1147/*
drh8af6c222010-05-14 12:43:01 +00001148** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001149**
1150** The mutex entered using the unixEnterMutex() function must be held
1151** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001152*/
danb0ac3e32010-06-16 10:55:42 +00001153static void releaseInodeInfo(unixFile *pFile){
1154 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001155 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001156 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001157 pInode->nRef--;
1158 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001159 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001160 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001161 if( pInode->pPrev ){
1162 assert( pInode->pPrev->pNext==pInode );
1163 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001164 }else{
drh8af6c222010-05-14 12:43:01 +00001165 assert( inodeList==pInode );
1166 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001167 }
drh8af6c222010-05-14 12:43:01 +00001168 if( pInode->pNext ){
1169 assert( pInode->pNext->pPrev==pInode );
1170 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001171 }
drh8af6c222010-05-14 12:43:01 +00001172 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001173 }
drhbbd42a62004-05-22 17:41:58 +00001174 }
1175}
1176
1177/*
drh8af6c222010-05-14 12:43:01 +00001178** Given a file descriptor, locate the unixInodeInfo object that
1179** describes that file descriptor. Create a new one if necessary. The
1180** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001181**
dan9359c7b2009-08-21 08:29:10 +00001182** The mutex entered using the unixEnterMutex() function must be held
1183** when this function is called.
1184**
drh6c7d5c52008-11-21 20:32:33 +00001185** Return an appropriate error code.
1186*/
drh8af6c222010-05-14 12:43:01 +00001187static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001188 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001189 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001190){
1191 int rc; /* System call return code */
1192 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001193 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1194 struct stat statbuf; /* Low-level file information */
1195 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001196
dan9359c7b2009-08-21 08:29:10 +00001197 assert( unixMutexHeld() );
1198
drh6c7d5c52008-11-21 20:32:33 +00001199 /* Get low-level information about the file that we can used to
1200 ** create a unique name for the file.
1201 */
1202 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001203 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001204 if( rc!=0 ){
1205 pFile->lastErrno = errno;
1206#ifdef EOVERFLOW
1207 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1208#endif
1209 return SQLITE_IOERR;
1210 }
1211
drheb0d74f2009-02-03 15:27:02 +00001212#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001213 /* On OS X on an msdos filesystem, the inode number is reported
1214 ** incorrectly for zero-size files. See ticket #3260. To work
1215 ** around this problem (we consider it a bug in OS X, not SQLite)
1216 ** we always increase the file size to 1 by writing a single byte
1217 ** prior to accessing the inode number. The one byte written is
1218 ** an ASCII 'S' character which also happens to be the first byte
1219 ** in the header of every SQLite database. In this way, if there
1220 ** is a race condition such that another thread has already populated
1221 ** the first page of the database, no damage is done.
1222 */
drh7ed97b92010-01-20 13:07:21 +00001223 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001224 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001225 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001226 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001227 return SQLITE_IOERR;
1228 }
drh99ab3b12011-03-02 15:09:07 +00001229 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001230 if( rc!=0 ){
1231 pFile->lastErrno = errno;
1232 return SQLITE_IOERR;
1233 }
1234 }
drheb0d74f2009-02-03 15:27:02 +00001235#endif
drh6c7d5c52008-11-21 20:32:33 +00001236
drh8af6c222010-05-14 12:43:01 +00001237 memset(&fileId, 0, sizeof(fileId));
1238 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001239#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001240 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001241#else
drh8af6c222010-05-14 12:43:01 +00001242 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001243#endif
drh8af6c222010-05-14 12:43:01 +00001244 pInode = inodeList;
1245 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1246 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001247 }
drh8af6c222010-05-14 12:43:01 +00001248 if( pInode==0 ){
1249 pInode = sqlite3_malloc( sizeof(*pInode) );
1250 if( pInode==0 ){
1251 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001252 }
drh8af6c222010-05-14 12:43:01 +00001253 memset(pInode, 0, sizeof(*pInode));
1254 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1255 pInode->nRef = 1;
1256 pInode->pNext = inodeList;
1257 pInode->pPrev = 0;
1258 if( inodeList ) inodeList->pPrev = pInode;
1259 inodeList = pInode;
1260 }else{
1261 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001262 }
drh8af6c222010-05-14 12:43:01 +00001263 *ppInode = pInode;
1264 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001265}
drh6c7d5c52008-11-21 20:32:33 +00001266
aswift5b1a2562008-08-22 00:22:35 +00001267
1268/*
danielk197713adf8a2004-06-03 16:08:41 +00001269** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001270** file by this or any other process. If such a lock is held, set *pResOut
1271** to a non-zero value otherwise *pResOut is set to zero. The return value
1272** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001273*/
danielk1977861f7452008-06-05 11:39:11 +00001274static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001275 int rc = SQLITE_OK;
1276 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001277 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001278
danielk1977861f7452008-06-05 11:39:11 +00001279 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1280
drh054889e2005-11-30 03:20:31 +00001281 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001282 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001283
1284 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001285 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001286 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001287 }
1288
drh2ac3ee92004-06-07 16:27:46 +00001289 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001290 */
danielk197709480a92009-02-09 05:32:32 +00001291#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001292 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001293 struct flock lock;
1294 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001295 lock.l_start = RESERVED_BYTE;
1296 lock.l_len = 1;
1297 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001298 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1299 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1300 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001301 } else if( lock.l_type!=F_UNLCK ){
1302 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001303 }
1304 }
danielk197709480a92009-02-09 05:32:32 +00001305#endif
danielk197713adf8a2004-06-03 16:08:41 +00001306
drh6c7d5c52008-11-21 20:32:33 +00001307 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001308 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001309
aswift5b1a2562008-08-22 00:22:35 +00001310 *pResOut = reserved;
1311 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001312}
1313
1314/*
drha7e61d82011-03-12 17:02:57 +00001315** Attempt to set a system-lock on the file pFile. The lock is
1316** described by pLock.
1317**
drh77197112011-03-15 19:08:48 +00001318** If the pFile was opened read/write from unix-excl, then the only lock
1319** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001320** the first time any lock is attempted. All subsequent system locking
1321** operations become no-ops. Locking operations still happen internally,
1322** in order to coordinate access between separate database connections
1323** within this process, but all of that is handled in memory and the
1324** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001325**
1326** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1327** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1328** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001329**
1330** Zero is returned if the call completes successfully, or -1 if a call
1331** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001332*/
1333static int unixFileLock(unixFile *pFile, struct flock *pLock){
1334 int rc;
drh3cb93392011-03-12 18:10:44 +00001335 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001336 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001337 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001338 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1339 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1340 ){
drh3cb93392011-03-12 18:10:44 +00001341 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001342 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001343 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001344 lock.l_whence = SEEK_SET;
1345 lock.l_start = SHARED_FIRST;
1346 lock.l_len = SHARED_SIZE;
1347 lock.l_type = F_WRLCK;
1348 rc = osFcntl(pFile->h, F_SETLK, &lock);
1349 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001350 pInode->bProcessLock = 1;
1351 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001352 }else{
1353 rc = 0;
1354 }
1355 }else{
1356 rc = osFcntl(pFile->h, F_SETLK, pLock);
1357 }
1358 return rc;
1359}
1360
1361/*
drh308c2a52010-05-14 11:30:18 +00001362** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001363** of the following:
1364**
drh2ac3ee92004-06-07 16:27:46 +00001365** (1) SHARED_LOCK
1366** (2) RESERVED_LOCK
1367** (3) PENDING_LOCK
1368** (4) EXCLUSIVE_LOCK
1369**
drhb3e04342004-06-08 00:47:47 +00001370** Sometimes when requesting one lock state, additional lock states
1371** are inserted in between. The locking might fail on one of the later
1372** transitions leaving the lock state different from what it started but
1373** still short of its goal. The following chart shows the allowed
1374** transitions and the inserted intermediate states:
1375**
1376** UNLOCKED -> SHARED
1377** SHARED -> RESERVED
1378** SHARED -> (PENDING) -> EXCLUSIVE
1379** RESERVED -> (PENDING) -> EXCLUSIVE
1380** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001381**
drha6abd042004-06-09 17:37:22 +00001382** This routine will only increase a lock. Use the sqlite3OsUnlock()
1383** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001384*/
drh308c2a52010-05-14 11:30:18 +00001385static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001386 /* The following describes the implementation of the various locks and
1387 ** lock transitions in terms of the POSIX advisory shared and exclusive
1388 ** lock primitives (called read-locks and write-locks below, to avoid
1389 ** confusion with SQLite lock names). The algorithms are complicated
1390 ** slightly in order to be compatible with windows systems simultaneously
1391 ** accessing the same database file, in case that is ever required.
1392 **
1393 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1394 ** byte', each single bytes at well known offsets, and the 'shared byte
1395 ** range', a range of 510 bytes at a well known offset.
1396 **
1397 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1398 ** byte'. If this is successful, a random byte from the 'shared byte
1399 ** range' is read-locked and the lock on the 'pending byte' released.
1400 **
danielk197790ba3bd2004-06-25 08:32:25 +00001401 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1402 ** A RESERVED lock is implemented by grabbing a write-lock on the
1403 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001404 **
1405 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001406 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1407 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1408 ** obtained, but existing SHARED locks are allowed to persist. A process
1409 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1410 ** This property is used by the algorithm for rolling back a journal file
1411 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001412 **
danielk197790ba3bd2004-06-25 08:32:25 +00001413 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1414 ** implemented by obtaining a write-lock on the entire 'shared byte
1415 ** range'. Since all other locks require a read-lock on one of the bytes
1416 ** within this range, this ensures that no other locks are held on the
1417 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001418 **
1419 ** The reason a single byte cannot be used instead of the 'shared byte
1420 ** range' is that some versions of windows do not support read-locks. By
1421 ** locking a random byte from a range, concurrent SHARED locks may exist
1422 ** even if the locking primitive used is always a write-lock.
1423 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001424 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001425 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001426 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001427 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001428 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001429
drh054889e2005-11-30 03:20:31 +00001430 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001431 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1432 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001433 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001434
1435 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001436 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001437 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001438 */
drh308c2a52010-05-14 11:30:18 +00001439 if( pFile->eFileLock>=eFileLock ){
1440 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1441 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001442 return SQLITE_OK;
1443 }
1444
drh0c2694b2009-09-03 16:23:44 +00001445 /* Make sure the locking sequence is correct.
1446 ** (1) We never move from unlocked to anything higher than shared lock.
1447 ** (2) SQLite never explicitly requests a pendig lock.
1448 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001449 */
drh308c2a52010-05-14 11:30:18 +00001450 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1451 assert( eFileLock!=PENDING_LOCK );
1452 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001453
drh8af6c222010-05-14 12:43:01 +00001454 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001455 */
drh6c7d5c52008-11-21 20:32:33 +00001456 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001457 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001458
danielk1977ad94b582007-08-20 06:44:22 +00001459 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001460 ** handle that precludes the requested lock, return BUSY.
1461 */
drh8af6c222010-05-14 12:43:01 +00001462 if( (pFile->eFileLock!=pInode->eFileLock &&
1463 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001464 ){
1465 rc = SQLITE_BUSY;
1466 goto end_lock;
1467 }
1468
1469 /* If a SHARED lock is requested, and some thread using this PID already
1470 ** has a SHARED or RESERVED lock, then increment reference counts and
1471 ** return SQLITE_OK.
1472 */
drh308c2a52010-05-14 11:30:18 +00001473 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001474 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001475 assert( eFileLock==SHARED_LOCK );
1476 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001477 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001478 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001479 pInode->nShared++;
1480 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001481 goto end_lock;
1482 }
1483
danielk19779a1d0ab2004-06-01 14:09:28 +00001484
drh3cde3bb2004-06-12 02:17:14 +00001485 /* A PENDING lock is needed before acquiring a SHARED lock and before
1486 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1487 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001488 */
drh0c2694b2009-09-03 16:23:44 +00001489 lock.l_len = 1L;
1490 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001491 if( eFileLock==SHARED_LOCK
1492 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001493 ){
drh308c2a52010-05-14 11:30:18 +00001494 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001495 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001496 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001497 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001498 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001499 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001500 pFile->lastErrno = tErrno;
1501 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001502 goto end_lock;
1503 }
drh3cde3bb2004-06-12 02:17:14 +00001504 }
1505
1506
1507 /* If control gets to this point, then actually go ahead and make
1508 ** operating system calls for the specified lock.
1509 */
drh308c2a52010-05-14 11:30:18 +00001510 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001511 assert( pInode->nShared==0 );
1512 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001513 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001514
drh2ac3ee92004-06-07 16:27:46 +00001515 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001516 lock.l_start = SHARED_FIRST;
1517 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001518 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001519 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001520 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001521 }
dan661d71a2011-03-30 19:08:03 +00001522
drh2ac3ee92004-06-07 16:27:46 +00001523 /* Drop the temporary PENDING lock */
1524 lock.l_start = PENDING_BYTE;
1525 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001526 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001527 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1528 /* This could happen with a network mount */
1529 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001530 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001531 }
dan661d71a2011-03-30 19:08:03 +00001532
1533 if( rc ){
1534 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001535 pFile->lastErrno = tErrno;
1536 }
dan661d71a2011-03-30 19:08:03 +00001537 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001538 }else{
drh308c2a52010-05-14 11:30:18 +00001539 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001540 pInode->nLock++;
1541 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001542 }
drh8af6c222010-05-14 12:43:01 +00001543 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001544 /* We are trying for an exclusive lock but another thread in this
1545 ** same process is still holding a shared lock. */
1546 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001547 }else{
drh3cde3bb2004-06-12 02:17:14 +00001548 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001549 ** assumed that there is a SHARED or greater lock on the file
1550 ** already.
1551 */
drh308c2a52010-05-14 11:30:18 +00001552 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001553 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001554
1555 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1556 if( eFileLock==RESERVED_LOCK ){
1557 lock.l_start = RESERVED_BYTE;
1558 lock.l_len = 1L;
1559 }else{
1560 lock.l_start = SHARED_FIRST;
1561 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001562 }
dan661d71a2011-03-30 19:08:03 +00001563
1564 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001565 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001566 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001567 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001568 pFile->lastErrno = tErrno;
1569 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001570 }
drhbbd42a62004-05-22 17:41:58 +00001571 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001572
drh8f941bc2009-01-14 23:03:40 +00001573
drhd3d8c042012-05-29 17:02:40 +00001574#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001575 /* Set up the transaction-counter change checking flags when
1576 ** transitioning from a SHARED to a RESERVED lock. The change
1577 ** from SHARED to RESERVED marks the beginning of a normal
1578 ** write operation (not a hot journal rollback).
1579 */
1580 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001581 && pFile->eFileLock<=SHARED_LOCK
1582 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001583 ){
1584 pFile->transCntrChng = 0;
1585 pFile->dbUpdate = 0;
1586 pFile->inNormalWrite = 1;
1587 }
1588#endif
1589
1590
danielk1977ecb2a962004-06-02 06:30:16 +00001591 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001592 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001593 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001594 }else if( eFileLock==EXCLUSIVE_LOCK ){
1595 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001596 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001597 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001598
1599end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001600 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001601 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1602 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001603 return rc;
1604}
1605
1606/*
dan08da86a2009-08-21 17:18:03 +00001607** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001608** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001609*/
1610static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001611 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001612 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001613 p->pNext = pInode->pUnused;
1614 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001615 pFile->h = -1;
1616 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001617}
1618
1619/*
drh308c2a52010-05-14 11:30:18 +00001620** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001621** must be either NO_LOCK or SHARED_LOCK.
1622**
1623** If the locking level of the file descriptor is already at or below
1624** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001625**
1626** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1627** the byte range is divided into 2 parts and the first part is unlocked then
1628** set to a read lock, then the other part is simply unlocked. This works
1629** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1630** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001631*/
drha7e61d82011-03-12 17:02:57 +00001632static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001633 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001634 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001635 struct flock lock;
1636 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001637
drh054889e2005-11-30 03:20:31 +00001638 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001639 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001640 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001641 getpid()));
drha6abd042004-06-09 17:37:22 +00001642
drh308c2a52010-05-14 11:30:18 +00001643 assert( eFileLock<=SHARED_LOCK );
1644 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001645 return SQLITE_OK;
1646 }
drh6c7d5c52008-11-21 20:32:33 +00001647 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001648 pInode = pFile->pInode;
1649 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001650 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001651 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001652
drhd3d8c042012-05-29 17:02:40 +00001653#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001654 /* When reducing a lock such that other processes can start
1655 ** reading the database file again, make sure that the
1656 ** transaction counter was updated if any part of the database
1657 ** file changed. If the transaction counter is not updated,
1658 ** other connections to the same file might not realize that
1659 ** the file has changed and hence might not know to flush their
1660 ** cache. The use of a stale cache can lead to database corruption.
1661 */
drh8f941bc2009-01-14 23:03:40 +00001662 pFile->inNormalWrite = 0;
1663#endif
1664
drh7ed97b92010-01-20 13:07:21 +00001665 /* downgrading to a shared lock on NFS involves clearing the write lock
1666 ** before establishing the readlock - to avoid a race condition we downgrade
1667 ** the lock in 2 blocks, so that part of the range will be covered by a
1668 ** write lock until the rest is covered by a read lock:
1669 ** 1: [WWWWW]
1670 ** 2: [....W]
1671 ** 3: [RRRRW]
1672 ** 4: [RRRR.]
1673 */
drh308c2a52010-05-14 11:30:18 +00001674 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001675
1676#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001677 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001678 assert( handleNFSUnlock==0 );
1679#endif
1680#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001681 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001682 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001683 off_t divSize = SHARED_SIZE - 1;
1684
1685 lock.l_type = F_UNLCK;
1686 lock.l_whence = SEEK_SET;
1687 lock.l_start = SHARED_FIRST;
1688 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001689 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001690 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001691 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001692 if( IS_LOCK_ERROR(rc) ){
1693 pFile->lastErrno = tErrno;
1694 }
1695 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001696 }
drh7ed97b92010-01-20 13:07:21 +00001697 lock.l_type = F_RDLCK;
1698 lock.l_whence = SEEK_SET;
1699 lock.l_start = SHARED_FIRST;
1700 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001701 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001702 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001703 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1704 if( IS_LOCK_ERROR(rc) ){
1705 pFile->lastErrno = tErrno;
1706 }
1707 goto end_unlock;
1708 }
1709 lock.l_type = F_UNLCK;
1710 lock.l_whence = SEEK_SET;
1711 lock.l_start = SHARED_FIRST+divSize;
1712 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001713 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001714 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001715 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001716 if( IS_LOCK_ERROR(rc) ){
1717 pFile->lastErrno = tErrno;
1718 }
1719 goto end_unlock;
1720 }
drh30f776f2011-02-25 03:25:07 +00001721 }else
1722#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1723 {
drh7ed97b92010-01-20 13:07:21 +00001724 lock.l_type = F_RDLCK;
1725 lock.l_whence = SEEK_SET;
1726 lock.l_start = SHARED_FIRST;
1727 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001728 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001729 /* In theory, the call to unixFileLock() cannot fail because another
1730 ** process is holding an incompatible lock. If it does, this
1731 ** indicates that the other process is not following the locking
1732 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1733 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1734 ** an assert to fail). */
1735 rc = SQLITE_IOERR_RDLOCK;
1736 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001737 goto end_unlock;
1738 }
drh9c105bb2004-10-02 20:38:28 +00001739 }
1740 }
drhbbd42a62004-05-22 17:41:58 +00001741 lock.l_type = F_UNLCK;
1742 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001743 lock.l_start = PENDING_BYTE;
1744 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001745 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001746 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001747 }else{
danea83bc62011-04-01 11:56:32 +00001748 rc = SQLITE_IOERR_UNLOCK;
1749 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001750 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001751 }
drhbbd42a62004-05-22 17:41:58 +00001752 }
drh308c2a52010-05-14 11:30:18 +00001753 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001754 /* Decrement the shared lock counter. Release the lock using an
1755 ** OS call only when all threads in this same process have released
1756 ** the lock.
1757 */
drh8af6c222010-05-14 12:43:01 +00001758 pInode->nShared--;
1759 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001760 lock.l_type = F_UNLCK;
1761 lock.l_whence = SEEK_SET;
1762 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001763 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001764 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001765 }else{
danea83bc62011-04-01 11:56:32 +00001766 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001767 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001768 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001769 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001770 }
drha6abd042004-06-09 17:37:22 +00001771 }
1772
drhbbd42a62004-05-22 17:41:58 +00001773 /* Decrement the count of locks against this same file. When the
1774 ** count reaches zero, close any other file descriptors whose close
1775 ** was deferred because of outstanding locks.
1776 */
drh8af6c222010-05-14 12:43:01 +00001777 pInode->nLock--;
1778 assert( pInode->nLock>=0 );
1779 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001780 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001781 }
1782 }
drhf2f105d2012-08-20 15:53:54 +00001783
aswift5b1a2562008-08-22 00:22:35 +00001784end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001785 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001786 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001787 return rc;
drhbbd42a62004-05-22 17:41:58 +00001788}
1789
1790/*
drh308c2a52010-05-14 11:30:18 +00001791** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001792** must be either NO_LOCK or SHARED_LOCK.
1793**
1794** If the locking level of the file descriptor is already at or below
1795** the requested locking level, this routine is a no-op.
1796*/
drh308c2a52010-05-14 11:30:18 +00001797static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001798 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001799}
1800
1801/*
danielk1977e339d652008-06-28 11:23:00 +00001802** This function performs the parts of the "close file" operation
1803** common to all locking schemes. It closes the directory and file
1804** handles, if they are valid, and sets all fields of the unixFile
1805** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001806**
1807** It is *not* necessary to hold the mutex when this routine is called,
1808** even on VxWorks. A mutex will be acquired on VxWorks by the
1809** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001810*/
1811static int closeUnixFile(sqlite3_file *id){
1812 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001813 if( pFile->h>=0 ){
1814 robust_close(pFile, pFile->h, __LINE__);
1815 pFile->h = -1;
1816 }
1817#if OS_VXWORKS
1818 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001819 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001820 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001821 }
1822 vxworksReleaseFileId(pFile->pId);
1823 pFile->pId = 0;
1824 }
1825#endif
1826 OSTRACE(("CLOSE %-3d\n", pFile->h));
1827 OpenCounter(-1);
1828 sqlite3_free(pFile->pUnused);
1829 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001830 return SQLITE_OK;
1831}
1832
1833/*
danielk1977e3026632004-06-22 11:29:02 +00001834** Close a file.
1835*/
danielk197762079062007-08-15 17:08:46 +00001836static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001837 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001838 unixFile *pFile = (unixFile *)id;
1839 unixUnlock(id, NO_LOCK);
1840 unixEnterMutex();
1841
1842 /* unixFile.pInode is always valid here. Otherwise, a different close
1843 ** routine (e.g. nolockClose()) would be called instead.
1844 */
1845 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1846 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1847 /* If there are outstanding locks, do not actually close the file just
1848 ** yet because that would clear those locks. Instead, add the file
1849 ** descriptor to pInode->pUnused list. It will be automatically closed
1850 ** when the last lock is cleared.
1851 */
1852 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001853 }
dan661d71a2011-03-30 19:08:03 +00001854 releaseInodeInfo(pFile);
1855 rc = closeUnixFile(id);
1856 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001857 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001858}
1859
drh734c9862008-11-28 15:37:20 +00001860/************** End of the posix advisory lock implementation *****************
1861******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001862
drh734c9862008-11-28 15:37:20 +00001863/******************************************************************************
1864****************************** No-op Locking **********************************
1865**
1866** Of the various locking implementations available, this is by far the
1867** simplest: locking is ignored. No attempt is made to lock the database
1868** file for reading or writing.
1869**
1870** This locking mode is appropriate for use on read-only databases
1871** (ex: databases that are burned into CD-ROM, for example.) It can
1872** also be used if the application employs some external mechanism to
1873** prevent simultaneous access of the same database by two or more
1874** database connections. But there is a serious risk of database
1875** corruption if this locking mode is used in situations where multiple
1876** database connections are accessing the same database file at the same
1877** time and one or more of those connections are writing.
1878*/
drhbfe66312006-10-03 17:40:40 +00001879
drh734c9862008-11-28 15:37:20 +00001880static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1881 UNUSED_PARAMETER(NotUsed);
1882 *pResOut = 0;
1883 return SQLITE_OK;
1884}
drh734c9862008-11-28 15:37:20 +00001885static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1886 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1887 return SQLITE_OK;
1888}
drh734c9862008-11-28 15:37:20 +00001889static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1890 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1891 return SQLITE_OK;
1892}
1893
1894/*
drh9b35ea62008-11-29 02:20:26 +00001895** Close the file.
drh734c9862008-11-28 15:37:20 +00001896*/
1897static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001898 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001899}
1900
1901/******************* End of the no-op lock implementation *********************
1902******************************************************************************/
1903
1904/******************************************************************************
1905************************* Begin dot-file Locking ******************************
1906**
drh0c2694b2009-09-03 16:23:44 +00001907** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001908** files (really a directory) to control access to the database. This works
1909** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001910**
1911** (1) There is zero concurrency. A single reader blocks all other
1912** connections from reading or writing the database.
1913**
1914** (2) An application crash or power loss can leave stale lock files
1915** sitting around that need to be cleared manually.
1916**
1917** Nevertheless, a dotlock is an appropriate locking mode for use if no
1918** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001919**
drh9ef6bc42011-11-04 02:24:02 +00001920** Dotfile locking works by creating a subdirectory in the same directory as
1921** the database and with the same name but with a ".lock" extension added.
1922** The existance of a lock directory implies an EXCLUSIVE lock. All other
1923** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001924*/
1925
1926/*
1927** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001928** lock directory.
drh734c9862008-11-28 15:37:20 +00001929*/
1930#define DOTLOCK_SUFFIX ".lock"
1931
drh7708e972008-11-29 00:56:52 +00001932/*
1933** This routine checks if there is a RESERVED lock held on the specified
1934** file by this or any other process. If such a lock is held, set *pResOut
1935** to a non-zero value otherwise *pResOut is set to zero. The return value
1936** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1937**
1938** In dotfile locking, either a lock exists or it does not. So in this
1939** variation of CheckReservedLock(), *pResOut is set to true if any lock
1940** is held on the file and false if the file is unlocked.
1941*/
drh734c9862008-11-28 15:37:20 +00001942static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1943 int rc = SQLITE_OK;
1944 int reserved = 0;
1945 unixFile *pFile = (unixFile*)id;
1946
1947 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1948
1949 assert( pFile );
1950
1951 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001952 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001953 /* Either this connection or some other connection in the same process
1954 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001955 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001956 }else{
1957 /* The lock is held if and only if the lockfile exists */
1958 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001959 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001960 }
drh308c2a52010-05-14 11:30:18 +00001961 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001962 *pResOut = reserved;
1963 return rc;
1964}
1965
drh7708e972008-11-29 00:56:52 +00001966/*
drh308c2a52010-05-14 11:30:18 +00001967** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001968** of the following:
1969**
1970** (1) SHARED_LOCK
1971** (2) RESERVED_LOCK
1972** (3) PENDING_LOCK
1973** (4) EXCLUSIVE_LOCK
1974**
1975** Sometimes when requesting one lock state, additional lock states
1976** are inserted in between. The locking might fail on one of the later
1977** transitions leaving the lock state different from what it started but
1978** still short of its goal. The following chart shows the allowed
1979** transitions and the inserted intermediate states:
1980**
1981** UNLOCKED -> SHARED
1982** SHARED -> RESERVED
1983** SHARED -> (PENDING) -> EXCLUSIVE
1984** RESERVED -> (PENDING) -> EXCLUSIVE
1985** PENDING -> EXCLUSIVE
1986**
1987** This routine will only increase a lock. Use the sqlite3OsUnlock()
1988** routine to lower a locking level.
1989**
1990** With dotfile locking, we really only support state (4): EXCLUSIVE.
1991** But we track the other locking levels internally.
1992*/
drh308c2a52010-05-14 11:30:18 +00001993static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001994 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001995 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001996 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001997
drh7708e972008-11-29 00:56:52 +00001998
1999 /* If we have any lock, then the lock file already exists. All we have
2000 ** to do is adjust our internal record of the lock level.
2001 */
drh308c2a52010-05-14 11:30:18 +00002002 if( pFile->eFileLock > NO_LOCK ){
2003 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002004 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002005#ifdef HAVE_UTIME
2006 utime(zLockFile, NULL);
2007#else
drh734c9862008-11-28 15:37:20 +00002008 utimes(zLockFile, NULL);
2009#endif
drh7708e972008-11-29 00:56:52 +00002010 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002011 }
2012
2013 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002014 rc = osMkdir(zLockFile, 0777);
2015 if( rc<0 ){
2016 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002017 int tErrno = errno;
2018 if( EEXIST == tErrno ){
2019 rc = SQLITE_BUSY;
2020 } else {
2021 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2022 if( IS_LOCK_ERROR(rc) ){
2023 pFile->lastErrno = tErrno;
2024 }
2025 }
drh7708e972008-11-29 00:56:52 +00002026 return rc;
drh734c9862008-11-28 15:37:20 +00002027 }
drh734c9862008-11-28 15:37:20 +00002028
2029 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002030 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002031 return rc;
2032}
2033
drh7708e972008-11-29 00:56:52 +00002034/*
drh308c2a52010-05-14 11:30:18 +00002035** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002036** must be either NO_LOCK or SHARED_LOCK.
2037**
2038** If the locking level of the file descriptor is already at or below
2039** the requested locking level, this routine is a no-op.
2040**
2041** When the locking level reaches NO_LOCK, delete the lock file.
2042*/
drh308c2a52010-05-14 11:30:18 +00002043static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002044 unixFile *pFile = (unixFile*)id;
2045 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002046 int rc;
drh734c9862008-11-28 15:37:20 +00002047
2048 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002049 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002050 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002051 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002052
2053 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002054 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002055 return SQLITE_OK;
2056 }
drh7708e972008-11-29 00:56:52 +00002057
2058 /* To downgrade to shared, simply update our internal notion of the
2059 ** lock state. No need to mess with the file on disk.
2060 */
drh308c2a52010-05-14 11:30:18 +00002061 if( eFileLock==SHARED_LOCK ){
2062 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002063 return SQLITE_OK;
2064 }
2065
drh7708e972008-11-29 00:56:52 +00002066 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002067 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002068 rc = osRmdir(zLockFile);
2069 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2070 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002071 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002072 rc = 0;
drh734c9862008-11-28 15:37:20 +00002073 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002074 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002075 }
2076 if( IS_LOCK_ERROR(rc) ){
2077 pFile->lastErrno = tErrno;
2078 }
2079 return rc;
2080 }
drh308c2a52010-05-14 11:30:18 +00002081 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002082 return SQLITE_OK;
2083}
2084
2085/*
drh9b35ea62008-11-29 02:20:26 +00002086** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002087*/
2088static int dotlockClose(sqlite3_file *id) {
2089 int rc;
2090 if( id ){
2091 unixFile *pFile = (unixFile*)id;
2092 dotlockUnlock(id, NO_LOCK);
2093 sqlite3_free(pFile->lockingContext);
2094 }
drh734c9862008-11-28 15:37:20 +00002095 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002096 return rc;
2097}
2098/****************** End of the dot-file lock implementation *******************
2099******************************************************************************/
2100
2101/******************************************************************************
2102************************** Begin flock Locking ********************************
2103**
2104** Use the flock() system call to do file locking.
2105**
drh6b9d6dd2008-12-03 19:34:47 +00002106** flock() locking is like dot-file locking in that the various
2107** fine-grain locking levels supported by SQLite are collapsed into
2108** a single exclusive lock. In other words, SHARED, RESERVED, and
2109** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2110** still works when you do this, but concurrency is reduced since
2111** only a single process can be reading the database at a time.
2112**
drh734c9862008-11-28 15:37:20 +00002113** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2114** compiling for VXWORKS.
2115*/
2116#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002117
drh6b9d6dd2008-12-03 19:34:47 +00002118/*
drhff812312011-02-23 13:33:46 +00002119** Retry flock() calls that fail with EINTR
2120*/
2121#ifdef EINTR
2122static int robust_flock(int fd, int op){
2123 int rc;
2124 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2125 return rc;
2126}
2127#else
drh5c819272011-02-23 14:00:12 +00002128# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002129#endif
2130
2131
2132/*
drh6b9d6dd2008-12-03 19:34:47 +00002133** This routine checks if there is a RESERVED lock held on the specified
2134** file by this or any other process. If such a lock is held, set *pResOut
2135** to a non-zero value otherwise *pResOut is set to zero. The return value
2136** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2137*/
drh734c9862008-11-28 15:37:20 +00002138static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2139 int rc = SQLITE_OK;
2140 int reserved = 0;
2141 unixFile *pFile = (unixFile*)id;
2142
2143 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2144
2145 assert( pFile );
2146
2147 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002148 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002149 reserved = 1;
2150 }
2151
2152 /* Otherwise see if some other process holds it. */
2153 if( !reserved ){
2154 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002155 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002156 if( !lrc ){
2157 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002158 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002159 if ( lrc ) {
2160 int tErrno = errno;
2161 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002162 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002163 if( IS_LOCK_ERROR(lrc) ){
2164 pFile->lastErrno = tErrno;
2165 rc = lrc;
2166 }
2167 }
2168 } else {
2169 int tErrno = errno;
2170 reserved = 1;
2171 /* someone else might have it reserved */
2172 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2173 if( IS_LOCK_ERROR(lrc) ){
2174 pFile->lastErrno = tErrno;
2175 rc = lrc;
2176 }
2177 }
2178 }
drh308c2a52010-05-14 11:30:18 +00002179 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002180
2181#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2182 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2183 rc = SQLITE_OK;
2184 reserved=1;
2185 }
2186#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2187 *pResOut = reserved;
2188 return rc;
2189}
2190
drh6b9d6dd2008-12-03 19:34:47 +00002191/*
drh308c2a52010-05-14 11:30:18 +00002192** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002193** of the following:
2194**
2195** (1) SHARED_LOCK
2196** (2) RESERVED_LOCK
2197** (3) PENDING_LOCK
2198** (4) EXCLUSIVE_LOCK
2199**
2200** Sometimes when requesting one lock state, additional lock states
2201** are inserted in between. The locking might fail on one of the later
2202** transitions leaving the lock state different from what it started but
2203** still short of its goal. The following chart shows the allowed
2204** transitions and the inserted intermediate states:
2205**
2206** UNLOCKED -> SHARED
2207** SHARED -> RESERVED
2208** SHARED -> (PENDING) -> EXCLUSIVE
2209** RESERVED -> (PENDING) -> EXCLUSIVE
2210** PENDING -> EXCLUSIVE
2211**
2212** flock() only really support EXCLUSIVE locks. We track intermediate
2213** lock states in the sqlite3_file structure, but all locks SHARED or
2214** above are really EXCLUSIVE locks and exclude all other processes from
2215** access the file.
2216**
2217** This routine will only increase a lock. Use the sqlite3OsUnlock()
2218** routine to lower a locking level.
2219*/
drh308c2a52010-05-14 11:30:18 +00002220static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002221 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002222 unixFile *pFile = (unixFile*)id;
2223
2224 assert( pFile );
2225
2226 /* if we already have a lock, it is exclusive.
2227 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002228 if (pFile->eFileLock > NO_LOCK) {
2229 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002230 return SQLITE_OK;
2231 }
2232
2233 /* grab an exclusive lock */
2234
drhff812312011-02-23 13:33:46 +00002235 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002236 int tErrno = errno;
2237 /* didn't get, must be busy */
2238 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2239 if( IS_LOCK_ERROR(rc) ){
2240 pFile->lastErrno = tErrno;
2241 }
2242 } else {
2243 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002244 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002245 }
drh308c2a52010-05-14 11:30:18 +00002246 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2247 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002248#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2249 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2250 rc = SQLITE_BUSY;
2251 }
2252#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2253 return rc;
2254}
2255
drh6b9d6dd2008-12-03 19:34:47 +00002256
2257/*
drh308c2a52010-05-14 11:30:18 +00002258** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002259** must be either NO_LOCK or SHARED_LOCK.
2260**
2261** If the locking level of the file descriptor is already at or below
2262** the requested locking level, this routine is a no-op.
2263*/
drh308c2a52010-05-14 11:30:18 +00002264static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002265 unixFile *pFile = (unixFile*)id;
2266
2267 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002268 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2269 pFile->eFileLock, getpid()));
2270 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002271
2272 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002273 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002274 return SQLITE_OK;
2275 }
2276
2277 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002278 if (eFileLock==SHARED_LOCK) {
2279 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002280 return SQLITE_OK;
2281 }
2282
2283 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002284 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002285#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002286 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002287#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002288 return SQLITE_IOERR_UNLOCK;
2289 }else{
drh308c2a52010-05-14 11:30:18 +00002290 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002291 return SQLITE_OK;
2292 }
2293}
2294
2295/*
2296** Close a file.
2297*/
2298static int flockClose(sqlite3_file *id) {
2299 if( id ){
2300 flockUnlock(id, NO_LOCK);
2301 }
2302 return closeUnixFile(id);
2303}
2304
2305#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2306
2307/******************* End of the flock lock implementation *********************
2308******************************************************************************/
2309
2310/******************************************************************************
2311************************ Begin Named Semaphore Locking ************************
2312**
2313** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002314**
2315** Semaphore locking is like dot-lock and flock in that it really only
2316** supports EXCLUSIVE locking. Only a single process can read or write
2317** the database file at a time. This reduces potential concurrency, but
2318** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002319*/
2320#if OS_VXWORKS
2321
drh6b9d6dd2008-12-03 19:34:47 +00002322/*
2323** This routine checks if there is a RESERVED lock held on the specified
2324** file by this or any other process. If such a lock is held, set *pResOut
2325** to a non-zero value otherwise *pResOut is set to zero. The return value
2326** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2327*/
drh734c9862008-11-28 15:37:20 +00002328static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2329 int rc = SQLITE_OK;
2330 int reserved = 0;
2331 unixFile *pFile = (unixFile*)id;
2332
2333 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2334
2335 assert( pFile );
2336
2337 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002338 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002339 reserved = 1;
2340 }
2341
2342 /* Otherwise see if some other process holds it. */
2343 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002344 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002345 struct stat statBuf;
2346
2347 if( sem_trywait(pSem)==-1 ){
2348 int tErrno = errno;
2349 if( EAGAIN != tErrno ){
2350 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2351 pFile->lastErrno = tErrno;
2352 } else {
2353 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002354 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002355 }
2356 }else{
2357 /* we could have it if we want it */
2358 sem_post(pSem);
2359 }
2360 }
drh308c2a52010-05-14 11:30:18 +00002361 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002362
2363 *pResOut = reserved;
2364 return rc;
2365}
2366
drh6b9d6dd2008-12-03 19:34:47 +00002367/*
drh308c2a52010-05-14 11:30:18 +00002368** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002369** of the following:
2370**
2371** (1) SHARED_LOCK
2372** (2) RESERVED_LOCK
2373** (3) PENDING_LOCK
2374** (4) EXCLUSIVE_LOCK
2375**
2376** Sometimes when requesting one lock state, additional lock states
2377** are inserted in between. The locking might fail on one of the later
2378** transitions leaving the lock state different from what it started but
2379** still short of its goal. The following chart shows the allowed
2380** transitions and the inserted intermediate states:
2381**
2382** UNLOCKED -> SHARED
2383** SHARED -> RESERVED
2384** SHARED -> (PENDING) -> EXCLUSIVE
2385** RESERVED -> (PENDING) -> EXCLUSIVE
2386** PENDING -> EXCLUSIVE
2387**
2388** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2389** lock states in the sqlite3_file structure, but all locks SHARED or
2390** above are really EXCLUSIVE locks and exclude all other processes from
2391** access the file.
2392**
2393** This routine will only increase a lock. Use the sqlite3OsUnlock()
2394** routine to lower a locking level.
2395*/
drh308c2a52010-05-14 11:30:18 +00002396static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002397 unixFile *pFile = (unixFile*)id;
2398 int fd;
drh8af6c222010-05-14 12:43:01 +00002399 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002400 int rc = SQLITE_OK;
2401
2402 /* if we already have a lock, it is exclusive.
2403 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002404 if (pFile->eFileLock > NO_LOCK) {
2405 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002406 rc = SQLITE_OK;
2407 goto sem_end_lock;
2408 }
2409
2410 /* lock semaphore now but bail out when already locked. */
2411 if( sem_trywait(pSem)==-1 ){
2412 rc = SQLITE_BUSY;
2413 goto sem_end_lock;
2414 }
2415
2416 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002417 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002418
2419 sem_end_lock:
2420 return rc;
2421}
2422
drh6b9d6dd2008-12-03 19:34:47 +00002423/*
drh308c2a52010-05-14 11:30:18 +00002424** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002425** must be either NO_LOCK or SHARED_LOCK.
2426**
2427** If the locking level of the file descriptor is already at or below
2428** the requested locking level, this routine is a no-op.
2429*/
drh308c2a52010-05-14 11:30:18 +00002430static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002431 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002432 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002433
2434 assert( pFile );
2435 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002436 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002437 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002438 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002439
2440 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002441 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002442 return SQLITE_OK;
2443 }
2444
2445 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002446 if (eFileLock==SHARED_LOCK) {
2447 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002448 return SQLITE_OK;
2449 }
2450
2451 /* no, really unlock. */
2452 if ( sem_post(pSem)==-1 ) {
2453 int rc, tErrno = errno;
2454 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2455 if( IS_LOCK_ERROR(rc) ){
2456 pFile->lastErrno = tErrno;
2457 }
2458 return rc;
2459 }
drh308c2a52010-05-14 11:30:18 +00002460 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002461 return SQLITE_OK;
2462}
2463
2464/*
2465 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002466 */
drh734c9862008-11-28 15:37:20 +00002467static int semClose(sqlite3_file *id) {
2468 if( id ){
2469 unixFile *pFile = (unixFile*)id;
2470 semUnlock(id, NO_LOCK);
2471 assert( pFile );
2472 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002473 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002474 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002475 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002476 }
2477 return SQLITE_OK;
2478}
2479
2480#endif /* OS_VXWORKS */
2481/*
2482** Named semaphore locking is only available on VxWorks.
2483**
2484*************** End of the named semaphore lock implementation ****************
2485******************************************************************************/
2486
2487
2488/******************************************************************************
2489*************************** Begin AFP Locking *********************************
2490**
2491** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2492** on Apple Macintosh computers - both OS9 and OSX.
2493**
2494** Third-party implementations of AFP are available. But this code here
2495** only works on OSX.
2496*/
2497
drhd2cb50b2009-01-09 21:41:17 +00002498#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002499/*
2500** The afpLockingContext structure contains all afp lock specific state
2501*/
drhbfe66312006-10-03 17:40:40 +00002502typedef struct afpLockingContext afpLockingContext;
2503struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002504 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002505 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002506};
2507
2508struct ByteRangeLockPB2
2509{
2510 unsigned long long offset; /* offset to first byte to lock */
2511 unsigned long long length; /* nbr of bytes to lock */
2512 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2513 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2514 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2515 int fd; /* file desc to assoc this lock with */
2516};
2517
drhfd131da2007-08-07 17:13:03 +00002518#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002519
drh6b9d6dd2008-12-03 19:34:47 +00002520/*
2521** This is a utility for setting or clearing a bit-range lock on an
2522** AFP filesystem.
2523**
2524** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2525*/
2526static int afpSetLock(
2527 const char *path, /* Name of the file to be locked or unlocked */
2528 unixFile *pFile, /* Open file descriptor on path */
2529 unsigned long long offset, /* First byte to be locked */
2530 unsigned long long length, /* Number of bytes to lock */
2531 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002532){
drh6b9d6dd2008-12-03 19:34:47 +00002533 struct ByteRangeLockPB2 pb;
2534 int err;
drhbfe66312006-10-03 17:40:40 +00002535
2536 pb.unLockFlag = setLockFlag ? 0 : 1;
2537 pb.startEndFlag = 0;
2538 pb.offset = offset;
2539 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002540 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002541
drh308c2a52010-05-14 11:30:18 +00002542 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002543 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002544 offset, length));
drhbfe66312006-10-03 17:40:40 +00002545 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2546 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002547 int rc;
2548 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002549 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2550 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002551#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2552 rc = SQLITE_BUSY;
2553#else
drh734c9862008-11-28 15:37:20 +00002554 rc = sqliteErrorFromPosixError(tErrno,
2555 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002556#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002557 if( IS_LOCK_ERROR(rc) ){
2558 pFile->lastErrno = tErrno;
2559 }
2560 return rc;
drhbfe66312006-10-03 17:40:40 +00002561 } else {
aswift5b1a2562008-08-22 00:22:35 +00002562 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002563 }
2564}
2565
drh6b9d6dd2008-12-03 19:34:47 +00002566/*
2567** This routine checks if there is a RESERVED lock held on the specified
2568** file by this or any other process. If such a lock is held, set *pResOut
2569** to a non-zero value otherwise *pResOut is set to zero. The return value
2570** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2571*/
danielk1977e339d652008-06-28 11:23:00 +00002572static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002573 int rc = SQLITE_OK;
2574 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002575 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002576 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002577
aswift5b1a2562008-08-22 00:22:35 +00002578 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2579
2580 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002581 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002582 if( context->reserved ){
2583 *pResOut = 1;
2584 return SQLITE_OK;
2585 }
drh8af6c222010-05-14 12:43:01 +00002586 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002587
2588 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002589 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002590 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002591 }
2592
2593 /* Otherwise see if some other process holds it.
2594 */
aswift5b1a2562008-08-22 00:22:35 +00002595 if( !reserved ){
2596 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002597 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002598 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002599 /* if we succeeded in taking the reserved lock, unlock it to restore
2600 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002601 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002602 } else {
2603 /* if we failed to get the lock then someone else must have it */
2604 reserved = 1;
2605 }
2606 if( IS_LOCK_ERROR(lrc) ){
2607 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002608 }
2609 }
drhbfe66312006-10-03 17:40:40 +00002610
drh7ed97b92010-01-20 13:07:21 +00002611 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002612 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002613
2614 *pResOut = reserved;
2615 return rc;
drhbfe66312006-10-03 17:40:40 +00002616}
2617
drh6b9d6dd2008-12-03 19:34:47 +00002618/*
drh308c2a52010-05-14 11:30:18 +00002619** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002620** of the following:
2621**
2622** (1) SHARED_LOCK
2623** (2) RESERVED_LOCK
2624** (3) PENDING_LOCK
2625** (4) EXCLUSIVE_LOCK
2626**
2627** Sometimes when requesting one lock state, additional lock states
2628** are inserted in between. The locking might fail on one of the later
2629** transitions leaving the lock state different from what it started but
2630** still short of its goal. The following chart shows the allowed
2631** transitions and the inserted intermediate states:
2632**
2633** UNLOCKED -> SHARED
2634** SHARED -> RESERVED
2635** SHARED -> (PENDING) -> EXCLUSIVE
2636** RESERVED -> (PENDING) -> EXCLUSIVE
2637** PENDING -> EXCLUSIVE
2638**
2639** This routine will only increase a lock. Use the sqlite3OsUnlock()
2640** routine to lower a locking level.
2641*/
drh308c2a52010-05-14 11:30:18 +00002642static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002643 int rc = SQLITE_OK;
2644 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002645 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002646 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002647
2648 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002649 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2650 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002651 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002652
drhbfe66312006-10-03 17:40:40 +00002653 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002654 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002655 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002656 */
drh308c2a52010-05-14 11:30:18 +00002657 if( pFile->eFileLock>=eFileLock ){
2658 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2659 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002660 return SQLITE_OK;
2661 }
2662
2663 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002664 ** (1) We never move from unlocked to anything higher than shared lock.
2665 ** (2) SQLite never explicitly requests a pendig lock.
2666 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002667 */
drh308c2a52010-05-14 11:30:18 +00002668 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2669 assert( eFileLock!=PENDING_LOCK );
2670 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002671
drh8af6c222010-05-14 12:43:01 +00002672 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002673 */
drh6c7d5c52008-11-21 20:32:33 +00002674 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002675 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002676
2677 /* If some thread using this PID has a lock via a different unixFile*
2678 ** handle that precludes the requested lock, return BUSY.
2679 */
drh8af6c222010-05-14 12:43:01 +00002680 if( (pFile->eFileLock!=pInode->eFileLock &&
2681 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002682 ){
2683 rc = SQLITE_BUSY;
2684 goto afp_end_lock;
2685 }
2686
2687 /* If a SHARED lock is requested, and some thread using this PID already
2688 ** has a SHARED or RESERVED lock, then increment reference counts and
2689 ** return SQLITE_OK.
2690 */
drh308c2a52010-05-14 11:30:18 +00002691 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002692 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002693 assert( eFileLock==SHARED_LOCK );
2694 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002695 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002696 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002697 pInode->nShared++;
2698 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002699 goto afp_end_lock;
2700 }
drhbfe66312006-10-03 17:40:40 +00002701
2702 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002703 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2704 ** be released.
2705 */
drh308c2a52010-05-14 11:30:18 +00002706 if( eFileLock==SHARED_LOCK
2707 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002708 ){
2709 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002710 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002711 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002712 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002713 goto afp_end_lock;
2714 }
2715 }
2716
2717 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002718 ** operating system calls for the specified lock.
2719 */
drh308c2a52010-05-14 11:30:18 +00002720 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002721 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002722 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002723
drh8af6c222010-05-14 12:43:01 +00002724 assert( pInode->nShared==0 );
2725 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002726
2727 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002728 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002729 /* note that the quality of the randomness doesn't matter that much */
2730 lk = random();
drh8af6c222010-05-14 12:43:01 +00002731 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002732 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002733 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002734 if( IS_LOCK_ERROR(lrc1) ){
2735 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002736 }
aswift5b1a2562008-08-22 00:22:35 +00002737 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002738 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002739
aswift5b1a2562008-08-22 00:22:35 +00002740 if( IS_LOCK_ERROR(lrc1) ) {
2741 pFile->lastErrno = lrc1Errno;
2742 rc = lrc1;
2743 goto afp_end_lock;
2744 } else if( IS_LOCK_ERROR(lrc2) ){
2745 rc = lrc2;
2746 goto afp_end_lock;
2747 } else if( lrc1 != SQLITE_OK ) {
2748 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002749 } else {
drh308c2a52010-05-14 11:30:18 +00002750 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002751 pInode->nLock++;
2752 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002753 }
drh8af6c222010-05-14 12:43:01 +00002754 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002755 /* We are trying for an exclusive lock but another thread in this
2756 ** same process is still holding a shared lock. */
2757 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002758 }else{
2759 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2760 ** assumed that there is a SHARED or greater lock on the file
2761 ** already.
2762 */
2763 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002764 assert( 0!=pFile->eFileLock );
2765 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002766 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002767 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002768 if( !failed ){
2769 context->reserved = 1;
2770 }
drhbfe66312006-10-03 17:40:40 +00002771 }
drh308c2a52010-05-14 11:30:18 +00002772 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002773 /* Acquire an EXCLUSIVE lock */
2774
2775 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002776 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002777 */
drh6b9d6dd2008-12-03 19:34:47 +00002778 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002779 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002780 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002781 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002782 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002783 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002784 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002785 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002786 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2787 ** a critical I/O error
2788 */
2789 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2790 SQLITE_IOERR_LOCK;
2791 goto afp_end_lock;
2792 }
2793 }else{
aswift5b1a2562008-08-22 00:22:35 +00002794 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002795 }
2796 }
aswift5b1a2562008-08-22 00:22:35 +00002797 if( failed ){
2798 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002799 }
2800 }
2801
2802 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002803 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002804 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002805 }else if( eFileLock==EXCLUSIVE_LOCK ){
2806 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002807 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002808 }
2809
2810afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002811 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002812 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2813 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002814 return rc;
2815}
2816
2817/*
drh308c2a52010-05-14 11:30:18 +00002818** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002819** must be either NO_LOCK or SHARED_LOCK.
2820**
2821** If the locking level of the file descriptor is already at or below
2822** the requested locking level, this routine is a no-op.
2823*/
drh308c2a52010-05-14 11:30:18 +00002824static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002825 int rc = SQLITE_OK;
2826 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002827 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002828 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2829 int skipShared = 0;
2830#ifdef SQLITE_TEST
2831 int h = pFile->h;
2832#endif
drhbfe66312006-10-03 17:40:40 +00002833
2834 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002835 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002836 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002837 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002838
drh308c2a52010-05-14 11:30:18 +00002839 assert( eFileLock<=SHARED_LOCK );
2840 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002841 return SQLITE_OK;
2842 }
drh6c7d5c52008-11-21 20:32:33 +00002843 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002844 pInode = pFile->pInode;
2845 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002846 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002847 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002848 SimulateIOErrorBenign(1);
2849 SimulateIOError( h=(-1) )
2850 SimulateIOErrorBenign(0);
2851
drhd3d8c042012-05-29 17:02:40 +00002852#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002853 /* When reducing a lock such that other processes can start
2854 ** reading the database file again, make sure that the
2855 ** transaction counter was updated if any part of the database
2856 ** file changed. If the transaction counter is not updated,
2857 ** other connections to the same file might not realize that
2858 ** the file has changed and hence might not know to flush their
2859 ** cache. The use of a stale cache can lead to database corruption.
2860 */
2861 assert( pFile->inNormalWrite==0
2862 || pFile->dbUpdate==0
2863 || pFile->transCntrChng==1 );
2864 pFile->inNormalWrite = 0;
2865#endif
aswiftaebf4132008-11-21 00:10:35 +00002866
drh308c2a52010-05-14 11:30:18 +00002867 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002868 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002869 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002870 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002871 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002872 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2873 } else {
2874 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002875 }
2876 }
drh308c2a52010-05-14 11:30:18 +00002877 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002878 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002879 }
drh308c2a52010-05-14 11:30:18 +00002880 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002881 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2882 if( !rc ){
2883 context->reserved = 0;
2884 }
aswiftaebf4132008-11-21 00:10:35 +00002885 }
drh8af6c222010-05-14 12:43:01 +00002886 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2887 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002888 }
aswiftaebf4132008-11-21 00:10:35 +00002889 }
drh308c2a52010-05-14 11:30:18 +00002890 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002891
drh7ed97b92010-01-20 13:07:21 +00002892 /* Decrement the shared lock counter. Release the lock using an
2893 ** OS call only when all threads in this same process have released
2894 ** the lock.
2895 */
drh8af6c222010-05-14 12:43:01 +00002896 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2897 pInode->nShared--;
2898 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002899 SimulateIOErrorBenign(1);
2900 SimulateIOError( h=(-1) )
2901 SimulateIOErrorBenign(0);
2902 if( !skipShared ){
2903 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2904 }
2905 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002906 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002907 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002908 }
2909 }
2910 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002911 pInode->nLock--;
2912 assert( pInode->nLock>=0 );
2913 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002914 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002915 }
2916 }
drhbfe66312006-10-03 17:40:40 +00002917 }
drh7ed97b92010-01-20 13:07:21 +00002918
drh6c7d5c52008-11-21 20:32:33 +00002919 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002920 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002921 return rc;
2922}
2923
2924/*
drh339eb0b2008-03-07 15:34:11 +00002925** Close a file & cleanup AFP specific locking context
2926*/
danielk1977e339d652008-06-28 11:23:00 +00002927static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002928 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002929 if( id ){
2930 unixFile *pFile = (unixFile*)id;
2931 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002932 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002933 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002934 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002935 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002936 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002937 ** the last lock is cleared.
2938 */
dan08da86a2009-08-21 17:18:03 +00002939 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002940 }
danb0ac3e32010-06-16 10:55:42 +00002941 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002942 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002943 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002944 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002945 }
drh7ed97b92010-01-20 13:07:21 +00002946 return rc;
drhbfe66312006-10-03 17:40:40 +00002947}
2948
drhd2cb50b2009-01-09 21:41:17 +00002949#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002950/*
2951** The code above is the AFP lock implementation. The code is specific
2952** to MacOSX and does not work on other unix platforms. No alternative
2953** is available. If you don't compile for a mac, then the "unix-afp"
2954** VFS is not available.
2955**
2956********************* End of the AFP lock implementation **********************
2957******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002958
drh7ed97b92010-01-20 13:07:21 +00002959/******************************************************************************
2960*************************** Begin NFS Locking ********************************/
2961
2962#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2963/*
drh308c2a52010-05-14 11:30:18 +00002964 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002965 ** must be either NO_LOCK or SHARED_LOCK.
2966 **
2967 ** If the locking level of the file descriptor is already at or below
2968 ** the requested locking level, this routine is a no-op.
2969 */
drh308c2a52010-05-14 11:30:18 +00002970static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002971 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002972}
2973
2974#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2975/*
2976** The code above is the NFS lock implementation. The code is specific
2977** to MacOSX and does not work on other unix platforms. No alternative
2978** is available.
2979**
2980********************* End of the NFS lock implementation **********************
2981******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002982
2983/******************************************************************************
2984**************** Non-locking sqlite3_file methods *****************************
2985**
2986** The next division contains implementations for all methods of the
2987** sqlite3_file object other than the locking methods. The locking
2988** methods were defined in divisions above (one locking method per
2989** division). Those methods that are common to all locking modes
2990** are gather together into this division.
2991*/
drhbfe66312006-10-03 17:40:40 +00002992
2993/*
drh734c9862008-11-28 15:37:20 +00002994** Seek to the offset passed as the second argument, then read cnt
2995** bytes into pBuf. Return the number of bytes actually read.
2996**
2997** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2998** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2999** one system to another. Since SQLite does not define USE_PREAD
3000** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3001** See tickets #2741 and #2681.
3002**
3003** To avoid stomping the errno value on a failed read the lastErrno value
3004** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003005*/
drh734c9862008-11-28 15:37:20 +00003006static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3007 int got;
drh58024642011-11-07 18:16:00 +00003008 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003009#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003010 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003011#endif
drh734c9862008-11-28 15:37:20 +00003012 TIMER_START;
drh58024642011-11-07 18:16:00 +00003013 do{
drh734c9862008-11-28 15:37:20 +00003014#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003015 got = osPread(id->h, pBuf, cnt, offset);
3016 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003017#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003018 got = osPread64(id->h, pBuf, cnt, offset);
3019 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003020#else
drh58024642011-11-07 18:16:00 +00003021 newOffset = lseek(id->h, offset, SEEK_SET);
3022 SimulateIOError( newOffset-- );
3023 if( newOffset!=offset ){
3024 if( newOffset == -1 ){
3025 ((unixFile*)id)->lastErrno = errno;
3026 }else{
drhf2f105d2012-08-20 15:53:54 +00003027 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003028 }
3029 return -1;
drh734c9862008-11-28 15:37:20 +00003030 }
drh58024642011-11-07 18:16:00 +00003031 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003032#endif
drh58024642011-11-07 18:16:00 +00003033 if( got==cnt ) break;
3034 if( got<0 ){
3035 if( errno==EINTR ){ got = 1; continue; }
3036 prior = 0;
3037 ((unixFile*)id)->lastErrno = errno;
3038 break;
3039 }else if( got>0 ){
3040 cnt -= got;
3041 offset += got;
3042 prior += got;
3043 pBuf = (void*)(got + (char*)pBuf);
3044 }
3045 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003046 TIMER_END;
drh58024642011-11-07 18:16:00 +00003047 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3048 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3049 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003050}
3051
3052/*
drh734c9862008-11-28 15:37:20 +00003053** Read data from a file into a buffer. Return SQLITE_OK if all
3054** bytes were read successfully and SQLITE_IOERR if anything goes
3055** wrong.
drh339eb0b2008-03-07 15:34:11 +00003056*/
drh734c9862008-11-28 15:37:20 +00003057static int unixRead(
3058 sqlite3_file *id,
3059 void *pBuf,
3060 int amt,
3061 sqlite3_int64 offset
3062){
dan08da86a2009-08-21 17:18:03 +00003063 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003064 int got;
3065 assert( id );
drh08c6d442009-02-09 17:34:07 +00003066
dan08da86a2009-08-21 17:18:03 +00003067 /* If this is a database file (not a journal, master-journal or temp
3068 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003069#if 0
dane946c392009-08-22 11:39:46 +00003070 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003071 || offset>=PENDING_BYTE+512
3072 || offset+amt<=PENDING_BYTE
3073 );
dan7c246102010-04-12 19:00:29 +00003074#endif
drh08c6d442009-02-09 17:34:07 +00003075
dan08da86a2009-08-21 17:18:03 +00003076 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003077 if( got==amt ){
3078 return SQLITE_OK;
3079 }else if( got<0 ){
3080 /* lastErrno set by seekAndRead */
3081 return SQLITE_IOERR_READ;
3082 }else{
dan08da86a2009-08-21 17:18:03 +00003083 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003084 /* Unread parts of the buffer must be zero-filled */
3085 memset(&((char*)pBuf)[got], 0, amt-got);
3086 return SQLITE_IOERR_SHORT_READ;
3087 }
3088}
3089
3090/*
3091** Seek to the offset in id->offset then read cnt bytes into pBuf.
3092** Return the number of bytes actually read. Update the offset.
3093**
3094** To avoid stomping the errno value on a failed write the lastErrno value
3095** is set before returning.
3096*/
3097static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3098 int got;
drh7ed97b92010-01-20 13:07:21 +00003099#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003100 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003101#endif
drh734c9862008-11-28 15:37:20 +00003102 TIMER_START;
3103#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003104 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003105#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003106 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003107#else
drhbd1e50c2011-08-19 14:54:12 +00003108 do{
3109 newOffset = lseek(id->h, offset, SEEK_SET);
3110 SimulateIOError( newOffset-- );
3111 if( newOffset!=offset ){
3112 if( newOffset == -1 ){
3113 ((unixFile*)id)->lastErrno = errno;
3114 }else{
drhf2f105d2012-08-20 15:53:54 +00003115 ((unixFile*)id)->lastErrno = 0;
drhbd1e50c2011-08-19 14:54:12 +00003116 }
3117 return -1;
drh734c9862008-11-28 15:37:20 +00003118 }
drhbd1e50c2011-08-19 14:54:12 +00003119 got = osWrite(id->h, pBuf, cnt);
3120 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003121#endif
3122 TIMER_END;
3123 if( got<0 ){
3124 ((unixFile*)id)->lastErrno = errno;
3125 }
3126
drh308c2a52010-05-14 11:30:18 +00003127 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003128 return got;
3129}
3130
3131
3132/*
3133** Write data from a buffer into a file. Return SQLITE_OK on success
3134** or some other error code on failure.
3135*/
3136static int unixWrite(
3137 sqlite3_file *id,
3138 const void *pBuf,
3139 int amt,
3140 sqlite3_int64 offset
3141){
dan08da86a2009-08-21 17:18:03 +00003142 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003143 int wrote = 0;
3144 assert( id );
3145 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003146
dan08da86a2009-08-21 17:18:03 +00003147 /* If this is a database file (not a journal, master-journal or temp
3148 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003149#if 0
dane946c392009-08-22 11:39:46 +00003150 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003151 || offset>=PENDING_BYTE+512
3152 || offset+amt<=PENDING_BYTE
3153 );
dan7c246102010-04-12 19:00:29 +00003154#endif
drh08c6d442009-02-09 17:34:07 +00003155
drhd3d8c042012-05-29 17:02:40 +00003156#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003157 /* If we are doing a normal write to a database file (as opposed to
3158 ** doing a hot-journal rollback or a write to some file other than a
3159 ** normal database file) then record the fact that the database
3160 ** has changed. If the transaction counter is modified, record that
3161 ** fact too.
3162 */
dan08da86a2009-08-21 17:18:03 +00003163 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003164 pFile->dbUpdate = 1; /* The database has been modified */
3165 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003166 int rc;
drh8f941bc2009-01-14 23:03:40 +00003167 char oldCntr[4];
3168 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003169 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003170 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003171 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003172 pFile->transCntrChng = 1; /* The transaction counter has changed */
3173 }
3174 }
3175 }
3176#endif
3177
dan08da86a2009-08-21 17:18:03 +00003178 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003179 amt -= wrote;
3180 offset += wrote;
3181 pBuf = &((char*)pBuf)[wrote];
3182 }
3183 SimulateIOError(( wrote=(-1), amt=1 ));
3184 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003185
drh734c9862008-11-28 15:37:20 +00003186 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003187 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003188 /* lastErrno set by seekAndWrite */
3189 return SQLITE_IOERR_WRITE;
3190 }else{
dan08da86a2009-08-21 17:18:03 +00003191 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003192 return SQLITE_FULL;
3193 }
3194 }
dan6e09d692010-07-27 18:34:15 +00003195
drh734c9862008-11-28 15:37:20 +00003196 return SQLITE_OK;
3197}
3198
3199#ifdef SQLITE_TEST
3200/*
3201** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003202** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003203*/
3204int sqlite3_sync_count = 0;
3205int sqlite3_fullsync_count = 0;
3206#endif
3207
3208/*
drh89240432009-03-25 01:06:01 +00003209** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003210** Others do no. To be safe, we will stick with the (slightly slower)
3211** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003212** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003213*/
drh20f8e132011-08-31 21:01:55 +00003214#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003215# define fdatasync fsync
3216#endif
3217
3218/*
3219** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3220** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3221** only available on Mac OS X. But that could change.
3222*/
3223#ifdef F_FULLFSYNC
3224# define HAVE_FULLFSYNC 1
3225#else
3226# define HAVE_FULLFSYNC 0
3227#endif
3228
3229
3230/*
3231** The fsync() system call does not work as advertised on many
3232** unix systems. The following procedure is an attempt to make
3233** it work better.
3234**
3235** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3236** for testing when we want to run through the test suite quickly.
3237** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3238** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3239** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003240**
3241** SQLite sets the dataOnly flag if the size of the file is unchanged.
3242** The idea behind dataOnly is that it should only write the file content
3243** to disk, not the inode. We only set dataOnly if the file size is
3244** unchanged since the file size is part of the inode. However,
3245** Ted Ts'o tells us that fdatasync() will also write the inode if the
3246** file size has changed. The only real difference between fdatasync()
3247** and fsync(), Ted tells us, is that fdatasync() will not flush the
3248** inode if the mtime or owner or other inode attributes have changed.
3249** We only care about the file size, not the other file attributes, so
3250** as far as SQLite is concerned, an fdatasync() is always adequate.
3251** So, we always use fdatasync() if it is available, regardless of
3252** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003253*/
3254static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003255 int rc;
drh734c9862008-11-28 15:37:20 +00003256
3257 /* The following "ifdef/elif/else/" block has the same structure as
3258 ** the one below. It is replicated here solely to avoid cluttering
3259 ** up the real code with the UNUSED_PARAMETER() macros.
3260 */
3261#ifdef SQLITE_NO_SYNC
3262 UNUSED_PARAMETER(fd);
3263 UNUSED_PARAMETER(fullSync);
3264 UNUSED_PARAMETER(dataOnly);
3265#elif HAVE_FULLFSYNC
3266 UNUSED_PARAMETER(dataOnly);
3267#else
3268 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003269 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003270#endif
3271
3272 /* Record the number of times that we do a normal fsync() and
3273 ** FULLSYNC. This is used during testing to verify that this procedure
3274 ** gets called with the correct arguments.
3275 */
3276#ifdef SQLITE_TEST
3277 if( fullSync ) sqlite3_fullsync_count++;
3278 sqlite3_sync_count++;
3279#endif
3280
3281 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3282 ** no-op
3283 */
3284#ifdef SQLITE_NO_SYNC
3285 rc = SQLITE_OK;
3286#elif HAVE_FULLFSYNC
3287 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003288 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003289 }else{
3290 rc = 1;
3291 }
3292 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003293 ** It shouldn't be possible for fullfsync to fail on the local
3294 ** file system (on OSX), so failure indicates that FULLFSYNC
3295 ** isn't supported for this file system. So, attempt an fsync
3296 ** and (for now) ignore the overhead of a superfluous fcntl call.
3297 ** It'd be better to detect fullfsync support once and avoid
3298 ** the fcntl call every time sync is called.
3299 */
drh734c9862008-11-28 15:37:20 +00003300 if( rc ) rc = fsync(fd);
3301
drh7ed97b92010-01-20 13:07:21 +00003302#elif defined(__APPLE__)
3303 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3304 ** so currently we default to the macro that redefines fdatasync to fsync
3305 */
3306 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003307#else
drh0b647ff2009-03-21 14:41:04 +00003308 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003309#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003310 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003311 rc = fsync(fd);
3312 }
drh0b647ff2009-03-21 14:41:04 +00003313#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003314#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3315
3316 if( OS_VXWORKS && rc!= -1 ){
3317 rc = 0;
3318 }
chw97185482008-11-17 08:05:31 +00003319 return rc;
drhbfe66312006-10-03 17:40:40 +00003320}
3321
drh734c9862008-11-28 15:37:20 +00003322/*
drh0059eae2011-08-08 23:48:40 +00003323** Open a file descriptor to the directory containing file zFilename.
3324** If successful, *pFd is set to the opened file descriptor and
3325** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3326** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3327** value.
3328**
drh90315a22011-08-10 01:52:12 +00003329** The directory file descriptor is used for only one thing - to
3330** fsync() a directory to make sure file creation and deletion events
3331** are flushed to disk. Such fsyncs are not needed on newer
3332** journaling filesystems, but are required on older filesystems.
3333**
3334** This routine can be overridden using the xSetSysCall interface.
3335** The ability to override this routine was added in support of the
3336** chromium sandbox. Opening a directory is a security risk (we are
3337** told) so making it overrideable allows the chromium sandbox to
3338** replace this routine with a harmless no-op. To make this routine
3339** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3340** *pFd set to a negative number.
3341**
drh0059eae2011-08-08 23:48:40 +00003342** If SQLITE_OK is returned, the caller is responsible for closing
3343** the file descriptor *pFd using close().
3344*/
3345static int openDirectory(const char *zFilename, int *pFd){
3346 int ii;
3347 int fd = -1;
3348 char zDirname[MAX_PATHNAME+1];
3349
3350 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3351 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3352 if( ii>0 ){
3353 zDirname[ii] = '\0';
3354 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3355 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003356 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3357 }
3358 }
3359 *pFd = fd;
3360 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3361}
3362
3363/*
drh734c9862008-11-28 15:37:20 +00003364** Make sure all writes to a particular file are committed to disk.
3365**
3366** If dataOnly==0 then both the file itself and its metadata (file
3367** size, access time, etc) are synced. If dataOnly!=0 then only the
3368** file data is synced.
3369**
3370** Under Unix, also make sure that the directory entry for the file
3371** has been created by fsync-ing the directory that contains the file.
3372** If we do not do this and we encounter a power failure, the directory
3373** entry for the journal might not exist after we reboot. The next
3374** SQLite to access the file will not know that the journal exists (because
3375** the directory entry for the journal was never created) and the transaction
3376** will not roll back - possibly leading to database corruption.
3377*/
3378static int unixSync(sqlite3_file *id, int flags){
3379 int rc;
3380 unixFile *pFile = (unixFile*)id;
3381
3382 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3383 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3384
3385 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3386 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3387 || (flags&0x0F)==SQLITE_SYNC_FULL
3388 );
3389
3390 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3391 ** line is to test that doing so does not cause any problems.
3392 */
3393 SimulateDiskfullError( return SQLITE_FULL );
3394
3395 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003396 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003397 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3398 SimulateIOError( rc=1 );
3399 if( rc ){
3400 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003401 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003402 }
drh0059eae2011-08-08 23:48:40 +00003403
3404 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003405 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3406 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003407 */
3408 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3409 int dirfd;
3410 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003411 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003412 rc = osOpenDirectory(pFile->zPath, &dirfd);
3413 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003414 full_fsync(dirfd, 0, 0);
3415 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003416 }else if( rc==SQLITE_CANTOPEN ){
3417 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003418 }
drh0059eae2011-08-08 23:48:40 +00003419 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003420 }
3421 return rc;
3422}
3423
3424/*
3425** Truncate an open file to a specified size
3426*/
3427static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003428 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003429 int rc;
dan6e09d692010-07-27 18:34:15 +00003430 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003431 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003432
3433 /* If the user has configured a chunk-size for this file, truncate the
3434 ** file so that it consists of an integer number of chunks (i.e. the
3435 ** actual file size after the operation may be larger than the requested
3436 ** size).
3437 */
drhb8af4b72012-04-05 20:04:39 +00003438 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003439 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3440 }
3441
drhff812312011-02-23 13:33:46 +00003442 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003443 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003444 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003445 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003446 }else{
drhd3d8c042012-05-29 17:02:40 +00003447#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003448 /* If we are doing a normal write to a database file (as opposed to
3449 ** doing a hot-journal rollback or a write to some file other than a
3450 ** normal database file) and we truncate the file to zero length,
3451 ** that effectively updates the change counter. This might happen
3452 ** when restoring a database using the backup API from a zero-length
3453 ** source.
3454 */
dan6e09d692010-07-27 18:34:15 +00003455 if( pFile->inNormalWrite && nByte==0 ){
3456 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003457 }
3458#endif
3459
drh734c9862008-11-28 15:37:20 +00003460 return SQLITE_OK;
3461 }
3462}
3463
3464/*
3465** Determine the current size of a file in bytes
3466*/
3467static int unixFileSize(sqlite3_file *id, i64 *pSize){
3468 int rc;
3469 struct stat buf;
3470 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003471 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003472 SimulateIOError( rc=1 );
3473 if( rc!=0 ){
3474 ((unixFile*)id)->lastErrno = errno;
3475 return SQLITE_IOERR_FSTAT;
3476 }
3477 *pSize = buf.st_size;
3478
drh8af6c222010-05-14 12:43:01 +00003479 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003480 ** writes a single byte into that file in order to work around a bug
3481 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3482 ** layers, we need to report this file size as zero even though it is
3483 ** really 1. Ticket #3260.
3484 */
3485 if( *pSize==1 ) *pSize = 0;
3486
3487
3488 return SQLITE_OK;
3489}
3490
drhd2cb50b2009-01-09 21:41:17 +00003491#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003492/*
3493** Handler for proxy-locking file-control verbs. Defined below in the
3494** proxying locking division.
3495*/
3496static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003497#endif
drh715ff302008-12-03 22:32:44 +00003498
dan502019c2010-07-28 14:26:17 +00003499/*
3500** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003501** file-control operation. Enlarge the database to nBytes in size
3502** (rounded up to the next chunk-size). If the database is already
3503** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003504*/
3505static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003506 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003507 i64 nSize; /* Required file size */
3508 struct stat buf; /* Used to hold return values of fstat() */
3509
drh99ab3b12011-03-02 15:09:07 +00003510 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003511
3512 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3513 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003514
dan502019c2010-07-28 14:26:17 +00003515#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003516 /* The code below is handling the return value of osFallocate()
3517 ** correctly. posix_fallocate() is defined to "returns zero on success,
3518 ** or an error number on failure". See the manpage for details. */
3519 int err;
drhff812312011-02-23 13:33:46 +00003520 do{
dan661d71a2011-03-30 19:08:03 +00003521 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3522 }while( err==EINTR );
3523 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003524#else
3525 /* If the OS does not have posix_fallocate(), fake it. First use
3526 ** ftruncate() to set the file size, then write a single byte to
3527 ** the last byte in each block within the extended region. This
3528 ** is the same technique used by glibc to implement posix_fallocate()
3529 ** on systems that do not have a real fallocate() system call.
3530 */
3531 int nBlk = buf.st_blksize; /* File-system block size */
3532 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003533
drhff812312011-02-23 13:33:46 +00003534 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003535 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003536 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003537 }
3538 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003539 while( iWrite<nSize ){
3540 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3541 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003542 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003543 }
dan502019c2010-07-28 14:26:17 +00003544#endif
3545 }
3546 }
3547
3548 return SQLITE_OK;
3549}
danielk1977ad94b582007-08-20 06:44:22 +00003550
danielk1977e3026632004-06-22 11:29:02 +00003551/*
drhf12b3f62011-12-21 14:42:29 +00003552** If *pArg is inititially negative then this is a query. Set *pArg to
3553** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3554**
3555** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3556*/
3557static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3558 if( *pArg<0 ){
3559 *pArg = (pFile->ctrlFlags & mask)!=0;
3560 }else if( (*pArg)==0 ){
3561 pFile->ctrlFlags &= ~mask;
3562 }else{
3563 pFile->ctrlFlags |= mask;
3564 }
3565}
3566
3567/*
drh9e33c2c2007-08-31 18:34:59 +00003568** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003569*/
drhcc6bb3e2007-08-31 16:11:35 +00003570static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003571 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003572 switch( op ){
3573 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003574 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003575 return SQLITE_OK;
3576 }
drh7708e972008-11-29 00:56:52 +00003577 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003578 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003579 return SQLITE_OK;
3580 }
dan6e09d692010-07-27 18:34:15 +00003581 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003582 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003583 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003584 }
drh9ff27ec2010-05-19 19:26:05 +00003585 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003586 int rc;
3587 SimulateIOErrorBenign(1);
3588 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3589 SimulateIOErrorBenign(0);
3590 return rc;
drhf0b190d2011-07-26 16:03:07 +00003591 }
3592 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003593 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3594 return SQLITE_OK;
3595 }
drhcb15f352011-12-23 01:04:17 +00003596 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3597 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003598 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003599 }
drhde60fc22011-12-14 17:53:36 +00003600 case SQLITE_FCNTL_VFSNAME: {
3601 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3602 return SQLITE_OK;
3603 }
drhd3d8c042012-05-29 17:02:40 +00003604#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003605 /* The pager calls this method to signal that it has done
3606 ** a rollback and that the database is therefore unchanged and
3607 ** it hence it is OK for the transaction change counter to be
3608 ** unchanged.
3609 */
3610 case SQLITE_FCNTL_DB_UNCHANGED: {
3611 ((unixFile*)id)->dbUpdate = 0;
3612 return SQLITE_OK;
3613 }
3614#endif
drhd2cb50b2009-01-09 21:41:17 +00003615#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003616 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003617 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003618 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003619 }
drhd2cb50b2009-01-09 21:41:17 +00003620#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003621 }
drh0b52b7d2011-01-26 19:46:22 +00003622 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003623}
3624
3625/*
danielk1977a3d4c882007-03-23 10:08:38 +00003626** Return the sector size in bytes of the underlying block device for
3627** the specified file. This is almost always 512 bytes, but may be
3628** larger for some devices.
3629**
3630** SQLite code assumes this function cannot fail. It also assumes that
3631** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003632** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003633** same for both.
3634*/
drh1da88f02011-12-17 16:09:16 +00003635static int unixSectorSize(sqlite3_file *pFile){
drh8942d412012-01-02 18:20:14 +00003636 (void)pFile;
3637 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003638}
3639
danielk197790949c22007-08-17 16:50:38 +00003640/*
drhf12b3f62011-12-21 14:42:29 +00003641** Return the device characteristics for the file.
3642**
drhcb15f352011-12-23 01:04:17 +00003643** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3644** However, that choice is contraversial since technically the underlying
3645** file system does not always provide powersafe overwrites. (In other
3646** words, after a power-loss event, parts of the file that were never
3647** written might end up being altered.) However, non-PSOW behavior is very,
3648** very rare. And asserting PSOW makes a large reduction in the amount
3649** of required I/O for journaling, since a lot of padding is eliminated.
3650** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3651** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003652*/
drhf12b3f62011-12-21 14:42:29 +00003653static int unixDeviceCharacteristics(sqlite3_file *id){
3654 unixFile *p = (unixFile*)id;
drhcb15f352011-12-23 01:04:17 +00003655 if( p->ctrlFlags & UNIXFILE_PSOW ){
3656 return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3657 }else{
3658 return 0;
3659 }
danielk197762079062007-08-15 17:08:46 +00003660}
3661
drhd9e5c4f2010-05-12 18:01:39 +00003662#ifndef SQLITE_OMIT_WAL
3663
3664
3665/*
drhd91c68f2010-05-14 14:52:25 +00003666** Object used to represent an shared memory buffer.
3667**
3668** When multiple threads all reference the same wal-index, each thread
3669** has its own unixShm object, but they all point to a single instance
3670** of this unixShmNode object. In other words, each wal-index is opened
3671** only once per process.
3672**
3673** Each unixShmNode object is connected to a single unixInodeInfo object.
3674** We could coalesce this object into unixInodeInfo, but that would mean
3675** every open file that does not use shared memory (in other words, most
3676** open files) would have to carry around this extra information. So
3677** the unixInodeInfo object contains a pointer to this unixShmNode object
3678** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003679**
3680** unixMutexHeld() must be true when creating or destroying
3681** this object or while reading or writing the following fields:
3682**
3683** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003684**
3685** The following fields are read-only after the object is created:
3686**
3687** fid
3688** zFilename
3689**
drhd91c68f2010-05-14 14:52:25 +00003690** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003691** unixMutexHeld() is true when reading or writing any other field
3692** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003693*/
drhd91c68f2010-05-14 14:52:25 +00003694struct unixShmNode {
3695 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003696 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003697 char *zFilename; /* Name of the mmapped file */
3698 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003699 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003700 u16 nRegion; /* Size of array apRegion */
3701 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003702 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003703 int nRef; /* Number of unixShm objects pointing to this */
3704 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003705#ifdef SQLITE_DEBUG
3706 u8 exclMask; /* Mask of exclusive locks held */
3707 u8 sharedMask; /* Mask of shared locks held */
3708 u8 nextShmId; /* Next available unixShm.id value */
3709#endif
3710};
3711
3712/*
drhd9e5c4f2010-05-12 18:01:39 +00003713** Structure used internally by this VFS to record the state of an
3714** open shared memory connection.
3715**
drhd91c68f2010-05-14 14:52:25 +00003716** The following fields are initialized when this object is created and
3717** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003718**
drhd91c68f2010-05-14 14:52:25 +00003719** unixShm.pFile
3720** unixShm.id
3721**
3722** All other fields are read/write. The unixShm.pFile->mutex must be held
3723** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003724*/
3725struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003726 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3727 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003728 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003729 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003730 u16 sharedMask; /* Mask of shared locks held */
3731 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003732};
3733
3734/*
drhd9e5c4f2010-05-12 18:01:39 +00003735** Constants used for locking
3736*/
drhbd9676c2010-06-23 17:58:38 +00003737#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003738#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003739
drhd9e5c4f2010-05-12 18:01:39 +00003740/*
drh73b64e42010-05-30 19:55:15 +00003741** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003742**
3743** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3744** otherwise.
3745*/
3746static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003747 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3748 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003749 int ofst, /* First byte of the locking range */
3750 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003751){
3752 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003753 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003754
drhd91c68f2010-05-14 14:52:25 +00003755 /* Access to the unixShmNode object is serialized by the caller */
3756 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003757
drh73b64e42010-05-30 19:55:15 +00003758 /* Shared locks never span more than one byte */
3759 assert( n==1 || lockType!=F_RDLCK );
3760
3761 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003762 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003763
drh3cb93392011-03-12 18:10:44 +00003764 if( pShmNode->h>=0 ){
3765 /* Initialize the locking parameters */
3766 memset(&f, 0, sizeof(f));
3767 f.l_type = lockType;
3768 f.l_whence = SEEK_SET;
3769 f.l_start = ofst;
3770 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003771
drh3cb93392011-03-12 18:10:44 +00003772 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3773 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3774 }
drhd9e5c4f2010-05-12 18:01:39 +00003775
3776 /* Update the global lock state and do debug tracing */
3777#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003778 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003779 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003780 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003781 if( rc==SQLITE_OK ){
3782 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003783 OSTRACE(("unlock %d ok", ofst));
3784 pShmNode->exclMask &= ~mask;
3785 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003786 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003787 OSTRACE(("read-lock %d ok", ofst));
3788 pShmNode->exclMask &= ~mask;
3789 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003790 }else{
3791 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003792 OSTRACE(("write-lock %d ok", ofst));
3793 pShmNode->exclMask |= mask;
3794 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003795 }
3796 }else{
3797 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003798 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003799 }else if( lockType==F_RDLCK ){
3800 OSTRACE(("read-lock failed"));
3801 }else{
3802 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003803 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003804 }
3805 }
drh20e1f082010-05-31 16:10:12 +00003806 OSTRACE((" - afterwards %03x,%03x\n",
3807 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003808 }
drhd9e5c4f2010-05-12 18:01:39 +00003809#endif
3810
3811 return rc;
3812}
3813
drhd9e5c4f2010-05-12 18:01:39 +00003814
3815/*
drhd91c68f2010-05-14 14:52:25 +00003816** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003817**
3818** This is not a VFS shared-memory method; it is a utility function called
3819** by VFS shared-memory methods.
3820*/
drhd91c68f2010-05-14 14:52:25 +00003821static void unixShmPurge(unixFile *pFd){
3822 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003823 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003824 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003825 int i;
drhd91c68f2010-05-14 14:52:25 +00003826 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003827 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003828 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003829 if( p->h>=0 ){
3830 munmap(p->apRegion[i], p->szRegion);
3831 }else{
3832 sqlite3_free(p->apRegion[i]);
3833 }
dan13a3cb82010-06-11 19:04:21 +00003834 }
dan18801912010-06-14 14:07:50 +00003835 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003836 if( p->h>=0 ){
3837 robust_close(pFd, p->h, __LINE__);
3838 p->h = -1;
3839 }
drhd91c68f2010-05-14 14:52:25 +00003840 p->pInode->pShmNode = 0;
3841 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003842 }
3843}
3844
3845/*
danda9fe0c2010-07-13 18:44:03 +00003846** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003847** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003848**
drh7234c6d2010-06-19 15:10:09 +00003849** The file used to implement shared-memory is in the same directory
3850** as the open database file and has the same name as the open database
3851** file with the "-shm" suffix added. For example, if the database file
3852** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003853** for shared memory will be called "/home/user1/config.db-shm".
3854**
3855** Another approach to is to use files in /dev/shm or /dev/tmp or an
3856** some other tmpfs mount. But if a file in a different directory
3857** from the database file is used, then differing access permissions
3858** or a chroot() might cause two different processes on the same
3859** database to end up using different files for shared memory -
3860** meaning that their memory would not really be shared - resulting
3861** in database corruption. Nevertheless, this tmpfs file usage
3862** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3863** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3864** option results in an incompatible build of SQLite; builds of SQLite
3865** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3866** same database file at the same time, database corruption will likely
3867** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3868** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003869**
3870** When opening a new shared-memory file, if no other instances of that
3871** file are currently open, in this process or in other processes, then
3872** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003873**
3874** If the original database file (pDbFd) is using the "unix-excl" VFS
3875** that means that an exclusive lock is held on the database file and
3876** that no other processes are able to read or write the database. In
3877** that case, we do not really need shared memory. No shared memory
3878** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003879*/
danda9fe0c2010-07-13 18:44:03 +00003880static int unixOpenSharedMemory(unixFile *pDbFd){
3881 struct unixShm *p = 0; /* The connection to be opened */
3882 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3883 int rc; /* Result code */
3884 unixInodeInfo *pInode; /* The inode of fd */
3885 char *zShmFilename; /* Name of the file used for SHM */
3886 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003887
danda9fe0c2010-07-13 18:44:03 +00003888 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003889 p = sqlite3_malloc( sizeof(*p) );
3890 if( p==0 ) return SQLITE_NOMEM;
3891 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003892 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003893
danda9fe0c2010-07-13 18:44:03 +00003894 /* Check to see if a unixShmNode object already exists. Reuse an existing
3895 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003896 */
3897 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003898 pInode = pDbFd->pInode;
3899 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003900 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003901 struct stat sStat; /* fstat() info for database file */
3902
3903 /* Call fstat() to figure out the permissions on the database file. If
3904 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00003905 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00003906 */
drh3cb93392011-03-12 18:10:44 +00003907 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003908 rc = SQLITE_IOERR_FSTAT;
3909 goto shm_open_err;
3910 }
3911
drha4ced192010-07-15 18:32:40 +00003912#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00003913 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00003914#else
drh52bcde02012-01-03 14:50:45 +00003915 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003916#endif
drh7234c6d2010-06-19 15:10:09 +00003917 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003918 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003919 rc = SQLITE_NOMEM;
3920 goto shm_open_err;
3921 }
drh9cb5a0d2012-01-05 21:19:54 +00003922 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00003923 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003924#ifdef SQLITE_SHM_DIRECTORY
3925 sqlite3_snprintf(nShmFilename, zShmFilename,
3926 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3927 (u32)sStat.st_ino, (u32)sStat.st_dev);
3928#else
drh7234c6d2010-06-19 15:10:09 +00003929 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003930 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003931#endif
drhd91c68f2010-05-14 14:52:25 +00003932 pShmNode->h = -1;
3933 pDbFd->pInode->pShmNode = pShmNode;
3934 pShmNode->pInode = pDbFd->pInode;
3935 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3936 if( pShmNode->mutex==0 ){
3937 rc = SQLITE_NOMEM;
3938 goto shm_open_err;
3939 }
drhd9e5c4f2010-05-12 18:01:39 +00003940
drh3cb93392011-03-12 18:10:44 +00003941 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003942 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003943 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003944 openFlags = O_RDONLY;
3945 pShmNode->isReadonly = 1;
3946 }
3947 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003948 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00003949 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3950 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003951 }
drhac7c3ac2012-02-11 19:23:48 +00003952
3953 /* If this process is running as root, make sure that the SHM file
3954 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00003955 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00003956 */
drhed466822012-05-31 13:10:49 +00003957 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00003958
3959 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003960 ** If not, truncate the file to zero length.
3961 */
3962 rc = SQLITE_OK;
3963 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3964 if( robust_ftruncate(pShmNode->h, 0) ){
3965 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003966 }
3967 }
drh66dfec8b2011-06-01 20:01:49 +00003968 if( rc==SQLITE_OK ){
3969 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3970 }
3971 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003972 }
drhd9e5c4f2010-05-12 18:01:39 +00003973 }
3974
drhd91c68f2010-05-14 14:52:25 +00003975 /* Make the new connection a child of the unixShmNode */
3976 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003977#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003978 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003979#endif
drhd91c68f2010-05-14 14:52:25 +00003980 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003981 pDbFd->pShm = p;
3982 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003983
3984 /* The reference count on pShmNode has already been incremented under
3985 ** the cover of the unixEnterMutex() mutex and the pointer from the
3986 ** new (struct unixShm) object to the pShmNode has been set. All that is
3987 ** left to do is to link the new object into the linked list starting
3988 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3989 ** mutex.
3990 */
3991 sqlite3_mutex_enter(pShmNode->mutex);
3992 p->pNext = pShmNode->pFirst;
3993 pShmNode->pFirst = p;
3994 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003995 return SQLITE_OK;
3996
3997 /* Jump here on any error */
3998shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003999 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004000 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004001 unixLeaveMutex();
4002 return rc;
4003}
4004
4005/*
danda9fe0c2010-07-13 18:44:03 +00004006** This function is called to obtain a pointer to region iRegion of the
4007** shared-memory associated with the database file fd. Shared-memory regions
4008** are numbered starting from zero. Each shared-memory region is szRegion
4009** bytes in size.
4010**
4011** If an error occurs, an error code is returned and *pp is set to NULL.
4012**
4013** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4014** region has not been allocated (by any client, including one running in a
4015** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4016** bExtend is non-zero and the requested shared-memory region has not yet
4017** been allocated, it is allocated by this function.
4018**
4019** If the shared-memory region has already been allocated or is allocated by
4020** this call as described above, then it is mapped into this processes
4021** address space (if it is not already), *pp is set to point to the mapped
4022** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004023*/
danda9fe0c2010-07-13 18:44:03 +00004024static int unixShmMap(
4025 sqlite3_file *fd, /* Handle open on database file */
4026 int iRegion, /* Region to retrieve */
4027 int szRegion, /* Size of regions */
4028 int bExtend, /* True to extend file if necessary */
4029 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004030){
danda9fe0c2010-07-13 18:44:03 +00004031 unixFile *pDbFd = (unixFile*)fd;
4032 unixShm *p;
4033 unixShmNode *pShmNode;
4034 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004035
danda9fe0c2010-07-13 18:44:03 +00004036 /* If the shared-memory file has not yet been opened, open it now. */
4037 if( pDbFd->pShm==0 ){
4038 rc = unixOpenSharedMemory(pDbFd);
4039 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004040 }
drhd9e5c4f2010-05-12 18:01:39 +00004041
danda9fe0c2010-07-13 18:44:03 +00004042 p = pDbFd->pShm;
4043 pShmNode = p->pShmNode;
4044 sqlite3_mutex_enter(pShmNode->mutex);
4045 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004046 assert( pShmNode->pInode==pDbFd->pInode );
4047 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4048 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004049
4050 if( pShmNode->nRegion<=iRegion ){
4051 char **apNew; /* New apRegion[] array */
4052 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4053 struct stat sStat; /* Used by fstat() */
4054
4055 pShmNode->szRegion = szRegion;
4056
drh3cb93392011-03-12 18:10:44 +00004057 if( pShmNode->h>=0 ){
4058 /* The requested region is not mapped into this processes address space.
4059 ** Check to see if it has been allocated (i.e. if the wal-index file is
4060 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004061 */
drh3cb93392011-03-12 18:10:44 +00004062 if( osFstat(pShmNode->h, &sStat) ){
4063 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004064 goto shmpage_out;
4065 }
drh3cb93392011-03-12 18:10:44 +00004066
4067 if( sStat.st_size<nByte ){
4068 /* The requested memory region does not exist. If bExtend is set to
4069 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4070 **
4071 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4072 ** the requested memory region.
4073 */
4074 if( !bExtend ) goto shmpage_out;
4075 if( robust_ftruncate(pShmNode->h, nByte) ){
4076 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4077 pShmNode->zFilename);
4078 goto shmpage_out;
4079 }
4080 }
danda9fe0c2010-07-13 18:44:03 +00004081 }
4082
4083 /* Map the requested memory region into this processes address space. */
4084 apNew = (char **)sqlite3_realloc(
4085 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4086 );
4087 if( !apNew ){
4088 rc = SQLITE_IOERR_NOMEM;
4089 goto shmpage_out;
4090 }
4091 pShmNode->apRegion = apNew;
4092 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004093 void *pMem;
4094 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004095 pMem = mmap(0, szRegion,
4096 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004097 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4098 );
4099 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004100 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004101 goto shmpage_out;
4102 }
4103 }else{
4104 pMem = sqlite3_malloc(szRegion);
4105 if( pMem==0 ){
4106 rc = SQLITE_NOMEM;
4107 goto shmpage_out;
4108 }
4109 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004110 }
4111 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4112 pShmNode->nRegion++;
4113 }
4114 }
4115
4116shmpage_out:
4117 if( pShmNode->nRegion>iRegion ){
4118 *pp = pShmNode->apRegion[iRegion];
4119 }else{
4120 *pp = 0;
4121 }
drh66dfec8b2011-06-01 20:01:49 +00004122 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004123 sqlite3_mutex_leave(pShmNode->mutex);
4124 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004125}
4126
4127/*
drhd9e5c4f2010-05-12 18:01:39 +00004128** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004129**
4130** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4131** different here than in posix. In xShmLock(), one can go from unlocked
4132** to shared and back or from unlocked to exclusive and back. But one may
4133** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004134*/
4135static int unixShmLock(
4136 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004137 int ofst, /* First lock to acquire or release */
4138 int n, /* Number of locks to acquire or release */
4139 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004140){
drh73b64e42010-05-30 19:55:15 +00004141 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4142 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4143 unixShm *pX; /* For looping over all siblings */
4144 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4145 int rc = SQLITE_OK; /* Result code */
4146 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004147
drhd91c68f2010-05-14 14:52:25 +00004148 assert( pShmNode==pDbFd->pInode->pShmNode );
4149 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004150 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004151 assert( n>=1 );
4152 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4153 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4154 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4155 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4156 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004157 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4158 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004159
drhc99597c2010-05-31 01:41:15 +00004160 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004161 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004162 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004163 if( flags & SQLITE_SHM_UNLOCK ){
4164 u16 allMask = 0; /* Mask of locks held by siblings */
4165
4166 /* See if any siblings hold this same lock */
4167 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4168 if( pX==p ) continue;
4169 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4170 allMask |= pX->sharedMask;
4171 }
4172
4173 /* Unlock the system-level locks */
4174 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004175 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004176 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004177 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004178 }
drh73b64e42010-05-30 19:55:15 +00004179
4180 /* Undo the local locks */
4181 if( rc==SQLITE_OK ){
4182 p->exclMask &= ~mask;
4183 p->sharedMask &= ~mask;
4184 }
4185 }else if( flags & SQLITE_SHM_SHARED ){
4186 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4187
4188 /* Find out which shared locks are already held by sibling connections.
4189 ** If any sibling already holds an exclusive lock, go ahead and return
4190 ** SQLITE_BUSY.
4191 */
4192 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004193 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004194 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004195 break;
4196 }
4197 allShared |= pX->sharedMask;
4198 }
4199
4200 /* Get shared locks at the system level, if necessary */
4201 if( rc==SQLITE_OK ){
4202 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004203 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004204 }else{
drh73b64e42010-05-30 19:55:15 +00004205 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004206 }
drhd9e5c4f2010-05-12 18:01:39 +00004207 }
drh73b64e42010-05-30 19:55:15 +00004208
4209 /* Get the local shared locks */
4210 if( rc==SQLITE_OK ){
4211 p->sharedMask |= mask;
4212 }
4213 }else{
4214 /* Make sure no sibling connections hold locks that will block this
4215 ** lock. If any do, return SQLITE_BUSY right away.
4216 */
4217 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004218 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4219 rc = SQLITE_BUSY;
4220 break;
4221 }
4222 }
4223
4224 /* Get the exclusive locks at the system level. Then if successful
4225 ** also mark the local connection as being locked.
4226 */
4227 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004228 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004229 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004230 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004231 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004232 }
drhd9e5c4f2010-05-12 18:01:39 +00004233 }
4234 }
drhd91c68f2010-05-14 14:52:25 +00004235 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004236 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4237 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004238 return rc;
4239}
4240
drh286a2882010-05-20 23:51:06 +00004241/*
4242** Implement a memory barrier or memory fence on shared memory.
4243**
4244** All loads and stores begun before the barrier must complete before
4245** any load or store begun after the barrier.
4246*/
4247static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004248 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004249){
drhff828942010-06-26 21:34:06 +00004250 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004251 unixEnterMutex();
4252 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004253}
4254
dan18801912010-06-14 14:07:50 +00004255/*
danda9fe0c2010-07-13 18:44:03 +00004256** Close a connection to shared-memory. Delete the underlying
4257** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004258**
4259** If there is no shared memory associated with the connection then this
4260** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004261*/
danda9fe0c2010-07-13 18:44:03 +00004262static int unixShmUnmap(
4263 sqlite3_file *fd, /* The underlying database file */
4264 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004265){
danda9fe0c2010-07-13 18:44:03 +00004266 unixShm *p; /* The connection to be closed */
4267 unixShmNode *pShmNode; /* The underlying shared-memory file */
4268 unixShm **pp; /* For looping over sibling connections */
4269 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004270
danda9fe0c2010-07-13 18:44:03 +00004271 pDbFd = (unixFile*)fd;
4272 p = pDbFd->pShm;
4273 if( p==0 ) return SQLITE_OK;
4274 pShmNode = p->pShmNode;
4275
4276 assert( pShmNode==pDbFd->pInode->pShmNode );
4277 assert( pShmNode->pInode==pDbFd->pInode );
4278
4279 /* Remove connection p from the set of connections associated
4280 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004281 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004282 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4283 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004284
danda9fe0c2010-07-13 18:44:03 +00004285 /* Free the connection p */
4286 sqlite3_free(p);
4287 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004288 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004289
4290 /* If pShmNode->nRef has reached 0, then close the underlying
4291 ** shared-memory file, too */
4292 unixEnterMutex();
4293 assert( pShmNode->nRef>0 );
4294 pShmNode->nRef--;
4295 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004296 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004297 unixShmPurge(pDbFd);
4298 }
4299 unixLeaveMutex();
4300
4301 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004302}
drh286a2882010-05-20 23:51:06 +00004303
danda9fe0c2010-07-13 18:44:03 +00004304
drhd9e5c4f2010-05-12 18:01:39 +00004305#else
drh6b017cc2010-06-14 18:01:46 +00004306# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004307# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004308# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004309# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004310#endif /* #ifndef SQLITE_OMIT_WAL */
4311
drh734c9862008-11-28 15:37:20 +00004312/*
4313** Here ends the implementation of all sqlite3_file methods.
4314**
4315********************** End sqlite3_file Methods *******************************
4316******************************************************************************/
4317
4318/*
drh6b9d6dd2008-12-03 19:34:47 +00004319** This division contains definitions of sqlite3_io_methods objects that
4320** implement various file locking strategies. It also contains definitions
4321** of "finder" functions. A finder-function is used to locate the appropriate
4322** sqlite3_io_methods object for a particular database file. The pAppData
4323** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4324** the correct finder-function for that VFS.
4325**
4326** Most finder functions return a pointer to a fixed sqlite3_io_methods
4327** object. The only interesting finder-function is autolockIoFinder, which
4328** looks at the filesystem type and tries to guess the best locking
4329** strategy from that.
4330**
drh1875f7a2008-12-08 18:19:17 +00004331** For finder-funtion F, two objects are created:
4332**
4333** (1) The real finder-function named "FImpt()".
4334**
dane946c392009-08-22 11:39:46 +00004335** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004336**
4337**
4338** A pointer to the F pointer is used as the pAppData value for VFS
4339** objects. We have to do this instead of letting pAppData point
4340** directly at the finder-function since C90 rules prevent a void*
4341** from be cast into a function pointer.
4342**
drh6b9d6dd2008-12-03 19:34:47 +00004343**
drh7708e972008-11-29 00:56:52 +00004344** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004345**
drh7708e972008-11-29 00:56:52 +00004346** * A constant sqlite3_io_methods object call METHOD that has locking
4347** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4348**
4349** * An I/O method finder function called FINDER that returns a pointer
4350** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004351*/
drhd9e5c4f2010-05-12 18:01:39 +00004352#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004353static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004354 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004355 CLOSE, /* xClose */ \
4356 unixRead, /* xRead */ \
4357 unixWrite, /* xWrite */ \
4358 unixTruncate, /* xTruncate */ \
4359 unixSync, /* xSync */ \
4360 unixFileSize, /* xFileSize */ \
4361 LOCK, /* xLock */ \
4362 UNLOCK, /* xUnlock */ \
4363 CKLOCK, /* xCheckReservedLock */ \
4364 unixFileControl, /* xFileControl */ \
4365 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004366 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004367 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004368 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004369 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004370 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004371}; \
drh0c2694b2009-09-03 16:23:44 +00004372static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4373 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004374 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004375} \
drh0c2694b2009-09-03 16:23:44 +00004376static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004377 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004378
4379/*
4380** Here are all of the sqlite3_io_methods objects for each of the
4381** locking strategies. Functions that return pointers to these methods
4382** are also created.
4383*/
4384IOMETHODS(
4385 posixIoFinder, /* Finder function name */
4386 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004387 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004388 unixClose, /* xClose method */
4389 unixLock, /* xLock method */
4390 unixUnlock, /* xUnlock method */
4391 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004392)
drh7708e972008-11-29 00:56:52 +00004393IOMETHODS(
4394 nolockIoFinder, /* Finder function name */
4395 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004396 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004397 nolockClose, /* xClose method */
4398 nolockLock, /* xLock method */
4399 nolockUnlock, /* xUnlock method */
4400 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004401)
drh7708e972008-11-29 00:56:52 +00004402IOMETHODS(
4403 dotlockIoFinder, /* Finder function name */
4404 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004405 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004406 dotlockClose, /* xClose method */
4407 dotlockLock, /* xLock method */
4408 dotlockUnlock, /* xUnlock method */
4409 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004410)
drh7708e972008-11-29 00:56:52 +00004411
chw78a13182009-04-07 05:35:03 +00004412#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004413IOMETHODS(
4414 flockIoFinder, /* Finder function name */
4415 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004416 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004417 flockClose, /* xClose method */
4418 flockLock, /* xLock method */
4419 flockUnlock, /* xUnlock method */
4420 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004421)
drh7708e972008-11-29 00:56:52 +00004422#endif
4423
drh6c7d5c52008-11-21 20:32:33 +00004424#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004425IOMETHODS(
4426 semIoFinder, /* Finder function name */
4427 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004428 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004429 semClose, /* xClose method */
4430 semLock, /* xLock method */
4431 semUnlock, /* xUnlock method */
4432 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004433)
aswiftaebf4132008-11-21 00:10:35 +00004434#endif
drh7708e972008-11-29 00:56:52 +00004435
drhd2cb50b2009-01-09 21:41:17 +00004436#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004437IOMETHODS(
4438 afpIoFinder, /* Finder function name */
4439 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004440 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004441 afpClose, /* xClose method */
4442 afpLock, /* xLock method */
4443 afpUnlock, /* xUnlock method */
4444 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004445)
drh715ff302008-12-03 22:32:44 +00004446#endif
4447
4448/*
4449** The proxy locking method is a "super-method" in the sense that it
4450** opens secondary file descriptors for the conch and lock files and
4451** it uses proxy, dot-file, AFP, and flock() locking methods on those
4452** secondary files. For this reason, the division that implements
4453** proxy locking is located much further down in the file. But we need
4454** to go ahead and define the sqlite3_io_methods and finder function
4455** for proxy locking here. So we forward declare the I/O methods.
4456*/
drhd2cb50b2009-01-09 21:41:17 +00004457#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004458static int proxyClose(sqlite3_file*);
4459static int proxyLock(sqlite3_file*, int);
4460static int proxyUnlock(sqlite3_file*, int);
4461static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004462IOMETHODS(
4463 proxyIoFinder, /* Finder function name */
4464 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004465 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004466 proxyClose, /* xClose method */
4467 proxyLock, /* xLock method */
4468 proxyUnlock, /* xUnlock method */
4469 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004470)
aswiftaebf4132008-11-21 00:10:35 +00004471#endif
drh7708e972008-11-29 00:56:52 +00004472
drh7ed97b92010-01-20 13:07:21 +00004473/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4474#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4475IOMETHODS(
4476 nfsIoFinder, /* Finder function name */
4477 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004478 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004479 unixClose, /* xClose method */
4480 unixLock, /* xLock method */
4481 nfsUnlock, /* xUnlock method */
4482 unixCheckReservedLock /* xCheckReservedLock method */
4483)
4484#endif
drh7708e972008-11-29 00:56:52 +00004485
drhd2cb50b2009-01-09 21:41:17 +00004486#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004487/*
drh6b9d6dd2008-12-03 19:34:47 +00004488** This "finder" function attempts to determine the best locking strategy
4489** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004490** object that implements that strategy.
4491**
4492** This is for MacOSX only.
4493*/
drh1875f7a2008-12-08 18:19:17 +00004494static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004495 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004496 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004497){
4498 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004499 const char *zFilesystem; /* Filesystem type name */
4500 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004501 } aMap[] = {
4502 { "hfs", &posixIoMethods },
4503 { "ufs", &posixIoMethods },
4504 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004505 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004506 { "webdav", &nolockIoMethods },
4507 { 0, 0 }
4508 };
4509 int i;
4510 struct statfs fsInfo;
4511 struct flock lockInfo;
4512
4513 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004514 /* If filePath==NULL that means we are dealing with a transient file
4515 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004516 return &nolockIoMethods;
4517 }
4518 if( statfs(filePath, &fsInfo) != -1 ){
4519 if( fsInfo.f_flags & MNT_RDONLY ){
4520 return &nolockIoMethods;
4521 }
4522 for(i=0; aMap[i].zFilesystem; i++){
4523 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4524 return aMap[i].pMethods;
4525 }
4526 }
4527 }
4528
4529 /* Default case. Handles, amongst others, "nfs".
4530 ** Test byte-range lock using fcntl(). If the call succeeds,
4531 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004532 */
drh7708e972008-11-29 00:56:52 +00004533 lockInfo.l_len = 1;
4534 lockInfo.l_start = 0;
4535 lockInfo.l_whence = SEEK_SET;
4536 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004537 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004538 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4539 return &nfsIoMethods;
4540 } else {
4541 return &posixIoMethods;
4542 }
drh7708e972008-11-29 00:56:52 +00004543 }else{
4544 return &dotlockIoMethods;
4545 }
4546}
drh0c2694b2009-09-03 16:23:44 +00004547static const sqlite3_io_methods
4548 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004549
drhd2cb50b2009-01-09 21:41:17 +00004550#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004551
chw78a13182009-04-07 05:35:03 +00004552#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4553/*
4554** This "finder" function attempts to determine the best locking strategy
4555** for the database file "filePath". It then returns the sqlite3_io_methods
4556** object that implements that strategy.
4557**
4558** This is for VXWorks only.
4559*/
4560static const sqlite3_io_methods *autolockIoFinderImpl(
4561 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004562 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004563){
4564 struct flock lockInfo;
4565
4566 if( !filePath ){
4567 /* If filePath==NULL that means we are dealing with a transient file
4568 ** that does not need to be locked. */
4569 return &nolockIoMethods;
4570 }
4571
4572 /* Test if fcntl() is supported and use POSIX style locks.
4573 ** Otherwise fall back to the named semaphore method.
4574 */
4575 lockInfo.l_len = 1;
4576 lockInfo.l_start = 0;
4577 lockInfo.l_whence = SEEK_SET;
4578 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004579 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004580 return &posixIoMethods;
4581 }else{
4582 return &semIoMethods;
4583 }
4584}
drh0c2694b2009-09-03 16:23:44 +00004585static const sqlite3_io_methods
4586 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004587
4588#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4589
drh7708e972008-11-29 00:56:52 +00004590/*
4591** An abstract type for a pointer to a IO method finder function:
4592*/
drh0c2694b2009-09-03 16:23:44 +00004593typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004594
aswiftaebf4132008-11-21 00:10:35 +00004595
drh734c9862008-11-28 15:37:20 +00004596/****************************************************************************
4597**************************** sqlite3_vfs methods ****************************
4598**
4599** This division contains the implementation of methods on the
4600** sqlite3_vfs object.
4601*/
4602
danielk1977a3d4c882007-03-23 10:08:38 +00004603/*
danielk1977e339d652008-06-28 11:23:00 +00004604** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004605*/
4606static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004607 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004608 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004609 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004610 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004611 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004612){
drh7708e972008-11-29 00:56:52 +00004613 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004614 unixFile *pNew = (unixFile *)pId;
4615 int rc = SQLITE_OK;
4616
drh8af6c222010-05-14 12:43:01 +00004617 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004618
dan00157392010-10-05 11:33:15 +00004619 /* Usually the path zFilename should not be a relative pathname. The
4620 ** exception is when opening the proxy "conch" file in builds that
4621 ** include the special Apple locking styles.
4622 */
dan00157392010-10-05 11:33:15 +00004623#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004624 assert( zFilename==0 || zFilename[0]=='/'
4625 || pVfs->pAppData==(void*)&autolockIoFinder );
4626#else
4627 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004628#endif
dan00157392010-10-05 11:33:15 +00004629
drhb07028f2011-10-14 21:49:18 +00004630 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004631 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004632
drh308c2a52010-05-14 11:30:18 +00004633 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004634 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004635 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004636 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004637 pNew->ctrlFlags = (u8)ctrlFlags;
4638 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4639 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004640 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004641 }
drha7e61d82011-03-12 17:02:57 +00004642 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004643 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004644 }
drh339eb0b2008-03-07 15:34:11 +00004645
drh6c7d5c52008-11-21 20:32:33 +00004646#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004647 pNew->pId = vxworksFindFileId(zFilename);
4648 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004649 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004650 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004651 }
4652#endif
4653
drhc02a43a2012-01-10 23:18:38 +00004654 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004655 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004656 }else{
drh0c2694b2009-09-03 16:23:44 +00004657 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004658#if SQLITE_ENABLE_LOCKING_STYLE
4659 /* Cache zFilename in the locking context (AFP and dotlock override) for
4660 ** proxyLock activation is possible (remote proxy is based on db name)
4661 ** zFilename remains valid until file is closed, to support */
4662 pNew->lockingContext = (void*)zFilename;
4663#endif
drhda0e7682008-07-30 15:27:54 +00004664 }
danielk1977e339d652008-06-28 11:23:00 +00004665
drh7ed97b92010-01-20 13:07:21 +00004666 if( pLockingStyle == &posixIoMethods
4667#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4668 || pLockingStyle == &nfsIoMethods
4669#endif
4670 ){
drh7708e972008-11-29 00:56:52 +00004671 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004672 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004673 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004674 /* If an error occured in findInodeInfo(), close the file descriptor
4675 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004676 ** in two scenarios:
4677 **
4678 ** (a) A call to fstat() failed.
4679 ** (b) A malloc failed.
4680 **
4681 ** Scenario (b) may only occur if the process is holding no other
4682 ** file descriptors open on the same file. If there were other file
4683 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004684 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004685 ** handle h - as it is guaranteed that no posix locks will be released
4686 ** by doing so.
4687 **
4688 ** If scenario (a) caused the error then things are not so safe. The
4689 ** implicit assumption here is that if fstat() fails, things are in
4690 ** such bad shape that dropping a lock or two doesn't matter much.
4691 */
drh0e9365c2011-03-02 02:08:13 +00004692 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004693 h = -1;
4694 }
drh7708e972008-11-29 00:56:52 +00004695 unixLeaveMutex();
4696 }
danielk1977e339d652008-06-28 11:23:00 +00004697
drhd2cb50b2009-01-09 21:41:17 +00004698#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004699 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004700 /* AFP locking uses the file path so it needs to be included in
4701 ** the afpLockingContext.
4702 */
4703 afpLockingContext *pCtx;
4704 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4705 if( pCtx==0 ){
4706 rc = SQLITE_NOMEM;
4707 }else{
4708 /* NB: zFilename exists and remains valid until the file is closed
4709 ** according to requirement F11141. So we do not need to make a
4710 ** copy of the filename. */
4711 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004712 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004713 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004714 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004715 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004716 if( rc!=SQLITE_OK ){
4717 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004718 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004719 h = -1;
4720 }
drh7708e972008-11-29 00:56:52 +00004721 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004722 }
drh7708e972008-11-29 00:56:52 +00004723 }
4724#endif
danielk1977e339d652008-06-28 11:23:00 +00004725
drh7708e972008-11-29 00:56:52 +00004726 else if( pLockingStyle == &dotlockIoMethods ){
4727 /* Dotfile locking uses the file path so it needs to be included in
4728 ** the dotlockLockingContext
4729 */
4730 char *zLockFile;
4731 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004732 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004733 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004734 zLockFile = (char *)sqlite3_malloc(nFilename);
4735 if( zLockFile==0 ){
4736 rc = SQLITE_NOMEM;
4737 }else{
4738 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004739 }
drh7708e972008-11-29 00:56:52 +00004740 pNew->lockingContext = zLockFile;
4741 }
danielk1977e339d652008-06-28 11:23:00 +00004742
drh6c7d5c52008-11-21 20:32:33 +00004743#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004744 else if( pLockingStyle == &semIoMethods ){
4745 /* Named semaphore locking uses the file path so it needs to be
4746 ** included in the semLockingContext
4747 */
4748 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004749 rc = findInodeInfo(pNew, &pNew->pInode);
4750 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4751 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004752 int n;
drh2238dcc2009-08-27 17:56:20 +00004753 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004754 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004755 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004756 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004757 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4758 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004759 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004760 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004761 }
chw97185482008-11-17 08:05:31 +00004762 }
drh7708e972008-11-29 00:56:52 +00004763 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004764 }
drh7708e972008-11-29 00:56:52 +00004765#endif
aswift5b1a2562008-08-22 00:22:35 +00004766
4767 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004768#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004769 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004770 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004771 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004772 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004773 isDelete = 0;
4774 }
drhc02a43a2012-01-10 23:18:38 +00004775 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004776#endif
danielk1977e339d652008-06-28 11:23:00 +00004777 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004778 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004779 }else{
drh7708e972008-11-29 00:56:52 +00004780 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004781 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004782 }
danielk1977e339d652008-06-28 11:23:00 +00004783 return rc;
drh054889e2005-11-30 03:20:31 +00004784}
drh9c06c952005-11-26 00:25:00 +00004785
danielk1977ad94b582007-08-20 06:44:22 +00004786/*
drh8b3cf822010-06-01 21:02:51 +00004787** Return the name of a directory in which to put temporary files.
4788** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004789*/
drh7234c6d2010-06-19 15:10:09 +00004790static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004791 static const char *azDirs[] = {
4792 0,
aswiftaebf4132008-11-21 00:10:35 +00004793 0,
danielk197717b90b52008-06-06 11:11:25 +00004794 "/var/tmp",
4795 "/usr/tmp",
4796 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004797 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004798 };
drh8b3cf822010-06-01 21:02:51 +00004799 unsigned int i;
4800 struct stat buf;
4801 const char *zDir = 0;
4802
4803 azDirs[0] = sqlite3_temp_directory;
4804 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004805 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004806 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004807 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004808 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004809 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004810 break;
4811 }
4812 return zDir;
4813}
4814
4815/*
4816** Create a temporary file name in zBuf. zBuf must be allocated
4817** by the calling process and must be big enough to hold at least
4818** pVfs->mxPathname bytes.
4819*/
4820static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004821 static const unsigned char zChars[] =
4822 "abcdefghijklmnopqrstuvwxyz"
4823 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4824 "0123456789";
drh41022642008-11-21 00:24:42 +00004825 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004826 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004827
4828 /* It's odd to simulate an io-error here, but really this is just
4829 ** using the io-error infrastructure to test that SQLite handles this
4830 ** function failing.
4831 */
4832 SimulateIOError( return SQLITE_IOERR );
4833
drh7234c6d2010-06-19 15:10:09 +00004834 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004835 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004836
4837 /* Check that the output buffer is large enough for the temporary file
4838 ** name. If it is not, return SQLITE_ERROR.
4839 */
drhc02a43a2012-01-10 23:18:38 +00004840 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004841 return SQLITE_ERROR;
4842 }
4843
4844 do{
drhc02a43a2012-01-10 23:18:38 +00004845 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004846 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004847 sqlite3_randomness(15, &zBuf[j]);
4848 for(i=0; i<15; i++, j++){
4849 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4850 }
4851 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00004852 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00004853 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004854 return SQLITE_OK;
4855}
4856
drhd2cb50b2009-01-09 21:41:17 +00004857#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004858/*
4859** Routine to transform a unixFile into a proxy-locking unixFile.
4860** Implementation in the proxy-lock division, but used by unixOpen()
4861** if SQLITE_PREFER_PROXY_LOCKING is defined.
4862*/
4863static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004864#endif
drhc66d5b62008-12-03 22:48:32 +00004865
dan08da86a2009-08-21 17:18:03 +00004866/*
4867** Search for an unused file descriptor that was opened on the database
4868** file (not a journal or master-journal file) identified by pathname
4869** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4870** argument to this function.
4871**
4872** Such a file descriptor may exist if a database connection was closed
4873** but the associated file descriptor could not be closed because some
4874** other file descriptor open on the same file is holding a file-lock.
4875** Refer to comments in the unixClose() function and the lengthy comment
4876** describing "Posix Advisory Locking" at the start of this file for
4877** further details. Also, ticket #4018.
4878**
4879** If a suitable file descriptor is found, then it is returned. If no
4880** such file descriptor is located, -1 is returned.
4881*/
dane946c392009-08-22 11:39:46 +00004882static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4883 UnixUnusedFd *pUnused = 0;
4884
4885 /* Do not search for an unused file descriptor on vxworks. Not because
4886 ** vxworks would not benefit from the change (it might, we're not sure),
4887 ** but because no way to test it is currently available. It is better
4888 ** not to risk breaking vxworks support for the sake of such an obscure
4889 ** feature. */
4890#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004891 struct stat sStat; /* Results of stat() call */
4892
4893 /* A stat() call may fail for various reasons. If this happens, it is
4894 ** almost certain that an open() call on the same path will also fail.
4895 ** For this reason, if an error occurs in the stat() call here, it is
4896 ** ignored and -1 is returned. The caller will try to open a new file
4897 ** descriptor on the same path, fail, and return an error to SQLite.
4898 **
4899 ** Even if a subsequent open() call does succeed, the consequences of
4900 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004901 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004902 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004903
4904 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004905 pInode = inodeList;
4906 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4907 || pInode->fileId.ino!=sStat.st_ino) ){
4908 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004909 }
drh8af6c222010-05-14 12:43:01 +00004910 if( pInode ){
dane946c392009-08-22 11:39:46 +00004911 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004912 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004913 pUnused = *pp;
4914 if( pUnused ){
4915 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004916 }
4917 }
4918 unixLeaveMutex();
4919 }
dane946c392009-08-22 11:39:46 +00004920#endif /* if !OS_VXWORKS */
4921 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004922}
danielk197717b90b52008-06-06 11:11:25 +00004923
4924/*
danddb0ac42010-07-14 14:48:58 +00004925** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004926** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004927** and a value suitable for passing as the third argument to open(2) is
4928** written to *pMode. If an IO error occurs, an SQLite error code is
4929** returned and the value of *pMode is not modified.
4930**
drh8c815d12012-02-13 20:16:37 +00004931** In most cases cases, this routine sets *pMode to 0, which will become
4932** an indication to robust_open() to create the file using
4933** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
4934** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00004935** this function queries the file-system for the permissions on the
4936** corresponding database file and sets *pMode to this value. Whenever
4937** possible, WAL and journal files are created using the same permissions
4938** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004939**
4940** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4941** original filename is unavailable. But 8_3_NAMES is only used for
4942** FAT filesystems and permissions do not matter there, so just use
4943** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004944*/
4945static int findCreateFileMode(
4946 const char *zPath, /* Path of file (possibly) being created */
4947 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00004948 mode_t *pMode, /* OUT: Permissions to open file with */
4949 uid_t *pUid, /* OUT: uid to set on the file */
4950 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00004951){
4952 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00004953 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00004954 *pUid = 0;
4955 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00004956 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004957 char zDb[MAX_PATHNAME+1]; /* Database file path */
4958 int nDb; /* Number of valid bytes in zDb */
4959 struct stat sStat; /* Output of stat() on database file */
4960
dana0c989d2010-11-05 18:07:37 +00004961 /* zPath is a path to a WAL or journal file. The following block derives
4962 ** the path to the associated database file from zPath. This block handles
4963 ** the following naming conventions:
4964 **
4965 ** "<path to db>-journal"
4966 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004967 ** "<path to db>-journalNN"
4968 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004969 **
drhd337c5b2011-10-20 18:23:35 +00004970 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004971 ** used by the test_multiplex.c module.
4972 */
4973 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004974#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004975 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004976 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004977#else
4978 while( zPath[nDb]!='-' ){
4979 assert( nDb>0 );
4980 assert( zPath[nDb]!='\n' );
4981 nDb--;
4982 }
4983#endif
danddb0ac42010-07-14 14:48:58 +00004984 memcpy(zDb, zPath, nDb);
4985 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004986
drh58384f12011-07-28 00:14:45 +00004987 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004988 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00004989 *pUid = sStat.st_uid;
4990 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00004991 }else{
4992 rc = SQLITE_IOERR_FSTAT;
4993 }
4994 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4995 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004996 }
4997 return rc;
4998}
4999
5000/*
danielk1977ad94b582007-08-20 06:44:22 +00005001** Open the file zPath.
5002**
danielk1977b4b47412007-08-17 15:53:36 +00005003** Previously, the SQLite OS layer used three functions in place of this
5004** one:
5005**
5006** sqlite3OsOpenReadWrite();
5007** sqlite3OsOpenReadOnly();
5008** sqlite3OsOpenExclusive();
5009**
5010** These calls correspond to the following combinations of flags:
5011**
5012** ReadWrite() -> (READWRITE | CREATE)
5013** ReadOnly() -> (READONLY)
5014** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5015**
5016** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5017** true, the file was configured to be automatically deleted when the
5018** file handle closed. To achieve the same effect using this new
5019** interface, add the DELETEONCLOSE flag to those specified above for
5020** OpenExclusive().
5021*/
5022static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005023 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5024 const char *zPath, /* Pathname of file to be opened */
5025 sqlite3_file *pFile, /* The file descriptor to be filled in */
5026 int flags, /* Input flags to control the opening */
5027 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005028){
dan08da86a2009-08-21 17:18:03 +00005029 unixFile *p = (unixFile *)pFile;
5030 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005031 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005032 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005033 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005034 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005035 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005036
5037 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5038 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5039 int isCreate = (flags & SQLITE_OPEN_CREATE);
5040 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5041 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005042#if SQLITE_ENABLE_LOCKING_STYLE
5043 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5044#endif
drh3d4435b2011-08-26 20:55:50 +00005045#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5046 struct statfs fsInfo;
5047#endif
danielk1977b4b47412007-08-17 15:53:36 +00005048
danielk1977fee2d252007-08-18 10:59:19 +00005049 /* If creating a master or main-file journal, this function will open
5050 ** a file-descriptor on the directory too. The first time unixSync()
5051 ** is called the directory file descriptor will be fsync()ed and close()d.
5052 */
drh0059eae2011-08-08 23:48:40 +00005053 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005054 eType==SQLITE_OPEN_MASTER_JOURNAL
5055 || eType==SQLITE_OPEN_MAIN_JOURNAL
5056 || eType==SQLITE_OPEN_WAL
5057 ));
danielk1977fee2d252007-08-18 10:59:19 +00005058
danielk197717b90b52008-06-06 11:11:25 +00005059 /* If argument zPath is a NULL pointer, this function is required to open
5060 ** a temporary file. Use this buffer to store the file name in.
5061 */
drhc02a43a2012-01-10 23:18:38 +00005062 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005063 const char *zName = zPath;
5064
danielk1977fee2d252007-08-18 10:59:19 +00005065 /* Check the following statements are true:
5066 **
5067 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5068 ** (b) if CREATE is set, then READWRITE must also be set, and
5069 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005070 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005071 */
danielk1977b4b47412007-08-17 15:53:36 +00005072 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005073 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005074 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005075 assert(isDelete==0 || isCreate);
5076
danddb0ac42010-07-14 14:48:58 +00005077 /* The main DB, main journal, WAL file and master journal are never
5078 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005079 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5080 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5081 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005082 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005083
danielk1977fee2d252007-08-18 10:59:19 +00005084 /* Assert that the upper layer has set one of the "file-type" flags. */
5085 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5086 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5087 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005088 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005089 );
5090
dan08da86a2009-08-21 17:18:03 +00005091 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005092
dan08da86a2009-08-21 17:18:03 +00005093 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005094 UnixUnusedFd *pUnused;
5095 pUnused = findReusableFd(zName, flags);
5096 if( pUnused ){
5097 fd = pUnused->fd;
5098 }else{
dan6aa657f2009-08-24 18:57:58 +00005099 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005100 if( !pUnused ){
5101 return SQLITE_NOMEM;
5102 }
5103 }
5104 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005105
5106 /* Database filenames are double-zero terminated if they are not
5107 ** URIs with parameters. Hence, they can always be passed into
5108 ** sqlite3_uri_parameter(). */
5109 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5110
dan08da86a2009-08-21 17:18:03 +00005111 }else if( !zName ){
5112 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005113 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005114 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005115 if( rc!=SQLITE_OK ){
5116 return rc;
5117 }
5118 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005119
5120 /* Generated temporary filenames are always double-zero terminated
5121 ** for use by sqlite3_uri_parameter(). */
5122 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005123 }
5124
dan08da86a2009-08-21 17:18:03 +00005125 /* Determine the value of the flags parameter passed to POSIX function
5126 ** open(). These must be calculated even if open() is not called, as
5127 ** they may be stored as part of the file handle and used by the
5128 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005129 if( isReadonly ) openFlags |= O_RDONLY;
5130 if( isReadWrite ) openFlags |= O_RDWR;
5131 if( isCreate ) openFlags |= O_CREAT;
5132 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5133 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005134
danielk1977b4b47412007-08-17 15:53:36 +00005135 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005136 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005137 uid_t uid; /* Userid for the file */
5138 gid_t gid; /* Groupid for the file */
5139 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005140 if( rc!=SQLITE_OK ){
5141 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005142 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005143 return rc;
5144 }
drhad4f1e52011-03-04 15:43:57 +00005145 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005146 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005147 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5148 /* Failed to open the file for read/write access. Try read-only. */
5149 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005150 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005151 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005152 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005153 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005154 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005155 }
5156 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005157 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005158 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005159 }
drhac7c3ac2012-02-11 19:23:48 +00005160
5161 /* If this process is running as root and if creating a new rollback
5162 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005163 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005164 */
5165 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005166 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005167 }
danielk1977b4b47412007-08-17 15:53:36 +00005168 }
dan08da86a2009-08-21 17:18:03 +00005169 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005170 if( pOutFlags ){
5171 *pOutFlags = flags;
5172 }
5173
dane946c392009-08-22 11:39:46 +00005174 if( p->pUnused ){
5175 p->pUnused->fd = fd;
5176 p->pUnused->flags = flags;
5177 }
5178
danielk1977b4b47412007-08-17 15:53:36 +00005179 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005180#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005181 zPath = zName;
5182#else
drh036ac7f2011-08-08 23:18:05 +00005183 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005184#endif
danielk1977b4b47412007-08-17 15:53:36 +00005185 }
drh41022642008-11-21 00:24:42 +00005186#if SQLITE_ENABLE_LOCKING_STYLE
5187 else{
dan08da86a2009-08-21 17:18:03 +00005188 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005189 }
5190#endif
5191
drhda0e7682008-07-30 15:27:54 +00005192 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005193
drh7ed97b92010-01-20 13:07:21 +00005194
5195#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005196 if( fstatfs(fd, &fsInfo) == -1 ){
5197 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005198 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005199 return SQLITE_IOERR_ACCESS;
5200 }
5201 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5202 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5203 }
5204#endif
drhc02a43a2012-01-10 23:18:38 +00005205
5206 /* Set up appropriate ctrlFlags */
5207 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5208 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5209 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5210 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5211 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5212
drh7ed97b92010-01-20 13:07:21 +00005213#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005214#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005215 isAutoProxy = 1;
5216#endif
5217 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005218 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5219 int useProxy = 0;
5220
dan08da86a2009-08-21 17:18:03 +00005221 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5222 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005223 if( envforce!=NULL ){
5224 useProxy = atoi(envforce)>0;
5225 }else{
aswiftaebf4132008-11-21 00:10:35 +00005226 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005227 /* In theory, the close(fd) call is sub-optimal. If the file opened
5228 ** with fd is a database file, and there are other connections open
5229 ** on that file that are currently holding advisory locks on it,
5230 ** then the call to close() will cancel those locks. In practice,
5231 ** we're assuming that statfs() doesn't fail very often. At least
5232 ** not while other file descriptors opened by the same process on
5233 ** the same file are working. */
5234 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005235 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005236 rc = SQLITE_IOERR_ACCESS;
5237 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005238 }
5239 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5240 }
5241 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005242 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005243 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005244 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005245 if( rc!=SQLITE_OK ){
5246 /* Use unixClose to clean up the resources added in fillInUnixFile
5247 ** and clear all the structure's references. Specifically,
5248 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5249 */
5250 unixClose(pFile);
5251 return rc;
5252 }
aswiftaebf4132008-11-21 00:10:35 +00005253 }
dane946c392009-08-22 11:39:46 +00005254 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005255 }
5256 }
5257#endif
5258
drhc02a43a2012-01-10 23:18:38 +00005259 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5260
dane946c392009-08-22 11:39:46 +00005261open_finished:
5262 if( rc!=SQLITE_OK ){
5263 sqlite3_free(p->pUnused);
5264 }
5265 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005266}
5267
dane946c392009-08-22 11:39:46 +00005268
danielk1977b4b47412007-08-17 15:53:36 +00005269/*
danielk1977fee2d252007-08-18 10:59:19 +00005270** Delete the file at zPath. If the dirSync argument is true, fsync()
5271** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005272*/
drh6b9d6dd2008-12-03 19:34:47 +00005273static int unixDelete(
5274 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5275 const char *zPath, /* Name of file to be deleted */
5276 int dirSync /* If true, fsync() directory after deleting file */
5277){
danielk1977fee2d252007-08-18 10:59:19 +00005278 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005279 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005280 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005281 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005282 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005283 }
danielk1977d39fa702008-10-16 13:27:40 +00005284#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005285 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005286 int fd;
drh90315a22011-08-10 01:52:12 +00005287 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005288 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005289#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005290 if( fsync(fd)==-1 )
5291#else
5292 if( fsync(fd) )
5293#endif
5294 {
dane18d4952011-02-21 11:46:24 +00005295 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005296 }
drh0e9365c2011-03-02 02:08:13 +00005297 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005298 }else if( rc==SQLITE_CANTOPEN ){
5299 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005300 }
5301 }
danielk1977d138dd82008-10-15 16:02:48 +00005302#endif
danielk1977fee2d252007-08-18 10:59:19 +00005303 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005304}
5305
danielk197790949c22007-08-17 16:50:38 +00005306/*
5307** Test the existance of or access permissions of file zPath. The
5308** test performed depends on the value of flags:
5309**
5310** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5311** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5312** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5313**
5314** Otherwise return 0.
5315*/
danielk1977861f7452008-06-05 11:39:11 +00005316static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005317 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5318 const char *zPath, /* Path of the file to examine */
5319 int flags, /* What do we want to learn about the zPath file? */
5320 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005321){
rse25c0d1a2007-09-20 08:38:14 +00005322 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005323 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005324 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005325 switch( flags ){
5326 case SQLITE_ACCESS_EXISTS:
5327 amode = F_OK;
5328 break;
5329 case SQLITE_ACCESS_READWRITE:
5330 amode = W_OK|R_OK;
5331 break;
drh50d3f902007-08-27 21:10:36 +00005332 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005333 amode = R_OK;
5334 break;
5335
5336 default:
5337 assert(!"Invalid flags argument");
5338 }
drh99ab3b12011-03-02 15:09:07 +00005339 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005340 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5341 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005342 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005343 *pResOut = 0;
5344 }
5345 }
danielk1977861f7452008-06-05 11:39:11 +00005346 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005347}
5348
danielk1977b4b47412007-08-17 15:53:36 +00005349
5350/*
5351** Turn a relative pathname into a full pathname. The relative path
5352** is stored as a nul-terminated string in the buffer pointed to by
5353** zPath.
5354**
5355** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5356** (in this case, MAX_PATHNAME bytes). The full-path is written to
5357** this buffer before returning.
5358*/
danielk1977adfb9b02007-09-17 07:02:56 +00005359static int unixFullPathname(
5360 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5361 const char *zPath, /* Possibly relative input path */
5362 int nOut, /* Size of output buffer in bytes */
5363 char *zOut /* Output buffer */
5364){
danielk1977843e65f2007-09-01 16:16:15 +00005365
5366 /* It's odd to simulate an io-error here, but really this is just
5367 ** using the io-error infrastructure to test that SQLite handles this
5368 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005369 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005370 */
5371 SimulateIOError( return SQLITE_ERROR );
5372
drh153c62c2007-08-24 03:51:33 +00005373 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005374 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005375
drh3c7f2dc2007-12-06 13:26:20 +00005376 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005377 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005378 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005379 }else{
5380 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005381 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005382 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005383 }
drhea678832008-12-10 19:26:22 +00005384 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005385 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005386 }
5387 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005388}
5389
drh0ccebe72005-06-07 22:22:50 +00005390
drh761df872006-12-21 01:29:22 +00005391#ifndef SQLITE_OMIT_LOAD_EXTENSION
5392/*
5393** Interfaces for opening a shared library, finding entry points
5394** within the shared library, and closing the shared library.
5395*/
5396#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005397static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5398 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005399 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5400}
danielk197795c8a542007-09-01 06:51:27 +00005401
5402/*
5403** SQLite calls this function immediately after a call to unixDlSym() or
5404** unixDlOpen() fails (returns a null pointer). If a more detailed error
5405** message is available, it is written to zBufOut. If no error message
5406** is available, zBufOut is left unmodified and SQLite uses a default
5407** error message.
5408*/
danielk1977397d65f2008-11-19 11:35:39 +00005409static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005410 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005411 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005412 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005413 zErr = dlerror();
5414 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005415 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005416 }
drh6c7d5c52008-11-21 20:32:33 +00005417 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005418}
drh1875f7a2008-12-08 18:19:17 +00005419static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5420 /*
5421 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5422 ** cast into a pointer to a function. And yet the library dlsym() routine
5423 ** returns a void* which is really a pointer to a function. So how do we
5424 ** use dlsym() with -pedantic-errors?
5425 **
5426 ** Variable x below is defined to be a pointer to a function taking
5427 ** parameters void* and const char* and returning a pointer to a function.
5428 ** We initialize x by assigning it a pointer to the dlsym() function.
5429 ** (That assignment requires a cast.) Then we call the function that
5430 ** x points to.
5431 **
5432 ** This work-around is unlikely to work correctly on any system where
5433 ** you really cannot cast a function pointer into void*. But then, on the
5434 ** other hand, dlsym() will not work on such a system either, so we have
5435 ** not really lost anything.
5436 */
5437 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005438 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005439 x = (void(*(*)(void*,const char*))(void))dlsym;
5440 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005441}
danielk1977397d65f2008-11-19 11:35:39 +00005442static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5443 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005444 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005445}
danielk1977b4b47412007-08-17 15:53:36 +00005446#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5447 #define unixDlOpen 0
5448 #define unixDlError 0
5449 #define unixDlSym 0
5450 #define unixDlClose 0
5451#endif
5452
5453/*
danielk197790949c22007-08-17 16:50:38 +00005454** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005455*/
danielk1977397d65f2008-11-19 11:35:39 +00005456static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5457 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005458 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005459
drhbbd42a62004-05-22 17:41:58 +00005460 /* We have to initialize zBuf to prevent valgrind from reporting
5461 ** errors. The reports issued by valgrind are incorrect - we would
5462 ** prefer that the randomness be increased by making use of the
5463 ** uninitialized space in zBuf - but valgrind errors tend to worry
5464 ** some users. Rather than argue, it seems easier just to initialize
5465 ** the whole array and silence valgrind, even if that means less randomness
5466 ** in the random seed.
5467 **
5468 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005469 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005470 ** tests repeatable.
5471 */
danielk1977b4b47412007-08-17 15:53:36 +00005472 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005473#if !defined(SQLITE_TEST)
5474 {
drhc18b4042012-02-10 03:10:27 +00005475 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005476 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005477 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005478 time_t t;
5479 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005480 memcpy(zBuf, &t, sizeof(t));
5481 pid = getpid();
5482 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005483 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005484 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005485 }else{
drhc18b4042012-02-10 03:10:27 +00005486 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005487 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005488 }
drhbbd42a62004-05-22 17:41:58 +00005489 }
5490#endif
drh72cbd072008-10-14 17:58:38 +00005491 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005492}
5493
danielk1977b4b47412007-08-17 15:53:36 +00005494
drhbbd42a62004-05-22 17:41:58 +00005495/*
5496** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005497** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005498** The return value is the number of microseconds of sleep actually
5499** requested from the underlying operating system, a number which
5500** might be greater than or equal to the argument, but not less
5501** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005502*/
danielk1977397d65f2008-11-19 11:35:39 +00005503static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005504#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005505 struct timespec sp;
5506
5507 sp.tv_sec = microseconds / 1000000;
5508 sp.tv_nsec = (microseconds % 1000000) * 1000;
5509 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005510 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005511 return microseconds;
5512#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005513 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005514 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005515 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005516#else
danielk1977b4b47412007-08-17 15:53:36 +00005517 int seconds = (microseconds+999999)/1000000;
5518 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005519 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005520 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005521#endif
drh88f474a2006-01-02 20:00:12 +00005522}
5523
5524/*
drh6b9d6dd2008-12-03 19:34:47 +00005525** The following variable, if set to a non-zero value, is interpreted as
5526** the number of seconds since 1970 and is used to set the result of
5527** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005528*/
5529#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005530int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005531#endif
5532
5533/*
drhb7e8ea22010-05-03 14:32:30 +00005534** Find the current time (in Universal Coordinated Time). Write into *piNow
5535** the current time and date as a Julian Day number times 86_400_000. In
5536** other words, write into *piNow the number of milliseconds since the Julian
5537** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5538** proleptic Gregorian calendar.
5539**
drh31702252011-10-12 23:13:43 +00005540** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5541** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005542*/
5543static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5544 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005545 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005546#if defined(NO_GETTOD)
5547 time_t t;
5548 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005549 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005550#elif OS_VXWORKS
5551 struct timespec sNow;
5552 clock_gettime(CLOCK_REALTIME, &sNow);
5553 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5554#else
5555 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005556 if( gettimeofday(&sNow, 0)==0 ){
5557 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5558 }else{
5559 rc = SQLITE_ERROR;
5560 }
drhb7e8ea22010-05-03 14:32:30 +00005561#endif
5562
5563#ifdef SQLITE_TEST
5564 if( sqlite3_current_time ){
5565 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5566 }
5567#endif
5568 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005569 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005570}
5571
5572/*
drhbbd42a62004-05-22 17:41:58 +00005573** Find the current time (in Universal Coordinated Time). Write the
5574** current time and date as a Julian Day number into *prNow and
5575** return 0. Return 1 if the time and date cannot be found.
5576*/
danielk1977397d65f2008-11-19 11:35:39 +00005577static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005578 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005579 int rc;
drhff828942010-06-26 21:34:06 +00005580 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005581 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005582 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005583 return rc;
drhbbd42a62004-05-22 17:41:58 +00005584}
danielk1977b4b47412007-08-17 15:53:36 +00005585
drh6b9d6dd2008-12-03 19:34:47 +00005586/*
5587** We added the xGetLastError() method with the intention of providing
5588** better low-level error messages when operating-system problems come up
5589** during SQLite operation. But so far, none of that has been implemented
5590** in the core. So this routine is never called. For now, it is merely
5591** a place-holder.
5592*/
danielk1977397d65f2008-11-19 11:35:39 +00005593static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5594 UNUSED_PARAMETER(NotUsed);
5595 UNUSED_PARAMETER(NotUsed2);
5596 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005597 return 0;
5598}
5599
drhf2424c52010-04-26 00:04:55 +00005600
5601/*
drh734c9862008-11-28 15:37:20 +00005602************************ End of sqlite3_vfs methods ***************************
5603******************************************************************************/
5604
drh715ff302008-12-03 22:32:44 +00005605/******************************************************************************
5606************************** Begin Proxy Locking ********************************
5607**
5608** Proxy locking is a "uber-locking-method" in this sense: It uses the
5609** other locking methods on secondary lock files. Proxy locking is a
5610** meta-layer over top of the primitive locking implemented above. For
5611** this reason, the division that implements of proxy locking is deferred
5612** until late in the file (here) after all of the other I/O methods have
5613** been defined - so that the primitive locking methods are available
5614** as services to help with the implementation of proxy locking.
5615**
5616****
5617**
5618** The default locking schemes in SQLite use byte-range locks on the
5619** database file to coordinate safe, concurrent access by multiple readers
5620** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5621** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5622** as POSIX read & write locks over fixed set of locations (via fsctl),
5623** on AFP and SMB only exclusive byte-range locks are available via fsctl
5624** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5625** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5626** address in the shared range is taken for a SHARED lock, the entire
5627** shared range is taken for an EXCLUSIVE lock):
5628**
drhf2f105d2012-08-20 15:53:54 +00005629** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00005630** RESERVED_BYTE 0x40000001
5631** SHARED_RANGE 0x40000002 -> 0x40000200
5632**
5633** This works well on the local file system, but shows a nearly 100x
5634** slowdown in read performance on AFP because the AFP client disables
5635** the read cache when byte-range locks are present. Enabling the read
5636** cache exposes a cache coherency problem that is present on all OS X
5637** supported network file systems. NFS and AFP both observe the
5638** close-to-open semantics for ensuring cache coherency
5639** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5640** address the requirements for concurrent database access by multiple
5641** readers and writers
5642** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5643**
5644** To address the performance and cache coherency issues, proxy file locking
5645** changes the way database access is controlled by limiting access to a
5646** single host at a time and moving file locks off of the database file
5647** and onto a proxy file on the local file system.
5648**
5649**
5650** Using proxy locks
5651** -----------------
5652**
5653** C APIs
5654**
5655** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5656** <proxy_path> | ":auto:");
5657** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5658**
5659**
5660** SQL pragmas
5661**
5662** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5663** PRAGMA [database.]lock_proxy_file
5664**
5665** Specifying ":auto:" means that if there is a conch file with a matching
5666** host ID in it, the proxy path in the conch file will be used, otherwise
5667** a proxy path based on the user's temp dir
5668** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5669** actual proxy file name is generated from the name and path of the
5670** database file. For example:
5671**
5672** For database path "/Users/me/foo.db"
5673** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5674**
5675** Once a lock proxy is configured for a database connection, it can not
5676** be removed, however it may be switched to a different proxy path via
5677** the above APIs (assuming the conch file is not being held by another
5678** connection or process).
5679**
5680**
5681** How proxy locking works
5682** -----------------------
5683**
5684** Proxy file locking relies primarily on two new supporting files:
5685**
5686** * conch file to limit access to the database file to a single host
5687** at a time
5688**
5689** * proxy file to act as a proxy for the advisory locks normally
5690** taken on the database
5691**
5692** The conch file - to use a proxy file, sqlite must first "hold the conch"
5693** by taking an sqlite-style shared lock on the conch file, reading the
5694** contents and comparing the host's unique host ID (see below) and lock
5695** proxy path against the values stored in the conch. The conch file is
5696** stored in the same directory as the database file and the file name
5697** is patterned after the database file name as ".<databasename>-conch".
5698** If the conch file does not exist, or it's contents do not match the
5699** host ID and/or proxy path, then the lock is escalated to an exclusive
5700** lock and the conch file contents is updated with the host ID and proxy
5701** path and the lock is downgraded to a shared lock again. If the conch
5702** is held by another process (with a shared lock), the exclusive lock
5703** will fail and SQLITE_BUSY is returned.
5704**
5705** The proxy file - a single-byte file used for all advisory file locks
5706** normally taken on the database file. This allows for safe sharing
5707** of the database file for multiple readers and writers on the same
5708** host (the conch ensures that they all use the same local lock file).
5709**
drh715ff302008-12-03 22:32:44 +00005710** Requesting the lock proxy does not immediately take the conch, it is
5711** only taken when the first request to lock database file is made.
5712** This matches the semantics of the traditional locking behavior, where
5713** opening a connection to a database file does not take a lock on it.
5714** The shared lock and an open file descriptor are maintained until
5715** the connection to the database is closed.
5716**
5717** The proxy file and the lock file are never deleted so they only need
5718** to be created the first time they are used.
5719**
5720** Configuration options
5721** ---------------------
5722**
5723** SQLITE_PREFER_PROXY_LOCKING
5724**
5725** Database files accessed on non-local file systems are
5726** automatically configured for proxy locking, lock files are
5727** named automatically using the same logic as
5728** PRAGMA lock_proxy_file=":auto:"
5729**
5730** SQLITE_PROXY_DEBUG
5731**
5732** Enables the logging of error messages during host id file
5733** retrieval and creation
5734**
drh715ff302008-12-03 22:32:44 +00005735** LOCKPROXYDIR
5736**
5737** Overrides the default directory used for lock proxy files that
5738** are named automatically via the ":auto:" setting
5739**
5740** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5741**
5742** Permissions to use when creating a directory for storing the
5743** lock proxy files, only used when LOCKPROXYDIR is not set.
5744**
5745**
5746** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5747** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5748** force proxy locking to be used for every database file opened, and 0
5749** will force automatic proxy locking to be disabled for all database
5750** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5751** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5752*/
5753
5754/*
5755** Proxy locking is only available on MacOSX
5756*/
drhd2cb50b2009-01-09 21:41:17 +00005757#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005758
drh715ff302008-12-03 22:32:44 +00005759/*
5760** The proxyLockingContext has the path and file structures for the remote
5761** and local proxy files in it
5762*/
5763typedef struct proxyLockingContext proxyLockingContext;
5764struct proxyLockingContext {
5765 unixFile *conchFile; /* Open conch file */
5766 char *conchFilePath; /* Name of the conch file */
5767 unixFile *lockProxy; /* Open proxy lock file */
5768 char *lockProxyPath; /* Name of the proxy lock file */
5769 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005770 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005771 void *oldLockingContext; /* Original lockingcontext to restore on close */
5772 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5773};
5774
drh7ed97b92010-01-20 13:07:21 +00005775/*
5776** The proxy lock file path for the database at dbPath is written into lPath,
5777** which must point to valid, writable memory large enough for a maxLen length
5778** file path.
drh715ff302008-12-03 22:32:44 +00005779*/
drh715ff302008-12-03 22:32:44 +00005780static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5781 int len;
5782 int dbLen;
5783 int i;
5784
5785#ifdef LOCKPROXYDIR
5786 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5787#else
5788# ifdef _CS_DARWIN_USER_TEMP_DIR
5789 {
drh7ed97b92010-01-20 13:07:21 +00005790 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005791 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5792 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005793 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005794 }
drh7ed97b92010-01-20 13:07:21 +00005795 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005796 }
5797# else
5798 len = strlcpy(lPath, "/tmp/", maxLen);
5799# endif
5800#endif
5801
5802 if( lPath[len-1]!='/' ){
5803 len = strlcat(lPath, "/", maxLen);
5804 }
5805
5806 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005807 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005808 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005809 char c = dbPath[i];
5810 lPath[i+len] = (c=='/')?'_':c;
5811 }
5812 lPath[i+len]='\0';
5813 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005814 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005815 return SQLITE_OK;
5816}
5817
drh7ed97b92010-01-20 13:07:21 +00005818/*
5819 ** Creates the lock file and any missing directories in lockPath
5820 */
5821static int proxyCreateLockPath(const char *lockPath){
5822 int i, len;
5823 char buf[MAXPATHLEN];
5824 int start = 0;
5825
5826 assert(lockPath!=NULL);
5827 /* try to create all the intermediate directories */
5828 len = (int)strlen(lockPath);
5829 buf[0] = lockPath[0];
5830 for( i=1; i<len; i++ ){
5831 if( lockPath[i] == '/' && (i - start > 0) ){
5832 /* only mkdir if leaf dir != "." or "/" or ".." */
5833 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5834 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5835 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005836 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005837 int err=errno;
5838 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005839 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005840 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005841 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005842 return err;
5843 }
5844 }
5845 }
5846 start=i+1;
5847 }
5848 buf[i] = lockPath[i];
5849 }
drh308c2a52010-05-14 11:30:18 +00005850 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005851 return 0;
5852}
5853
drh715ff302008-12-03 22:32:44 +00005854/*
5855** Create a new VFS file descriptor (stored in memory obtained from
5856** sqlite3_malloc) and open the file named "path" in the file descriptor.
5857**
5858** The caller is responsible not only for closing the file descriptor
5859** but also for freeing the memory associated with the file descriptor.
5860*/
drh7ed97b92010-01-20 13:07:21 +00005861static int proxyCreateUnixFile(
5862 const char *path, /* path for the new unixFile */
5863 unixFile **ppFile, /* unixFile created and returned by ref */
5864 int islockfile /* if non zero missing dirs will be created */
5865) {
5866 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005867 unixFile *pNew;
5868 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005869 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005870 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005871 int terrno = 0;
5872 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005873
drh7ed97b92010-01-20 13:07:21 +00005874 /* 1. first try to open/create the file
5875 ** 2. if that fails, and this is a lock file (not-conch), try creating
5876 ** the parent directories and then try again.
5877 ** 3. if that fails, try to open the file read-only
5878 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5879 */
5880 pUnused = findReusableFd(path, openFlags);
5881 if( pUnused ){
5882 fd = pUnused->fd;
5883 }else{
5884 pUnused = sqlite3_malloc(sizeof(*pUnused));
5885 if( !pUnused ){
5886 return SQLITE_NOMEM;
5887 }
5888 }
5889 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00005890 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005891 terrno = errno;
5892 if( fd<0 && errno==ENOENT && islockfile ){
5893 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00005894 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005895 }
5896 }
5897 }
5898 if( fd<0 ){
5899 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00005900 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005901 terrno = errno;
5902 }
5903 if( fd<0 ){
5904 if( islockfile ){
5905 return SQLITE_BUSY;
5906 }
5907 switch (terrno) {
5908 case EACCES:
5909 return SQLITE_PERM;
5910 case EIO:
5911 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5912 default:
drh9978c972010-02-23 17:36:32 +00005913 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005914 }
5915 }
5916
5917 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5918 if( pNew==NULL ){
5919 rc = SQLITE_NOMEM;
5920 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005921 }
5922 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005923 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005924 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005925 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005926 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005927 pUnused->fd = fd;
5928 pUnused->flags = openFlags;
5929 pNew->pUnused = pUnused;
5930
drhc02a43a2012-01-10 23:18:38 +00005931 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00005932 if( rc==SQLITE_OK ){
5933 *ppFile = pNew;
5934 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005935 }
drh7ed97b92010-01-20 13:07:21 +00005936end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005937 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005938 sqlite3_free(pNew);
5939 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005940 return rc;
5941}
5942
drh7ed97b92010-01-20 13:07:21 +00005943#ifdef SQLITE_TEST
5944/* simulate multiple hosts by creating unique hostid file paths */
5945int sqlite3_hostid_num = 0;
5946#endif
5947
5948#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5949
drh0ab216a2010-07-02 17:10:40 +00005950/* Not always defined in the headers as it ought to be */
5951extern int gethostuuid(uuid_t id, const struct timespec *wait);
5952
drh7ed97b92010-01-20 13:07:21 +00005953/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5954** bytes of writable memory.
5955*/
5956static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005957 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5958 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005959#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5960 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005961 {
5962 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5963 if( gethostuuid(pHostID, &timeout) ){
5964 int err = errno;
5965 if( pError ){
5966 *pError = err;
5967 }
5968 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005969 }
drh7ed97b92010-01-20 13:07:21 +00005970 }
drh3d4435b2011-08-26 20:55:50 +00005971#else
5972 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005973#endif
drh7ed97b92010-01-20 13:07:21 +00005974#ifdef SQLITE_TEST
5975 /* simulate multiple hosts by creating unique hostid file paths */
5976 if( sqlite3_hostid_num != 0){
5977 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5978 }
5979#endif
5980
5981 return SQLITE_OK;
5982}
5983
5984/* The conch file contains the header, host id and lock file path
5985 */
5986#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5987#define PROXY_HEADERLEN 1 /* conch file header length */
5988#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5989#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5990
5991/*
5992** Takes an open conch file, copies the contents to a new path and then moves
5993** it back. The newly created file's file descriptor is assigned to the
5994** conch file structure and finally the original conch file descriptor is
5995** closed. Returns zero if successful.
5996*/
5997static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5998 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5999 unixFile *conchFile = pCtx->conchFile;
6000 char tPath[MAXPATHLEN];
6001 char buf[PROXY_MAXCONCHLEN];
6002 char *cPath = pCtx->conchFilePath;
6003 size_t readLen = 0;
6004 size_t pathLen = 0;
6005 char errmsg[64] = "";
6006 int fd = -1;
6007 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006008 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006009
6010 /* create a new path by replace the trailing '-conch' with '-break' */
6011 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6012 if( pathLen>MAXPATHLEN || pathLen<6 ||
6013 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006014 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006015 goto end_breaklock;
6016 }
6017 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006018 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006019 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006020 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006021 goto end_breaklock;
6022 }
6023 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006024 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006025 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006026 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006027 goto end_breaklock;
6028 }
drhe562be52011-03-02 18:01:10 +00006029 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006030 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006031 goto end_breaklock;
6032 }
6033 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006034 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006035 goto end_breaklock;
6036 }
6037 rc = 0;
6038 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006039 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006040 conchFile->h = fd;
6041 conchFile->openFlags = O_RDWR | O_CREAT;
6042
6043end_breaklock:
6044 if( rc ){
6045 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006046 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006047 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006048 }
6049 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6050 }
6051 return rc;
6052}
6053
6054/* Take the requested lock on the conch file and break a stale lock if the
6055** host id matches.
6056*/
6057static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6058 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6059 unixFile *conchFile = pCtx->conchFile;
6060 int rc = SQLITE_OK;
6061 int nTries = 0;
6062 struct timespec conchModTime;
6063
drh3d4435b2011-08-26 20:55:50 +00006064 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006065 do {
6066 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6067 nTries ++;
6068 if( rc==SQLITE_BUSY ){
6069 /* If the lock failed (busy):
6070 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6071 * 2nd try: fail if the mod time changed or host id is different, wait
6072 * 10 sec and try again
6073 * 3rd try: break the lock unless the mod time has changed.
6074 */
6075 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006076 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006077 pFile->lastErrno = errno;
6078 return SQLITE_IOERR_LOCK;
6079 }
6080
6081 if( nTries==1 ){
6082 conchModTime = buf.st_mtimespec;
6083 usleep(500000); /* wait 0.5 sec and try the lock again*/
6084 continue;
6085 }
6086
6087 assert( nTries>1 );
6088 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6089 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6090 return SQLITE_BUSY;
6091 }
6092
6093 if( nTries==2 ){
6094 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006095 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006096 if( len<0 ){
6097 pFile->lastErrno = errno;
6098 return SQLITE_IOERR_LOCK;
6099 }
6100 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6101 /* don't break the lock if the host id doesn't match */
6102 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6103 return SQLITE_BUSY;
6104 }
6105 }else{
6106 /* don't break the lock on short read or a version mismatch */
6107 return SQLITE_BUSY;
6108 }
6109 usleep(10000000); /* wait 10 sec and try the lock again */
6110 continue;
6111 }
6112
6113 assert( nTries==3 );
6114 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6115 rc = SQLITE_OK;
6116 if( lockType==EXCLUSIVE_LOCK ){
6117 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6118 }
6119 if( !rc ){
6120 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6121 }
6122 }
6123 }
6124 } while( rc==SQLITE_BUSY && nTries<3 );
6125
6126 return rc;
6127}
6128
6129/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006130** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6131** lockPath means that the lockPath in the conch file will be used if the
6132** host IDs match, or a new lock path will be generated automatically
6133** and written to the conch file.
6134*/
6135static int proxyTakeConch(unixFile *pFile){
6136 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6137
drh7ed97b92010-01-20 13:07:21 +00006138 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006139 return SQLITE_OK;
6140 }else{
6141 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006142 uuid_t myHostID;
6143 int pError = 0;
6144 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006145 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006146 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006147 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006148 int createConch = 0;
6149 int hostIdMatch = 0;
6150 int readLen = 0;
6151 int tryOldLockPath = 0;
6152 int forceNewLockPath = 0;
6153
drh308c2a52010-05-14 11:30:18 +00006154 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6155 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006156
drh7ed97b92010-01-20 13:07:21 +00006157 rc = proxyGetHostID(myHostID, &pError);
6158 if( (rc&0xff)==SQLITE_IOERR ){
6159 pFile->lastErrno = pError;
6160 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006161 }
drh7ed97b92010-01-20 13:07:21 +00006162 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006163 if( rc!=SQLITE_OK ){
6164 goto end_takeconch;
6165 }
drh7ed97b92010-01-20 13:07:21 +00006166 /* read the existing conch file */
6167 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6168 if( readLen<0 ){
6169 /* I/O error: lastErrno set by seekAndRead */
6170 pFile->lastErrno = conchFile->lastErrno;
6171 rc = SQLITE_IOERR_READ;
6172 goto end_takeconch;
6173 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6174 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6175 /* a short read or version format mismatch means we need to create a new
6176 ** conch file.
6177 */
6178 createConch = 1;
6179 }
6180 /* if the host id matches and the lock path already exists in the conch
6181 ** we'll try to use the path there, if we can't open that path, we'll
6182 ** retry with a new auto-generated path
6183 */
6184 do { /* in case we need to try again for an :auto: named lock file */
6185
6186 if( !createConch && !forceNewLockPath ){
6187 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6188 PROXY_HOSTIDLEN);
6189 /* if the conch has data compare the contents */
6190 if( !pCtx->lockProxyPath ){
6191 /* for auto-named local lock file, just check the host ID and we'll
6192 ** use the local lock file path that's already in there
6193 */
6194 if( hostIdMatch ){
6195 size_t pathLen = (readLen - PROXY_PATHINDEX);
6196
6197 if( pathLen>=MAXPATHLEN ){
6198 pathLen=MAXPATHLEN-1;
6199 }
6200 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6201 lockPath[pathLen] = 0;
6202 tempLockPath = lockPath;
6203 tryOldLockPath = 1;
6204 /* create a copy of the lock path if the conch is taken */
6205 goto end_takeconch;
6206 }
6207 }else if( hostIdMatch
6208 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6209 readLen-PROXY_PATHINDEX)
6210 ){
6211 /* conch host and lock path match */
6212 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006213 }
drh7ed97b92010-01-20 13:07:21 +00006214 }
6215
6216 /* if the conch isn't writable and doesn't match, we can't take it */
6217 if( (conchFile->openFlags&O_RDWR) == 0 ){
6218 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006219 goto end_takeconch;
6220 }
drh7ed97b92010-01-20 13:07:21 +00006221
6222 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006223 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006224 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6225 tempLockPath = lockPath;
6226 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006227 }
drh7ed97b92010-01-20 13:07:21 +00006228
6229 /* update conch with host and path (this will fail if other process
6230 ** has a shared lock already), if the host id matches, use the big
6231 ** stick.
drh715ff302008-12-03 22:32:44 +00006232 */
drh7ed97b92010-01-20 13:07:21 +00006233 futimes(conchFile->h, NULL);
6234 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006235 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006236 /* We are trying for an exclusive lock but another thread in this
6237 ** same process is still holding a shared lock. */
6238 rc = SQLITE_BUSY;
6239 } else {
6240 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006241 }
drh715ff302008-12-03 22:32:44 +00006242 }else{
drh7ed97b92010-01-20 13:07:21 +00006243 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006244 }
drh7ed97b92010-01-20 13:07:21 +00006245 if( rc==SQLITE_OK ){
6246 char writeBuffer[PROXY_MAXCONCHLEN];
6247 int writeSize = 0;
6248
6249 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6250 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6251 if( pCtx->lockProxyPath!=NULL ){
6252 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6253 }else{
6254 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6255 }
6256 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006257 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006258 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6259 fsync(conchFile->h);
6260 /* If we created a new conch file (not just updated the contents of a
6261 ** valid conch file), try to match the permissions of the database
6262 */
6263 if( rc==SQLITE_OK && createConch ){
6264 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006265 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006266 if( err==0 ){
6267 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6268 S_IROTH|S_IWOTH);
6269 /* try to match the database file R/W permissions, ignore failure */
6270#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006271 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006272#else
drhff812312011-02-23 13:33:46 +00006273 do{
drhe562be52011-03-02 18:01:10 +00006274 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006275 }while( rc==(-1) && errno==EINTR );
6276 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006277 int code = errno;
6278 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6279 cmode, code, strerror(code));
6280 } else {
6281 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6282 }
6283 }else{
6284 int code = errno;
6285 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6286 err, code, strerror(code));
6287#endif
6288 }
drh715ff302008-12-03 22:32:44 +00006289 }
6290 }
drh7ed97b92010-01-20 13:07:21 +00006291 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6292
6293 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006294 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006295 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006296 int fd;
drh7ed97b92010-01-20 13:07:21 +00006297 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006298 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006299 }
6300 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006301 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006302 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006303 if( fd>=0 ){
6304 pFile->h = fd;
6305 }else{
drh9978c972010-02-23 17:36:32 +00006306 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006307 during locking */
6308 }
6309 }
6310 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6311 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6312 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6313 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6314 /* we couldn't create the proxy lock file with the old lock file path
6315 ** so try again via auto-naming
6316 */
6317 forceNewLockPath = 1;
6318 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006319 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006320 }
6321 }
6322 if( rc==SQLITE_OK ){
6323 /* Need to make a copy of path if we extracted the value
6324 ** from the conch file or the path was allocated on the stack
6325 */
6326 if( tempLockPath ){
6327 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6328 if( !pCtx->lockProxyPath ){
6329 rc = SQLITE_NOMEM;
6330 }
6331 }
6332 }
6333 if( rc==SQLITE_OK ){
6334 pCtx->conchHeld = 1;
6335
6336 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6337 afpLockingContext *afpCtx;
6338 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6339 afpCtx->dbPath = pCtx->lockProxyPath;
6340 }
6341 } else {
6342 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6343 }
drh308c2a52010-05-14 11:30:18 +00006344 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6345 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006346 return rc;
drh308c2a52010-05-14 11:30:18 +00006347 } while (1); /* in case we need to retry the :auto: lock file -
6348 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006349 }
6350}
6351
6352/*
6353** If pFile holds a lock on a conch file, then release that lock.
6354*/
6355static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006356 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006357 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6358 unixFile *conchFile; /* Name of the conch file */
6359
6360 pCtx = (proxyLockingContext *)pFile->lockingContext;
6361 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006362 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006363 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006364 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006365 if( pCtx->conchHeld>0 ){
6366 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6367 }
drh715ff302008-12-03 22:32:44 +00006368 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006369 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6370 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006371 return rc;
6372}
6373
6374/*
6375** Given the name of a database file, compute the name of its conch file.
6376** Store the conch filename in memory obtained from sqlite3_malloc().
6377** Make *pConchPath point to the new name. Return SQLITE_OK on success
6378** or SQLITE_NOMEM if unable to obtain memory.
6379**
6380** The caller is responsible for ensuring that the allocated memory
6381** space is eventually freed.
6382**
6383** *pConchPath is set to NULL if a memory allocation error occurs.
6384*/
6385static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6386 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006387 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006388 char *conchPath; /* buffer in which to construct conch name */
6389
6390 /* Allocate space for the conch filename and initialize the name to
6391 ** the name of the original database file. */
6392 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6393 if( conchPath==0 ){
6394 return SQLITE_NOMEM;
6395 }
6396 memcpy(conchPath, dbPath, len+1);
6397
6398 /* now insert a "." before the last / character */
6399 for( i=(len-1); i>=0; i-- ){
6400 if( conchPath[i]=='/' ){
6401 i++;
6402 break;
6403 }
6404 }
6405 conchPath[i]='.';
6406 while ( i<len ){
6407 conchPath[i+1]=dbPath[i];
6408 i++;
6409 }
6410
6411 /* append the "-conch" suffix to the file */
6412 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006413 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006414
6415 return SQLITE_OK;
6416}
6417
6418
6419/* Takes a fully configured proxy locking-style unix file and switches
6420** the local lock file path
6421*/
6422static int switchLockProxyPath(unixFile *pFile, const char *path) {
6423 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6424 char *oldPath = pCtx->lockProxyPath;
6425 int rc = SQLITE_OK;
6426
drh308c2a52010-05-14 11:30:18 +00006427 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006428 return SQLITE_BUSY;
6429 }
6430
6431 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6432 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6433 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6434 return SQLITE_OK;
6435 }else{
6436 unixFile *lockProxy = pCtx->lockProxy;
6437 pCtx->lockProxy=NULL;
6438 pCtx->conchHeld = 0;
6439 if( lockProxy!=NULL ){
6440 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6441 if( rc ) return rc;
6442 sqlite3_free(lockProxy);
6443 }
6444 sqlite3_free(oldPath);
6445 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6446 }
6447
6448 return rc;
6449}
6450
6451/*
6452** pFile is a file that has been opened by a prior xOpen call. dbPath
6453** is a string buffer at least MAXPATHLEN+1 characters in size.
6454**
6455** This routine find the filename associated with pFile and writes it
6456** int dbPath.
6457*/
6458static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006459#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006460 if( pFile->pMethod == &afpIoMethods ){
6461 /* afp style keeps a reference to the db path in the filePath field
6462 ** of the struct */
drhea678832008-12-10 19:26:22 +00006463 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006464 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6465 } else
drh715ff302008-12-03 22:32:44 +00006466#endif
6467 if( pFile->pMethod == &dotlockIoMethods ){
6468 /* dot lock style uses the locking context to store the dot lock
6469 ** file path */
6470 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6471 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6472 }else{
6473 /* all other styles use the locking context to store the db file path */
6474 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006475 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006476 }
6477 return SQLITE_OK;
6478}
6479
6480/*
6481** Takes an already filled in unix file and alters it so all file locking
6482** will be performed on the local proxy lock file. The following fields
6483** are preserved in the locking context so that they can be restored and
6484** the unix structure properly cleaned up at close time:
6485** ->lockingContext
6486** ->pMethod
6487*/
6488static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6489 proxyLockingContext *pCtx;
6490 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6491 char *lockPath=NULL;
6492 int rc = SQLITE_OK;
6493
drh308c2a52010-05-14 11:30:18 +00006494 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006495 return SQLITE_BUSY;
6496 }
6497 proxyGetDbPathForUnixFile(pFile, dbPath);
6498 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6499 lockPath=NULL;
6500 }else{
6501 lockPath=(char *)path;
6502 }
6503
drh308c2a52010-05-14 11:30:18 +00006504 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6505 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006506
6507 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6508 if( pCtx==0 ){
6509 return SQLITE_NOMEM;
6510 }
6511 memset(pCtx, 0, sizeof(*pCtx));
6512
6513 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6514 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006515 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6516 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6517 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6518 ** (c) the file system is read-only, then enable no-locking access.
6519 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6520 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6521 */
6522 struct statfs fsInfo;
6523 struct stat conchInfo;
6524 int goLockless = 0;
6525
drh99ab3b12011-03-02 15:09:07 +00006526 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006527 int err = errno;
6528 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6529 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6530 }
6531 }
6532 if( goLockless ){
6533 pCtx->conchHeld = -1; /* read only FS/ lockless */
6534 rc = SQLITE_OK;
6535 }
6536 }
drh715ff302008-12-03 22:32:44 +00006537 }
6538 if( rc==SQLITE_OK && lockPath ){
6539 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6540 }
6541
6542 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006543 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6544 if( pCtx->dbPath==NULL ){
6545 rc = SQLITE_NOMEM;
6546 }
6547 }
6548 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006549 /* all memory is allocated, proxys are created and assigned,
6550 ** switch the locking context and pMethod then return.
6551 */
drh715ff302008-12-03 22:32:44 +00006552 pCtx->oldLockingContext = pFile->lockingContext;
6553 pFile->lockingContext = pCtx;
6554 pCtx->pOldMethod = pFile->pMethod;
6555 pFile->pMethod = &proxyIoMethods;
6556 }else{
6557 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006558 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006559 sqlite3_free(pCtx->conchFile);
6560 }
drhd56b1212010-08-11 06:14:15 +00006561 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006562 sqlite3_free(pCtx->conchFilePath);
6563 sqlite3_free(pCtx);
6564 }
drh308c2a52010-05-14 11:30:18 +00006565 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6566 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006567 return rc;
6568}
6569
6570
6571/*
6572** This routine handles sqlite3_file_control() calls that are specific
6573** to proxy locking.
6574*/
6575static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6576 switch( op ){
6577 case SQLITE_GET_LOCKPROXYFILE: {
6578 unixFile *pFile = (unixFile*)id;
6579 if( pFile->pMethod == &proxyIoMethods ){
6580 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6581 proxyTakeConch(pFile);
6582 if( pCtx->lockProxyPath ){
6583 *(const char **)pArg = pCtx->lockProxyPath;
6584 }else{
6585 *(const char **)pArg = ":auto: (not held)";
6586 }
6587 } else {
6588 *(const char **)pArg = NULL;
6589 }
6590 return SQLITE_OK;
6591 }
6592 case SQLITE_SET_LOCKPROXYFILE: {
6593 unixFile *pFile = (unixFile*)id;
6594 int rc = SQLITE_OK;
6595 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6596 if( pArg==NULL || (const char *)pArg==0 ){
6597 if( isProxyStyle ){
6598 /* turn off proxy locking - not supported */
6599 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6600 }else{
6601 /* turn off proxy locking - already off - NOOP */
6602 rc = SQLITE_OK;
6603 }
6604 }else{
6605 const char *proxyPath = (const char *)pArg;
6606 if( isProxyStyle ){
6607 proxyLockingContext *pCtx =
6608 (proxyLockingContext*)pFile->lockingContext;
6609 if( !strcmp(pArg, ":auto:")
6610 || (pCtx->lockProxyPath &&
6611 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6612 ){
6613 rc = SQLITE_OK;
6614 }else{
6615 rc = switchLockProxyPath(pFile, proxyPath);
6616 }
6617 }else{
6618 /* turn on proxy file locking */
6619 rc = proxyTransformUnixFile(pFile, proxyPath);
6620 }
6621 }
6622 return rc;
6623 }
6624 default: {
6625 assert( 0 ); /* The call assures that only valid opcodes are sent */
6626 }
6627 }
6628 /*NOTREACHED*/
6629 return SQLITE_ERROR;
6630}
6631
6632/*
6633** Within this division (the proxying locking implementation) the procedures
6634** above this point are all utilities. The lock-related methods of the
6635** proxy-locking sqlite3_io_method object follow.
6636*/
6637
6638
6639/*
6640** This routine checks if there is a RESERVED lock held on the specified
6641** file by this or any other process. If such a lock is held, set *pResOut
6642** to a non-zero value otherwise *pResOut is set to zero. The return value
6643** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6644*/
6645static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6646 unixFile *pFile = (unixFile*)id;
6647 int rc = proxyTakeConch(pFile);
6648 if( rc==SQLITE_OK ){
6649 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006650 if( pCtx->conchHeld>0 ){
6651 unixFile *proxy = pCtx->lockProxy;
6652 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6653 }else{ /* conchHeld < 0 is lockless */
6654 pResOut=0;
6655 }
drh715ff302008-12-03 22:32:44 +00006656 }
6657 return rc;
6658}
6659
6660/*
drh308c2a52010-05-14 11:30:18 +00006661** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006662** of the following:
6663**
6664** (1) SHARED_LOCK
6665** (2) RESERVED_LOCK
6666** (3) PENDING_LOCK
6667** (4) EXCLUSIVE_LOCK
6668**
6669** Sometimes when requesting one lock state, additional lock states
6670** are inserted in between. The locking might fail on one of the later
6671** transitions leaving the lock state different from what it started but
6672** still short of its goal. The following chart shows the allowed
6673** transitions and the inserted intermediate states:
6674**
6675** UNLOCKED -> SHARED
6676** SHARED -> RESERVED
6677** SHARED -> (PENDING) -> EXCLUSIVE
6678** RESERVED -> (PENDING) -> EXCLUSIVE
6679** PENDING -> EXCLUSIVE
6680**
6681** This routine will only increase a lock. Use the sqlite3OsUnlock()
6682** routine to lower a locking level.
6683*/
drh308c2a52010-05-14 11:30:18 +00006684static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006685 unixFile *pFile = (unixFile*)id;
6686 int rc = proxyTakeConch(pFile);
6687 if( rc==SQLITE_OK ){
6688 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006689 if( pCtx->conchHeld>0 ){
6690 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006691 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6692 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006693 }else{
6694 /* conchHeld < 0 is lockless */
6695 }
drh715ff302008-12-03 22:32:44 +00006696 }
6697 return rc;
6698}
6699
6700
6701/*
drh308c2a52010-05-14 11:30:18 +00006702** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006703** must be either NO_LOCK or SHARED_LOCK.
6704**
6705** If the locking level of the file descriptor is already at or below
6706** the requested locking level, this routine is a no-op.
6707*/
drh308c2a52010-05-14 11:30:18 +00006708static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006709 unixFile *pFile = (unixFile*)id;
6710 int rc = proxyTakeConch(pFile);
6711 if( rc==SQLITE_OK ){
6712 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006713 if( pCtx->conchHeld>0 ){
6714 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006715 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6716 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006717 }else{
6718 /* conchHeld < 0 is lockless */
6719 }
drh715ff302008-12-03 22:32:44 +00006720 }
6721 return rc;
6722}
6723
6724/*
6725** Close a file that uses proxy locks.
6726*/
6727static int proxyClose(sqlite3_file *id) {
6728 if( id ){
6729 unixFile *pFile = (unixFile*)id;
6730 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6731 unixFile *lockProxy = pCtx->lockProxy;
6732 unixFile *conchFile = pCtx->conchFile;
6733 int rc = SQLITE_OK;
6734
6735 if( lockProxy ){
6736 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6737 if( rc ) return rc;
6738 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6739 if( rc ) return rc;
6740 sqlite3_free(lockProxy);
6741 pCtx->lockProxy = 0;
6742 }
6743 if( conchFile ){
6744 if( pCtx->conchHeld ){
6745 rc = proxyReleaseConch(pFile);
6746 if( rc ) return rc;
6747 }
6748 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6749 if( rc ) return rc;
6750 sqlite3_free(conchFile);
6751 }
drhd56b1212010-08-11 06:14:15 +00006752 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006753 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006754 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006755 /* restore the original locking context and pMethod then close it */
6756 pFile->lockingContext = pCtx->oldLockingContext;
6757 pFile->pMethod = pCtx->pOldMethod;
6758 sqlite3_free(pCtx);
6759 return pFile->pMethod->xClose(id);
6760 }
6761 return SQLITE_OK;
6762}
6763
6764
6765
drhd2cb50b2009-01-09 21:41:17 +00006766#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006767/*
6768** The proxy locking style is intended for use with AFP filesystems.
6769** And since AFP is only supported on MacOSX, the proxy locking is also
6770** restricted to MacOSX.
6771**
6772**
6773******************* End of the proxy lock implementation **********************
6774******************************************************************************/
6775
drh734c9862008-11-28 15:37:20 +00006776/*
danielk1977e339d652008-06-28 11:23:00 +00006777** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006778**
6779** This routine registers all VFS implementations for unix-like operating
6780** systems. This routine, and the sqlite3_os_end() routine that follows,
6781** should be the only routines in this file that are visible from other
6782** files.
drh6b9d6dd2008-12-03 19:34:47 +00006783**
6784** This routine is called once during SQLite initialization and by a
6785** single thread. The memory allocation and mutex subsystems have not
6786** necessarily been initialized when this routine is called, and so they
6787** should not be used.
drh153c62c2007-08-24 03:51:33 +00006788*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006789int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006790 /*
6791 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006792 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6793 ** to the "finder" function. (pAppData is a pointer to a pointer because
6794 ** silly C90 rules prohibit a void* from being cast to a function pointer
6795 ** and so we have to go through the intermediate pointer to avoid problems
6796 ** when compiling with -pedantic-errors on GCC.)
6797 **
6798 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006799 ** finder-function. The finder-function returns a pointer to the
6800 ** sqlite_io_methods object that implements the desired locking
6801 ** behaviors. See the division above that contains the IOMETHODS
6802 ** macro for addition information on finder-functions.
6803 **
6804 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6805 ** object. But the "autolockIoFinder" available on MacOSX does a little
6806 ** more than that; it looks at the filesystem type that hosts the
6807 ** database file and tries to choose an locking method appropriate for
6808 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006809 */
drh7708e972008-11-29 00:56:52 +00006810 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006811 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006812 sizeof(unixFile), /* szOsFile */ \
6813 MAX_PATHNAME, /* mxPathname */ \
6814 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006815 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006816 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006817 unixOpen, /* xOpen */ \
6818 unixDelete, /* xDelete */ \
6819 unixAccess, /* xAccess */ \
6820 unixFullPathname, /* xFullPathname */ \
6821 unixDlOpen, /* xDlOpen */ \
6822 unixDlError, /* xDlError */ \
6823 unixDlSym, /* xDlSym */ \
6824 unixDlClose, /* xDlClose */ \
6825 unixRandomness, /* xRandomness */ \
6826 unixSleep, /* xSleep */ \
6827 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006828 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006829 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006830 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006831 unixGetSystemCall, /* xGetSystemCall */ \
6832 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006833 }
6834
drh6b9d6dd2008-12-03 19:34:47 +00006835 /*
6836 ** All default VFSes for unix are contained in the following array.
6837 **
6838 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6839 ** by the SQLite core when the VFS is registered. So the following
6840 ** array cannot be const.
6841 */
danielk1977e339d652008-06-28 11:23:00 +00006842 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006843#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006844 UNIXVFS("unix", autolockIoFinder ),
6845#else
6846 UNIXVFS("unix", posixIoFinder ),
6847#endif
6848 UNIXVFS("unix-none", nolockIoFinder ),
6849 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006850 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006851#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006852 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006853#endif
6854#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006855 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006856#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006857 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006858#endif
chw78a13182009-04-07 05:35:03 +00006859#endif
drhd2cb50b2009-01-09 21:41:17 +00006860#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006861 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006862 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006863 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006864#endif
drh153c62c2007-08-24 03:51:33 +00006865 };
drh6b9d6dd2008-12-03 19:34:47 +00006866 unsigned int i; /* Loop counter */
6867
drh2aa5a002011-04-13 13:42:25 +00006868 /* Double-check that the aSyscall[] array has been constructed
6869 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh8c815d12012-02-13 20:16:37 +00006870 assert( ArraySize(aSyscall)==22 );
drh2aa5a002011-04-13 13:42:25 +00006871
drh6b9d6dd2008-12-03 19:34:47 +00006872 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006873 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006874 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006875 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006876 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006877}
danielk1977e339d652008-06-28 11:23:00 +00006878
6879/*
drh6b9d6dd2008-12-03 19:34:47 +00006880** Shutdown the operating system interface.
6881**
6882** Some operating systems might need to do some cleanup in this routine,
6883** to release dynamically allocated objects. But not on unix.
6884** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006885*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006886int sqlite3_os_end(void){
6887 return SQLITE_OK;
6888}
drhdce8bdb2007-08-16 13:01:44 +00006889
danielk197729bafea2008-06-26 10:41:19 +00006890#endif /* SQLITE_OS_UNIX */