blob: 0852eb1a891f620aae1f998b06efb9a30b8e2d91 [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;
drhc1fd2cf2012-10-01 12:16:26 +00003013 assert( cnt==(cnt&0x1ffff) );
3014 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003015 do{
drh734c9862008-11-28 15:37:20 +00003016#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003017 got = osPread(id->h, pBuf, cnt, offset);
3018 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003019#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003020 got = osPread64(id->h, pBuf, cnt, offset);
3021 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003022#else
drh58024642011-11-07 18:16:00 +00003023 newOffset = lseek(id->h, offset, SEEK_SET);
3024 SimulateIOError( newOffset-- );
3025 if( newOffset!=offset ){
3026 if( newOffset == -1 ){
3027 ((unixFile*)id)->lastErrno = errno;
3028 }else{
drhf2f105d2012-08-20 15:53:54 +00003029 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003030 }
3031 return -1;
drh734c9862008-11-28 15:37:20 +00003032 }
drh58024642011-11-07 18:16:00 +00003033 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003034#endif
drh58024642011-11-07 18:16:00 +00003035 if( got==cnt ) break;
3036 if( got<0 ){
3037 if( errno==EINTR ){ got = 1; continue; }
3038 prior = 0;
3039 ((unixFile*)id)->lastErrno = errno;
3040 break;
3041 }else if( got>0 ){
3042 cnt -= got;
3043 offset += got;
3044 prior += got;
3045 pBuf = (void*)(got + (char*)pBuf);
3046 }
3047 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003048 TIMER_END;
drh58024642011-11-07 18:16:00 +00003049 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3050 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3051 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003052}
3053
3054/*
drh734c9862008-11-28 15:37:20 +00003055** Read data from a file into a buffer. Return SQLITE_OK if all
3056** bytes were read successfully and SQLITE_IOERR if anything goes
3057** wrong.
drh339eb0b2008-03-07 15:34:11 +00003058*/
drh734c9862008-11-28 15:37:20 +00003059static int unixRead(
3060 sqlite3_file *id,
3061 void *pBuf,
3062 int amt,
3063 sqlite3_int64 offset
3064){
dan08da86a2009-08-21 17:18:03 +00003065 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003066 int got;
3067 assert( id );
drh08c6d442009-02-09 17:34:07 +00003068
dan08da86a2009-08-21 17:18:03 +00003069 /* If this is a database file (not a journal, master-journal or temp
3070 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003071#if 0
dane946c392009-08-22 11:39:46 +00003072 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003073 || offset>=PENDING_BYTE+512
3074 || offset+amt<=PENDING_BYTE
3075 );
dan7c246102010-04-12 19:00:29 +00003076#endif
drh08c6d442009-02-09 17:34:07 +00003077
dan08da86a2009-08-21 17:18:03 +00003078 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003079 if( got==amt ){
3080 return SQLITE_OK;
3081 }else if( got<0 ){
3082 /* lastErrno set by seekAndRead */
3083 return SQLITE_IOERR_READ;
3084 }else{
dan08da86a2009-08-21 17:18:03 +00003085 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003086 /* Unread parts of the buffer must be zero-filled */
3087 memset(&((char*)pBuf)[got], 0, amt-got);
3088 return SQLITE_IOERR_SHORT_READ;
3089 }
3090}
3091
3092/*
3093** Seek to the offset in id->offset then read cnt bytes into pBuf.
3094** Return the number of bytes actually read. Update the offset.
3095**
3096** To avoid stomping the errno value on a failed write the lastErrno value
3097** is set before returning.
3098*/
3099static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3100 int got;
drh7ed97b92010-01-20 13:07:21 +00003101#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003102 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003103#endif
drhc1fd2cf2012-10-01 12:16:26 +00003104 assert( cnt==(cnt&0x1ffff) );
3105 cnt &= 0x1ffff;
drh734c9862008-11-28 15:37:20 +00003106 TIMER_START;
3107#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003108 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003109#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003110 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003111#else
drhbd1e50c2011-08-19 14:54:12 +00003112 do{
3113 newOffset = lseek(id->h, offset, SEEK_SET);
3114 SimulateIOError( newOffset-- );
3115 if( newOffset!=offset ){
3116 if( newOffset == -1 ){
3117 ((unixFile*)id)->lastErrno = errno;
3118 }else{
drhf2f105d2012-08-20 15:53:54 +00003119 ((unixFile*)id)->lastErrno = 0;
drhbd1e50c2011-08-19 14:54:12 +00003120 }
3121 return -1;
drh734c9862008-11-28 15:37:20 +00003122 }
drhbd1e50c2011-08-19 14:54:12 +00003123 got = osWrite(id->h, pBuf, cnt);
3124 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003125#endif
3126 TIMER_END;
3127 if( got<0 ){
3128 ((unixFile*)id)->lastErrno = errno;
3129 }
3130
drh308c2a52010-05-14 11:30:18 +00003131 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003132 return got;
3133}
3134
3135
3136/*
3137** Write data from a buffer into a file. Return SQLITE_OK on success
3138** or some other error code on failure.
3139*/
3140static int unixWrite(
3141 sqlite3_file *id,
3142 const void *pBuf,
3143 int amt,
3144 sqlite3_int64 offset
3145){
dan08da86a2009-08-21 17:18:03 +00003146 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003147 int wrote = 0;
3148 assert( id );
3149 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003150
dan08da86a2009-08-21 17:18:03 +00003151 /* If this is a database file (not a journal, master-journal or temp
3152 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003153#if 0
dane946c392009-08-22 11:39:46 +00003154 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003155 || offset>=PENDING_BYTE+512
3156 || offset+amt<=PENDING_BYTE
3157 );
dan7c246102010-04-12 19:00:29 +00003158#endif
drh08c6d442009-02-09 17:34:07 +00003159
drhd3d8c042012-05-29 17:02:40 +00003160#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003161 /* If we are doing a normal write to a database file (as opposed to
3162 ** doing a hot-journal rollback or a write to some file other than a
3163 ** normal database file) then record the fact that the database
3164 ** has changed. If the transaction counter is modified, record that
3165 ** fact too.
3166 */
dan08da86a2009-08-21 17:18:03 +00003167 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003168 pFile->dbUpdate = 1; /* The database has been modified */
3169 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003170 int rc;
drh8f941bc2009-01-14 23:03:40 +00003171 char oldCntr[4];
3172 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003173 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003174 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003175 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003176 pFile->transCntrChng = 1; /* The transaction counter has changed */
3177 }
3178 }
3179 }
3180#endif
3181
dan08da86a2009-08-21 17:18:03 +00003182 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003183 amt -= wrote;
3184 offset += wrote;
3185 pBuf = &((char*)pBuf)[wrote];
3186 }
3187 SimulateIOError(( wrote=(-1), amt=1 ));
3188 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003189
drh734c9862008-11-28 15:37:20 +00003190 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003191 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003192 /* lastErrno set by seekAndWrite */
3193 return SQLITE_IOERR_WRITE;
3194 }else{
dan08da86a2009-08-21 17:18:03 +00003195 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003196 return SQLITE_FULL;
3197 }
3198 }
dan6e09d692010-07-27 18:34:15 +00003199
drh734c9862008-11-28 15:37:20 +00003200 return SQLITE_OK;
3201}
3202
3203#ifdef SQLITE_TEST
3204/*
3205** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003206** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003207*/
3208int sqlite3_sync_count = 0;
3209int sqlite3_fullsync_count = 0;
3210#endif
3211
3212/*
drh89240432009-03-25 01:06:01 +00003213** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003214** Others do no. To be safe, we will stick with the (slightly slower)
3215** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003216** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003217*/
drh20f8e132011-08-31 21:01:55 +00003218#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003219# define fdatasync fsync
3220#endif
3221
3222/*
3223** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3224** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3225** only available on Mac OS X. But that could change.
3226*/
3227#ifdef F_FULLFSYNC
3228# define HAVE_FULLFSYNC 1
3229#else
3230# define HAVE_FULLFSYNC 0
3231#endif
3232
3233
3234/*
3235** The fsync() system call does not work as advertised on many
3236** unix systems. The following procedure is an attempt to make
3237** it work better.
3238**
3239** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3240** for testing when we want to run through the test suite quickly.
3241** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3242** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3243** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003244**
3245** SQLite sets the dataOnly flag if the size of the file is unchanged.
3246** The idea behind dataOnly is that it should only write the file content
3247** to disk, not the inode. We only set dataOnly if the file size is
3248** unchanged since the file size is part of the inode. However,
3249** Ted Ts'o tells us that fdatasync() will also write the inode if the
3250** file size has changed. The only real difference between fdatasync()
3251** and fsync(), Ted tells us, is that fdatasync() will not flush the
3252** inode if the mtime or owner or other inode attributes have changed.
3253** We only care about the file size, not the other file attributes, so
3254** as far as SQLite is concerned, an fdatasync() is always adequate.
3255** So, we always use fdatasync() if it is available, regardless of
3256** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003257*/
3258static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003259 int rc;
drh734c9862008-11-28 15:37:20 +00003260
3261 /* The following "ifdef/elif/else/" block has the same structure as
3262 ** the one below. It is replicated here solely to avoid cluttering
3263 ** up the real code with the UNUSED_PARAMETER() macros.
3264 */
3265#ifdef SQLITE_NO_SYNC
3266 UNUSED_PARAMETER(fd);
3267 UNUSED_PARAMETER(fullSync);
3268 UNUSED_PARAMETER(dataOnly);
3269#elif HAVE_FULLFSYNC
3270 UNUSED_PARAMETER(dataOnly);
3271#else
3272 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003273 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003274#endif
3275
3276 /* Record the number of times that we do a normal fsync() and
3277 ** FULLSYNC. This is used during testing to verify that this procedure
3278 ** gets called with the correct arguments.
3279 */
3280#ifdef SQLITE_TEST
3281 if( fullSync ) sqlite3_fullsync_count++;
3282 sqlite3_sync_count++;
3283#endif
3284
3285 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3286 ** no-op
3287 */
3288#ifdef SQLITE_NO_SYNC
3289 rc = SQLITE_OK;
3290#elif HAVE_FULLFSYNC
3291 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003292 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003293 }else{
3294 rc = 1;
3295 }
3296 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003297 ** It shouldn't be possible for fullfsync to fail on the local
3298 ** file system (on OSX), so failure indicates that FULLFSYNC
3299 ** isn't supported for this file system. So, attempt an fsync
3300 ** and (for now) ignore the overhead of a superfluous fcntl call.
3301 ** It'd be better to detect fullfsync support once and avoid
3302 ** the fcntl call every time sync is called.
3303 */
drh734c9862008-11-28 15:37:20 +00003304 if( rc ) rc = fsync(fd);
3305
drh7ed97b92010-01-20 13:07:21 +00003306#elif defined(__APPLE__)
3307 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3308 ** so currently we default to the macro that redefines fdatasync to fsync
3309 */
3310 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003311#else
drh0b647ff2009-03-21 14:41:04 +00003312 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003313#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003314 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003315 rc = fsync(fd);
3316 }
drh0b647ff2009-03-21 14:41:04 +00003317#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003318#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3319
3320 if( OS_VXWORKS && rc!= -1 ){
3321 rc = 0;
3322 }
chw97185482008-11-17 08:05:31 +00003323 return rc;
drhbfe66312006-10-03 17:40:40 +00003324}
3325
drh734c9862008-11-28 15:37:20 +00003326/*
drh0059eae2011-08-08 23:48:40 +00003327** Open a file descriptor to the directory containing file zFilename.
3328** If successful, *pFd is set to the opened file descriptor and
3329** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3330** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3331** value.
3332**
drh90315a22011-08-10 01:52:12 +00003333** The directory file descriptor is used for only one thing - to
3334** fsync() a directory to make sure file creation and deletion events
3335** are flushed to disk. Such fsyncs are not needed on newer
3336** journaling filesystems, but are required on older filesystems.
3337**
3338** This routine can be overridden using the xSetSysCall interface.
3339** The ability to override this routine was added in support of the
3340** chromium sandbox. Opening a directory is a security risk (we are
3341** told) so making it overrideable allows the chromium sandbox to
3342** replace this routine with a harmless no-op. To make this routine
3343** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3344** *pFd set to a negative number.
3345**
drh0059eae2011-08-08 23:48:40 +00003346** If SQLITE_OK is returned, the caller is responsible for closing
3347** the file descriptor *pFd using close().
3348*/
3349static int openDirectory(const char *zFilename, int *pFd){
3350 int ii;
3351 int fd = -1;
3352 char zDirname[MAX_PATHNAME+1];
3353
3354 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3355 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3356 if( ii>0 ){
3357 zDirname[ii] = '\0';
3358 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3359 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003360 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3361 }
3362 }
3363 *pFd = fd;
3364 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3365}
3366
3367/*
drh734c9862008-11-28 15:37:20 +00003368** Make sure all writes to a particular file are committed to disk.
3369**
3370** If dataOnly==0 then both the file itself and its metadata (file
3371** size, access time, etc) are synced. If dataOnly!=0 then only the
3372** file data is synced.
3373**
3374** Under Unix, also make sure that the directory entry for the file
3375** has been created by fsync-ing the directory that contains the file.
3376** If we do not do this and we encounter a power failure, the directory
3377** entry for the journal might not exist after we reboot. The next
3378** SQLite to access the file will not know that the journal exists (because
3379** the directory entry for the journal was never created) and the transaction
3380** will not roll back - possibly leading to database corruption.
3381*/
3382static int unixSync(sqlite3_file *id, int flags){
3383 int rc;
3384 unixFile *pFile = (unixFile*)id;
3385
3386 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3387 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3388
3389 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3390 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3391 || (flags&0x0F)==SQLITE_SYNC_FULL
3392 );
3393
3394 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3395 ** line is to test that doing so does not cause any problems.
3396 */
3397 SimulateDiskfullError( return SQLITE_FULL );
3398
3399 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003400 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003401 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3402 SimulateIOError( rc=1 );
3403 if( rc ){
3404 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003405 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003406 }
drh0059eae2011-08-08 23:48:40 +00003407
3408 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003409 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3410 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003411 */
3412 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3413 int dirfd;
3414 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003415 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003416 rc = osOpenDirectory(pFile->zPath, &dirfd);
3417 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003418 full_fsync(dirfd, 0, 0);
3419 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003420 }else if( rc==SQLITE_CANTOPEN ){
3421 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003422 }
drh0059eae2011-08-08 23:48:40 +00003423 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003424 }
3425 return rc;
3426}
3427
3428/*
3429** Truncate an open file to a specified size
3430*/
3431static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003432 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003433 int rc;
dan6e09d692010-07-27 18:34:15 +00003434 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003435 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003436
3437 /* If the user has configured a chunk-size for this file, truncate the
3438 ** file so that it consists of an integer number of chunks (i.e. the
3439 ** actual file size after the operation may be larger than the requested
3440 ** size).
3441 */
drhb8af4b72012-04-05 20:04:39 +00003442 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003443 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3444 }
3445
drhff812312011-02-23 13:33:46 +00003446 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003447 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003448 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003449 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003450 }else{
drhd3d8c042012-05-29 17:02:40 +00003451#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003452 /* If we are doing a normal write to a database file (as opposed to
3453 ** doing a hot-journal rollback or a write to some file other than a
3454 ** normal database file) and we truncate the file to zero length,
3455 ** that effectively updates the change counter. This might happen
3456 ** when restoring a database using the backup API from a zero-length
3457 ** source.
3458 */
dan6e09d692010-07-27 18:34:15 +00003459 if( pFile->inNormalWrite && nByte==0 ){
3460 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003461 }
3462#endif
3463
drh734c9862008-11-28 15:37:20 +00003464 return SQLITE_OK;
3465 }
3466}
3467
3468/*
3469** Determine the current size of a file in bytes
3470*/
3471static int unixFileSize(sqlite3_file *id, i64 *pSize){
3472 int rc;
3473 struct stat buf;
3474 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003475 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003476 SimulateIOError( rc=1 );
3477 if( rc!=0 ){
3478 ((unixFile*)id)->lastErrno = errno;
3479 return SQLITE_IOERR_FSTAT;
3480 }
3481 *pSize = buf.st_size;
3482
drh8af6c222010-05-14 12:43:01 +00003483 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003484 ** writes a single byte into that file in order to work around a bug
3485 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3486 ** layers, we need to report this file size as zero even though it is
3487 ** really 1. Ticket #3260.
3488 */
3489 if( *pSize==1 ) *pSize = 0;
3490
3491
3492 return SQLITE_OK;
3493}
3494
drhd2cb50b2009-01-09 21:41:17 +00003495#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003496/*
3497** Handler for proxy-locking file-control verbs. Defined below in the
3498** proxying locking division.
3499*/
3500static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003501#endif
drh715ff302008-12-03 22:32:44 +00003502
dan502019c2010-07-28 14:26:17 +00003503/*
3504** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003505** file-control operation. Enlarge the database to nBytes in size
3506** (rounded up to the next chunk-size). If the database is already
3507** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003508*/
3509static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003510 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003511 i64 nSize; /* Required file size */
3512 struct stat buf; /* Used to hold return values of fstat() */
3513
drh99ab3b12011-03-02 15:09:07 +00003514 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003515
3516 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3517 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003518
dan502019c2010-07-28 14:26:17 +00003519#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003520 /* The code below is handling the return value of osFallocate()
3521 ** correctly. posix_fallocate() is defined to "returns zero on success,
3522 ** or an error number on failure". See the manpage for details. */
3523 int err;
drhff812312011-02-23 13:33:46 +00003524 do{
dan661d71a2011-03-30 19:08:03 +00003525 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3526 }while( err==EINTR );
3527 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003528#else
3529 /* If the OS does not have posix_fallocate(), fake it. First use
3530 ** ftruncate() to set the file size, then write a single byte to
3531 ** the last byte in each block within the extended region. This
3532 ** is the same technique used by glibc to implement posix_fallocate()
3533 ** on systems that do not have a real fallocate() system call.
3534 */
3535 int nBlk = buf.st_blksize; /* File-system block size */
3536 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003537
drhff812312011-02-23 13:33:46 +00003538 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003539 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003540 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003541 }
3542 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003543 while( iWrite<nSize ){
3544 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3545 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003546 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003547 }
dan502019c2010-07-28 14:26:17 +00003548#endif
3549 }
3550 }
3551
3552 return SQLITE_OK;
3553}
danielk1977ad94b582007-08-20 06:44:22 +00003554
danielk1977e3026632004-06-22 11:29:02 +00003555/*
drhf12b3f62011-12-21 14:42:29 +00003556** If *pArg is inititially negative then this is a query. Set *pArg to
3557** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3558**
3559** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3560*/
3561static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3562 if( *pArg<0 ){
3563 *pArg = (pFile->ctrlFlags & mask)!=0;
3564 }else if( (*pArg)==0 ){
3565 pFile->ctrlFlags &= ~mask;
3566 }else{
3567 pFile->ctrlFlags |= mask;
3568 }
3569}
3570
3571/*
drh9e33c2c2007-08-31 18:34:59 +00003572** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003573*/
drhcc6bb3e2007-08-31 16:11:35 +00003574static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003575 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003576 switch( op ){
3577 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003578 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003579 return SQLITE_OK;
3580 }
drh7708e972008-11-29 00:56:52 +00003581 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003582 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003583 return SQLITE_OK;
3584 }
dan6e09d692010-07-27 18:34:15 +00003585 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003586 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003587 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003588 }
drh9ff27ec2010-05-19 19:26:05 +00003589 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003590 int rc;
3591 SimulateIOErrorBenign(1);
3592 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3593 SimulateIOErrorBenign(0);
3594 return rc;
drhf0b190d2011-07-26 16:03:07 +00003595 }
3596 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003597 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3598 return SQLITE_OK;
3599 }
drhcb15f352011-12-23 01:04:17 +00003600 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3601 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003602 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003603 }
drhde60fc22011-12-14 17:53:36 +00003604 case SQLITE_FCNTL_VFSNAME: {
3605 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3606 return SQLITE_OK;
3607 }
drhd3d8c042012-05-29 17:02:40 +00003608#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003609 /* The pager calls this method to signal that it has done
3610 ** a rollback and that the database is therefore unchanged and
3611 ** it hence it is OK for the transaction change counter to be
3612 ** unchanged.
3613 */
3614 case SQLITE_FCNTL_DB_UNCHANGED: {
3615 ((unixFile*)id)->dbUpdate = 0;
3616 return SQLITE_OK;
3617 }
3618#endif
drhd2cb50b2009-01-09 21:41:17 +00003619#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003620 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003621 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003622 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003623 }
drhd2cb50b2009-01-09 21:41:17 +00003624#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003625 }
drh0b52b7d2011-01-26 19:46:22 +00003626 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003627}
3628
3629/*
danielk1977a3d4c882007-03-23 10:08:38 +00003630** Return the sector size in bytes of the underlying block device for
3631** the specified file. This is almost always 512 bytes, but may be
3632** larger for some devices.
3633**
3634** SQLite code assumes this function cannot fail. It also assumes that
3635** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003636** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003637** same for both.
3638*/
drh1da88f02011-12-17 16:09:16 +00003639static int unixSectorSize(sqlite3_file *pFile){
drh8942d412012-01-02 18:20:14 +00003640 (void)pFile;
3641 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003642}
3643
danielk197790949c22007-08-17 16:50:38 +00003644/*
drhf12b3f62011-12-21 14:42:29 +00003645** Return the device characteristics for the file.
3646**
drhcb15f352011-12-23 01:04:17 +00003647** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3648** However, that choice is contraversial since technically the underlying
3649** file system does not always provide powersafe overwrites. (In other
3650** words, after a power-loss event, parts of the file that were never
3651** written might end up being altered.) However, non-PSOW behavior is very,
3652** very rare. And asserting PSOW makes a large reduction in the amount
3653** of required I/O for journaling, since a lot of padding is eliminated.
3654** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3655** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003656*/
drhf12b3f62011-12-21 14:42:29 +00003657static int unixDeviceCharacteristics(sqlite3_file *id){
3658 unixFile *p = (unixFile*)id;
drhcb15f352011-12-23 01:04:17 +00003659 if( p->ctrlFlags & UNIXFILE_PSOW ){
3660 return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3661 }else{
3662 return 0;
3663 }
danielk197762079062007-08-15 17:08:46 +00003664}
3665
drhd9e5c4f2010-05-12 18:01:39 +00003666#ifndef SQLITE_OMIT_WAL
3667
3668
3669/*
drhd91c68f2010-05-14 14:52:25 +00003670** Object used to represent an shared memory buffer.
3671**
3672** When multiple threads all reference the same wal-index, each thread
3673** has its own unixShm object, but they all point to a single instance
3674** of this unixShmNode object. In other words, each wal-index is opened
3675** only once per process.
3676**
3677** Each unixShmNode object is connected to a single unixInodeInfo object.
3678** We could coalesce this object into unixInodeInfo, but that would mean
3679** every open file that does not use shared memory (in other words, most
3680** open files) would have to carry around this extra information. So
3681** the unixInodeInfo object contains a pointer to this unixShmNode object
3682** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003683**
3684** unixMutexHeld() must be true when creating or destroying
3685** this object or while reading or writing the following fields:
3686**
3687** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003688**
3689** The following fields are read-only after the object is created:
3690**
3691** fid
3692** zFilename
3693**
drhd91c68f2010-05-14 14:52:25 +00003694** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003695** unixMutexHeld() is true when reading or writing any other field
3696** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003697*/
drhd91c68f2010-05-14 14:52:25 +00003698struct unixShmNode {
3699 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003700 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003701 char *zFilename; /* Name of the mmapped file */
3702 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003703 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003704 u16 nRegion; /* Size of array apRegion */
3705 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003706 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003707 int nRef; /* Number of unixShm objects pointing to this */
3708 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003709#ifdef SQLITE_DEBUG
3710 u8 exclMask; /* Mask of exclusive locks held */
3711 u8 sharedMask; /* Mask of shared locks held */
3712 u8 nextShmId; /* Next available unixShm.id value */
3713#endif
3714};
3715
3716/*
drhd9e5c4f2010-05-12 18:01:39 +00003717** Structure used internally by this VFS to record the state of an
3718** open shared memory connection.
3719**
drhd91c68f2010-05-14 14:52:25 +00003720** The following fields are initialized when this object is created and
3721** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003722**
drhd91c68f2010-05-14 14:52:25 +00003723** unixShm.pFile
3724** unixShm.id
3725**
3726** All other fields are read/write. The unixShm.pFile->mutex must be held
3727** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003728*/
3729struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003730 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3731 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003732 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003733 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003734 u16 sharedMask; /* Mask of shared locks held */
3735 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003736};
3737
3738/*
drhd9e5c4f2010-05-12 18:01:39 +00003739** Constants used for locking
3740*/
drhbd9676c2010-06-23 17:58:38 +00003741#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003742#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003743
drhd9e5c4f2010-05-12 18:01:39 +00003744/*
drh73b64e42010-05-30 19:55:15 +00003745** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003746**
3747** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3748** otherwise.
3749*/
3750static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003751 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3752 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003753 int ofst, /* First byte of the locking range */
3754 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003755){
3756 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003757 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003758
drhd91c68f2010-05-14 14:52:25 +00003759 /* Access to the unixShmNode object is serialized by the caller */
3760 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003761
drh73b64e42010-05-30 19:55:15 +00003762 /* Shared locks never span more than one byte */
3763 assert( n==1 || lockType!=F_RDLCK );
3764
3765 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003766 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003767
drh3cb93392011-03-12 18:10:44 +00003768 if( pShmNode->h>=0 ){
3769 /* Initialize the locking parameters */
3770 memset(&f, 0, sizeof(f));
3771 f.l_type = lockType;
3772 f.l_whence = SEEK_SET;
3773 f.l_start = ofst;
3774 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003775
drh3cb93392011-03-12 18:10:44 +00003776 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3777 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3778 }
drhd9e5c4f2010-05-12 18:01:39 +00003779
3780 /* Update the global lock state and do debug tracing */
3781#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003782 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003783 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003784 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003785 if( rc==SQLITE_OK ){
3786 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003787 OSTRACE(("unlock %d ok", ofst));
3788 pShmNode->exclMask &= ~mask;
3789 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003790 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003791 OSTRACE(("read-lock %d ok", ofst));
3792 pShmNode->exclMask &= ~mask;
3793 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003794 }else{
3795 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003796 OSTRACE(("write-lock %d ok", ofst));
3797 pShmNode->exclMask |= mask;
3798 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003799 }
3800 }else{
3801 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003802 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003803 }else if( lockType==F_RDLCK ){
3804 OSTRACE(("read-lock failed"));
3805 }else{
3806 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003807 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003808 }
3809 }
drh20e1f082010-05-31 16:10:12 +00003810 OSTRACE((" - afterwards %03x,%03x\n",
3811 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003812 }
drhd9e5c4f2010-05-12 18:01:39 +00003813#endif
3814
3815 return rc;
3816}
3817
drhd9e5c4f2010-05-12 18:01:39 +00003818
3819/*
drhd91c68f2010-05-14 14:52:25 +00003820** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003821**
3822** This is not a VFS shared-memory method; it is a utility function called
3823** by VFS shared-memory methods.
3824*/
drhd91c68f2010-05-14 14:52:25 +00003825static void unixShmPurge(unixFile *pFd){
3826 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003827 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003828 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003829 int i;
drhd91c68f2010-05-14 14:52:25 +00003830 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003831 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003832 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003833 if( p->h>=0 ){
3834 munmap(p->apRegion[i], p->szRegion);
3835 }else{
3836 sqlite3_free(p->apRegion[i]);
3837 }
dan13a3cb82010-06-11 19:04:21 +00003838 }
dan18801912010-06-14 14:07:50 +00003839 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003840 if( p->h>=0 ){
3841 robust_close(pFd, p->h, __LINE__);
3842 p->h = -1;
3843 }
drhd91c68f2010-05-14 14:52:25 +00003844 p->pInode->pShmNode = 0;
3845 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003846 }
3847}
3848
3849/*
danda9fe0c2010-07-13 18:44:03 +00003850** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003851** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003852**
drh7234c6d2010-06-19 15:10:09 +00003853** The file used to implement shared-memory is in the same directory
3854** as the open database file and has the same name as the open database
3855** file with the "-shm" suffix added. For example, if the database file
3856** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003857** for shared memory will be called "/home/user1/config.db-shm".
3858**
3859** Another approach to is to use files in /dev/shm or /dev/tmp or an
3860** some other tmpfs mount. But if a file in a different directory
3861** from the database file is used, then differing access permissions
3862** or a chroot() might cause two different processes on the same
3863** database to end up using different files for shared memory -
3864** meaning that their memory would not really be shared - resulting
3865** in database corruption. Nevertheless, this tmpfs file usage
3866** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3867** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3868** option results in an incompatible build of SQLite; builds of SQLite
3869** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3870** same database file at the same time, database corruption will likely
3871** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3872** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003873**
3874** When opening a new shared-memory file, if no other instances of that
3875** file are currently open, in this process or in other processes, then
3876** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003877**
3878** If the original database file (pDbFd) is using the "unix-excl" VFS
3879** that means that an exclusive lock is held on the database file and
3880** that no other processes are able to read or write the database. In
3881** that case, we do not really need shared memory. No shared memory
3882** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003883*/
danda9fe0c2010-07-13 18:44:03 +00003884static int unixOpenSharedMemory(unixFile *pDbFd){
3885 struct unixShm *p = 0; /* The connection to be opened */
3886 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3887 int rc; /* Result code */
3888 unixInodeInfo *pInode; /* The inode of fd */
3889 char *zShmFilename; /* Name of the file used for SHM */
3890 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003891
danda9fe0c2010-07-13 18:44:03 +00003892 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003893 p = sqlite3_malloc( sizeof(*p) );
3894 if( p==0 ) return SQLITE_NOMEM;
3895 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003896 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003897
danda9fe0c2010-07-13 18:44:03 +00003898 /* Check to see if a unixShmNode object already exists. Reuse an existing
3899 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003900 */
3901 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003902 pInode = pDbFd->pInode;
3903 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003904 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003905 struct stat sStat; /* fstat() info for database file */
3906
3907 /* Call fstat() to figure out the permissions on the database file. If
3908 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00003909 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00003910 */
drh3cb93392011-03-12 18:10:44 +00003911 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003912 rc = SQLITE_IOERR_FSTAT;
3913 goto shm_open_err;
3914 }
3915
drha4ced192010-07-15 18:32:40 +00003916#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00003917 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00003918#else
drh52bcde02012-01-03 14:50:45 +00003919 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003920#endif
drh7234c6d2010-06-19 15:10:09 +00003921 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003922 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003923 rc = SQLITE_NOMEM;
3924 goto shm_open_err;
3925 }
drh9cb5a0d2012-01-05 21:19:54 +00003926 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00003927 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003928#ifdef SQLITE_SHM_DIRECTORY
3929 sqlite3_snprintf(nShmFilename, zShmFilename,
3930 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3931 (u32)sStat.st_ino, (u32)sStat.st_dev);
3932#else
drh7234c6d2010-06-19 15:10:09 +00003933 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003934 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003935#endif
drhd91c68f2010-05-14 14:52:25 +00003936 pShmNode->h = -1;
3937 pDbFd->pInode->pShmNode = pShmNode;
3938 pShmNode->pInode = pDbFd->pInode;
3939 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3940 if( pShmNode->mutex==0 ){
3941 rc = SQLITE_NOMEM;
3942 goto shm_open_err;
3943 }
drhd9e5c4f2010-05-12 18:01:39 +00003944
drh3cb93392011-03-12 18:10:44 +00003945 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003946 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003947 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003948 openFlags = O_RDONLY;
3949 pShmNode->isReadonly = 1;
3950 }
3951 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003952 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00003953 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3954 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003955 }
drhac7c3ac2012-02-11 19:23:48 +00003956
3957 /* If this process is running as root, make sure that the SHM file
3958 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00003959 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00003960 */
drhed466822012-05-31 13:10:49 +00003961 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00003962
3963 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003964 ** If not, truncate the file to zero length.
3965 */
3966 rc = SQLITE_OK;
3967 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3968 if( robust_ftruncate(pShmNode->h, 0) ){
3969 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003970 }
3971 }
drh66dfec8b2011-06-01 20:01:49 +00003972 if( rc==SQLITE_OK ){
3973 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3974 }
3975 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003976 }
drhd9e5c4f2010-05-12 18:01:39 +00003977 }
3978
drhd91c68f2010-05-14 14:52:25 +00003979 /* Make the new connection a child of the unixShmNode */
3980 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003981#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003982 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003983#endif
drhd91c68f2010-05-14 14:52:25 +00003984 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003985 pDbFd->pShm = p;
3986 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003987
3988 /* The reference count on pShmNode has already been incremented under
3989 ** the cover of the unixEnterMutex() mutex and the pointer from the
3990 ** new (struct unixShm) object to the pShmNode has been set. All that is
3991 ** left to do is to link the new object into the linked list starting
3992 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3993 ** mutex.
3994 */
3995 sqlite3_mutex_enter(pShmNode->mutex);
3996 p->pNext = pShmNode->pFirst;
3997 pShmNode->pFirst = p;
3998 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003999 return SQLITE_OK;
4000
4001 /* Jump here on any error */
4002shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004003 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004004 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004005 unixLeaveMutex();
4006 return rc;
4007}
4008
4009/*
danda9fe0c2010-07-13 18:44:03 +00004010** This function is called to obtain a pointer to region iRegion of the
4011** shared-memory associated with the database file fd. Shared-memory regions
4012** are numbered starting from zero. Each shared-memory region is szRegion
4013** bytes in size.
4014**
4015** If an error occurs, an error code is returned and *pp is set to NULL.
4016**
4017** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4018** region has not been allocated (by any client, including one running in a
4019** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4020** bExtend is non-zero and the requested shared-memory region has not yet
4021** been allocated, it is allocated by this function.
4022**
4023** If the shared-memory region has already been allocated or is allocated by
4024** this call as described above, then it is mapped into this processes
4025** address space (if it is not already), *pp is set to point to the mapped
4026** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004027*/
danda9fe0c2010-07-13 18:44:03 +00004028static int unixShmMap(
4029 sqlite3_file *fd, /* Handle open on database file */
4030 int iRegion, /* Region to retrieve */
4031 int szRegion, /* Size of regions */
4032 int bExtend, /* True to extend file if necessary */
4033 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004034){
danda9fe0c2010-07-13 18:44:03 +00004035 unixFile *pDbFd = (unixFile*)fd;
4036 unixShm *p;
4037 unixShmNode *pShmNode;
4038 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004039
danda9fe0c2010-07-13 18:44:03 +00004040 /* If the shared-memory file has not yet been opened, open it now. */
4041 if( pDbFd->pShm==0 ){
4042 rc = unixOpenSharedMemory(pDbFd);
4043 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004044 }
drhd9e5c4f2010-05-12 18:01:39 +00004045
danda9fe0c2010-07-13 18:44:03 +00004046 p = pDbFd->pShm;
4047 pShmNode = p->pShmNode;
4048 sqlite3_mutex_enter(pShmNode->mutex);
4049 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004050 assert( pShmNode->pInode==pDbFd->pInode );
4051 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4052 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004053
4054 if( pShmNode->nRegion<=iRegion ){
4055 char **apNew; /* New apRegion[] array */
4056 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4057 struct stat sStat; /* Used by fstat() */
4058
4059 pShmNode->szRegion = szRegion;
4060
drh3cb93392011-03-12 18:10:44 +00004061 if( pShmNode->h>=0 ){
4062 /* The requested region is not mapped into this processes address space.
4063 ** Check to see if it has been allocated (i.e. if the wal-index file is
4064 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004065 */
drh3cb93392011-03-12 18:10:44 +00004066 if( osFstat(pShmNode->h, &sStat) ){
4067 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004068 goto shmpage_out;
4069 }
drh3cb93392011-03-12 18:10:44 +00004070
4071 if( sStat.st_size<nByte ){
4072 /* The requested memory region does not exist. If bExtend is set to
4073 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4074 **
4075 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4076 ** the requested memory region.
4077 */
4078 if( !bExtend ) goto shmpage_out;
4079 if( robust_ftruncate(pShmNode->h, nByte) ){
4080 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4081 pShmNode->zFilename);
4082 goto shmpage_out;
4083 }
4084 }
danda9fe0c2010-07-13 18:44:03 +00004085 }
4086
4087 /* Map the requested memory region into this processes address space. */
4088 apNew = (char **)sqlite3_realloc(
4089 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4090 );
4091 if( !apNew ){
4092 rc = SQLITE_IOERR_NOMEM;
4093 goto shmpage_out;
4094 }
4095 pShmNode->apRegion = apNew;
4096 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004097 void *pMem;
4098 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004099 pMem = mmap(0, szRegion,
4100 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004101 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4102 );
4103 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004104 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004105 goto shmpage_out;
4106 }
4107 }else{
4108 pMem = sqlite3_malloc(szRegion);
4109 if( pMem==0 ){
4110 rc = SQLITE_NOMEM;
4111 goto shmpage_out;
4112 }
4113 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004114 }
4115 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4116 pShmNode->nRegion++;
4117 }
4118 }
4119
4120shmpage_out:
4121 if( pShmNode->nRegion>iRegion ){
4122 *pp = pShmNode->apRegion[iRegion];
4123 }else{
4124 *pp = 0;
4125 }
drh66dfec8b2011-06-01 20:01:49 +00004126 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004127 sqlite3_mutex_leave(pShmNode->mutex);
4128 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004129}
4130
4131/*
drhd9e5c4f2010-05-12 18:01:39 +00004132** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004133**
4134** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4135** different here than in posix. In xShmLock(), one can go from unlocked
4136** to shared and back or from unlocked to exclusive and back. But one may
4137** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004138*/
4139static int unixShmLock(
4140 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004141 int ofst, /* First lock to acquire or release */
4142 int n, /* Number of locks to acquire or release */
4143 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004144){
drh73b64e42010-05-30 19:55:15 +00004145 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4146 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4147 unixShm *pX; /* For looping over all siblings */
4148 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4149 int rc = SQLITE_OK; /* Result code */
4150 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004151
drhd91c68f2010-05-14 14:52:25 +00004152 assert( pShmNode==pDbFd->pInode->pShmNode );
4153 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004154 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004155 assert( n>=1 );
4156 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4157 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4158 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4159 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4160 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004161 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4162 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004163
drhc99597c2010-05-31 01:41:15 +00004164 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004165 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004166 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004167 if( flags & SQLITE_SHM_UNLOCK ){
4168 u16 allMask = 0; /* Mask of locks held by siblings */
4169
4170 /* See if any siblings hold this same lock */
4171 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4172 if( pX==p ) continue;
4173 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4174 allMask |= pX->sharedMask;
4175 }
4176
4177 /* Unlock the system-level locks */
4178 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004179 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004180 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004181 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004182 }
drh73b64e42010-05-30 19:55:15 +00004183
4184 /* Undo the local locks */
4185 if( rc==SQLITE_OK ){
4186 p->exclMask &= ~mask;
4187 p->sharedMask &= ~mask;
4188 }
4189 }else if( flags & SQLITE_SHM_SHARED ){
4190 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4191
4192 /* Find out which shared locks are already held by sibling connections.
4193 ** If any sibling already holds an exclusive lock, go ahead and return
4194 ** SQLITE_BUSY.
4195 */
4196 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004197 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004198 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004199 break;
4200 }
4201 allShared |= pX->sharedMask;
4202 }
4203
4204 /* Get shared locks at the system level, if necessary */
4205 if( rc==SQLITE_OK ){
4206 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004207 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004208 }else{
drh73b64e42010-05-30 19:55:15 +00004209 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004210 }
drhd9e5c4f2010-05-12 18:01:39 +00004211 }
drh73b64e42010-05-30 19:55:15 +00004212
4213 /* Get the local shared locks */
4214 if( rc==SQLITE_OK ){
4215 p->sharedMask |= mask;
4216 }
4217 }else{
4218 /* Make sure no sibling connections hold locks that will block this
4219 ** lock. If any do, return SQLITE_BUSY right away.
4220 */
4221 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004222 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4223 rc = SQLITE_BUSY;
4224 break;
4225 }
4226 }
4227
4228 /* Get the exclusive locks at the system level. Then if successful
4229 ** also mark the local connection as being locked.
4230 */
4231 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004232 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004233 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004234 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004235 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004236 }
drhd9e5c4f2010-05-12 18:01:39 +00004237 }
4238 }
drhd91c68f2010-05-14 14:52:25 +00004239 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004240 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4241 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004242 return rc;
4243}
4244
drh286a2882010-05-20 23:51:06 +00004245/*
4246** Implement a memory barrier or memory fence on shared memory.
4247**
4248** All loads and stores begun before the barrier must complete before
4249** any load or store begun after the barrier.
4250*/
4251static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004252 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004253){
drhff828942010-06-26 21:34:06 +00004254 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004255 unixEnterMutex();
4256 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004257}
4258
dan18801912010-06-14 14:07:50 +00004259/*
danda9fe0c2010-07-13 18:44:03 +00004260** Close a connection to shared-memory. Delete the underlying
4261** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004262**
4263** If there is no shared memory associated with the connection then this
4264** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004265*/
danda9fe0c2010-07-13 18:44:03 +00004266static int unixShmUnmap(
4267 sqlite3_file *fd, /* The underlying database file */
4268 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004269){
danda9fe0c2010-07-13 18:44:03 +00004270 unixShm *p; /* The connection to be closed */
4271 unixShmNode *pShmNode; /* The underlying shared-memory file */
4272 unixShm **pp; /* For looping over sibling connections */
4273 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004274
danda9fe0c2010-07-13 18:44:03 +00004275 pDbFd = (unixFile*)fd;
4276 p = pDbFd->pShm;
4277 if( p==0 ) return SQLITE_OK;
4278 pShmNode = p->pShmNode;
4279
4280 assert( pShmNode==pDbFd->pInode->pShmNode );
4281 assert( pShmNode->pInode==pDbFd->pInode );
4282
4283 /* Remove connection p from the set of connections associated
4284 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004285 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004286 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4287 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004288
danda9fe0c2010-07-13 18:44:03 +00004289 /* Free the connection p */
4290 sqlite3_free(p);
4291 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004292 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004293
4294 /* If pShmNode->nRef has reached 0, then close the underlying
4295 ** shared-memory file, too */
4296 unixEnterMutex();
4297 assert( pShmNode->nRef>0 );
4298 pShmNode->nRef--;
4299 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004300 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004301 unixShmPurge(pDbFd);
4302 }
4303 unixLeaveMutex();
4304
4305 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004306}
drh286a2882010-05-20 23:51:06 +00004307
danda9fe0c2010-07-13 18:44:03 +00004308
drhd9e5c4f2010-05-12 18:01:39 +00004309#else
drh6b017cc2010-06-14 18:01:46 +00004310# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004311# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004312# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004313# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004314#endif /* #ifndef SQLITE_OMIT_WAL */
4315
drh734c9862008-11-28 15:37:20 +00004316/*
4317** Here ends the implementation of all sqlite3_file methods.
4318**
4319********************** End sqlite3_file Methods *******************************
4320******************************************************************************/
4321
4322/*
drh6b9d6dd2008-12-03 19:34:47 +00004323** This division contains definitions of sqlite3_io_methods objects that
4324** implement various file locking strategies. It also contains definitions
4325** of "finder" functions. A finder-function is used to locate the appropriate
4326** sqlite3_io_methods object for a particular database file. The pAppData
4327** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4328** the correct finder-function for that VFS.
4329**
4330** Most finder functions return a pointer to a fixed sqlite3_io_methods
4331** object. The only interesting finder-function is autolockIoFinder, which
4332** looks at the filesystem type and tries to guess the best locking
4333** strategy from that.
4334**
drh1875f7a2008-12-08 18:19:17 +00004335** For finder-funtion F, two objects are created:
4336**
4337** (1) The real finder-function named "FImpt()".
4338**
dane946c392009-08-22 11:39:46 +00004339** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004340**
4341**
4342** A pointer to the F pointer is used as the pAppData value for VFS
4343** objects. We have to do this instead of letting pAppData point
4344** directly at the finder-function since C90 rules prevent a void*
4345** from be cast into a function pointer.
4346**
drh6b9d6dd2008-12-03 19:34:47 +00004347**
drh7708e972008-11-29 00:56:52 +00004348** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004349**
drh7708e972008-11-29 00:56:52 +00004350** * A constant sqlite3_io_methods object call METHOD that has locking
4351** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4352**
4353** * An I/O method finder function called FINDER that returns a pointer
4354** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004355*/
drhd9e5c4f2010-05-12 18:01:39 +00004356#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004357static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004358 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004359 CLOSE, /* xClose */ \
4360 unixRead, /* xRead */ \
4361 unixWrite, /* xWrite */ \
4362 unixTruncate, /* xTruncate */ \
4363 unixSync, /* xSync */ \
4364 unixFileSize, /* xFileSize */ \
4365 LOCK, /* xLock */ \
4366 UNLOCK, /* xUnlock */ \
4367 CKLOCK, /* xCheckReservedLock */ \
4368 unixFileControl, /* xFileControl */ \
4369 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004370 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004371 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004372 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004373 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004374 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004375}; \
drh0c2694b2009-09-03 16:23:44 +00004376static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4377 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004378 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004379} \
drh0c2694b2009-09-03 16:23:44 +00004380static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004381 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004382
4383/*
4384** Here are all of the sqlite3_io_methods objects for each of the
4385** locking strategies. Functions that return pointers to these methods
4386** are also created.
4387*/
4388IOMETHODS(
4389 posixIoFinder, /* Finder function name */
4390 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004391 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004392 unixClose, /* xClose method */
4393 unixLock, /* xLock method */
4394 unixUnlock, /* xUnlock method */
4395 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004396)
drh7708e972008-11-29 00:56:52 +00004397IOMETHODS(
4398 nolockIoFinder, /* Finder function name */
4399 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004400 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004401 nolockClose, /* xClose method */
4402 nolockLock, /* xLock method */
4403 nolockUnlock, /* xUnlock method */
4404 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004405)
drh7708e972008-11-29 00:56:52 +00004406IOMETHODS(
4407 dotlockIoFinder, /* Finder function name */
4408 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004409 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004410 dotlockClose, /* xClose method */
4411 dotlockLock, /* xLock method */
4412 dotlockUnlock, /* xUnlock method */
4413 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004414)
drh7708e972008-11-29 00:56:52 +00004415
chw78a13182009-04-07 05:35:03 +00004416#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004417IOMETHODS(
4418 flockIoFinder, /* Finder function name */
4419 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004420 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004421 flockClose, /* xClose method */
4422 flockLock, /* xLock method */
4423 flockUnlock, /* xUnlock method */
4424 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004425)
drh7708e972008-11-29 00:56:52 +00004426#endif
4427
drh6c7d5c52008-11-21 20:32:33 +00004428#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004429IOMETHODS(
4430 semIoFinder, /* Finder function name */
4431 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004432 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004433 semClose, /* xClose method */
4434 semLock, /* xLock method */
4435 semUnlock, /* xUnlock method */
4436 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004437)
aswiftaebf4132008-11-21 00:10:35 +00004438#endif
drh7708e972008-11-29 00:56:52 +00004439
drhd2cb50b2009-01-09 21:41:17 +00004440#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004441IOMETHODS(
4442 afpIoFinder, /* Finder function name */
4443 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004444 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004445 afpClose, /* xClose method */
4446 afpLock, /* xLock method */
4447 afpUnlock, /* xUnlock method */
4448 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004449)
drh715ff302008-12-03 22:32:44 +00004450#endif
4451
4452/*
4453** The proxy locking method is a "super-method" in the sense that it
4454** opens secondary file descriptors for the conch and lock files and
4455** it uses proxy, dot-file, AFP, and flock() locking methods on those
4456** secondary files. For this reason, the division that implements
4457** proxy locking is located much further down in the file. But we need
4458** to go ahead and define the sqlite3_io_methods and finder function
4459** for proxy locking here. So we forward declare the I/O methods.
4460*/
drhd2cb50b2009-01-09 21:41:17 +00004461#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004462static int proxyClose(sqlite3_file*);
4463static int proxyLock(sqlite3_file*, int);
4464static int proxyUnlock(sqlite3_file*, int);
4465static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004466IOMETHODS(
4467 proxyIoFinder, /* Finder function name */
4468 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004469 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004470 proxyClose, /* xClose method */
4471 proxyLock, /* xLock method */
4472 proxyUnlock, /* xUnlock method */
4473 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004474)
aswiftaebf4132008-11-21 00:10:35 +00004475#endif
drh7708e972008-11-29 00:56:52 +00004476
drh7ed97b92010-01-20 13:07:21 +00004477/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4478#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4479IOMETHODS(
4480 nfsIoFinder, /* Finder function name */
4481 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004482 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004483 unixClose, /* xClose method */
4484 unixLock, /* xLock method */
4485 nfsUnlock, /* xUnlock method */
4486 unixCheckReservedLock /* xCheckReservedLock method */
4487)
4488#endif
drh7708e972008-11-29 00:56:52 +00004489
drhd2cb50b2009-01-09 21:41:17 +00004490#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004491/*
drh6b9d6dd2008-12-03 19:34:47 +00004492** This "finder" function attempts to determine the best locking strategy
4493** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004494** object that implements that strategy.
4495**
4496** This is for MacOSX only.
4497*/
drh1875f7a2008-12-08 18:19:17 +00004498static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004499 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004500 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004501){
4502 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004503 const char *zFilesystem; /* Filesystem type name */
4504 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004505 } aMap[] = {
4506 { "hfs", &posixIoMethods },
4507 { "ufs", &posixIoMethods },
4508 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004509 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004510 { "webdav", &nolockIoMethods },
4511 { 0, 0 }
4512 };
4513 int i;
4514 struct statfs fsInfo;
4515 struct flock lockInfo;
4516
4517 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004518 /* If filePath==NULL that means we are dealing with a transient file
4519 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004520 return &nolockIoMethods;
4521 }
4522 if( statfs(filePath, &fsInfo) != -1 ){
4523 if( fsInfo.f_flags & MNT_RDONLY ){
4524 return &nolockIoMethods;
4525 }
4526 for(i=0; aMap[i].zFilesystem; i++){
4527 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4528 return aMap[i].pMethods;
4529 }
4530 }
4531 }
4532
4533 /* Default case. Handles, amongst others, "nfs".
4534 ** Test byte-range lock using fcntl(). If the call succeeds,
4535 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004536 */
drh7708e972008-11-29 00:56:52 +00004537 lockInfo.l_len = 1;
4538 lockInfo.l_start = 0;
4539 lockInfo.l_whence = SEEK_SET;
4540 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004541 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004542 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4543 return &nfsIoMethods;
4544 } else {
4545 return &posixIoMethods;
4546 }
drh7708e972008-11-29 00:56:52 +00004547 }else{
4548 return &dotlockIoMethods;
4549 }
4550}
drh0c2694b2009-09-03 16:23:44 +00004551static const sqlite3_io_methods
4552 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004553
drhd2cb50b2009-01-09 21:41:17 +00004554#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004555
chw78a13182009-04-07 05:35:03 +00004556#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4557/*
4558** This "finder" function attempts to determine the best locking strategy
4559** for the database file "filePath". It then returns the sqlite3_io_methods
4560** object that implements that strategy.
4561**
4562** This is for VXWorks only.
4563*/
4564static const sqlite3_io_methods *autolockIoFinderImpl(
4565 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004566 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004567){
4568 struct flock lockInfo;
4569
4570 if( !filePath ){
4571 /* If filePath==NULL that means we are dealing with a transient file
4572 ** that does not need to be locked. */
4573 return &nolockIoMethods;
4574 }
4575
4576 /* Test if fcntl() is supported and use POSIX style locks.
4577 ** Otherwise fall back to the named semaphore method.
4578 */
4579 lockInfo.l_len = 1;
4580 lockInfo.l_start = 0;
4581 lockInfo.l_whence = SEEK_SET;
4582 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004583 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004584 return &posixIoMethods;
4585 }else{
4586 return &semIoMethods;
4587 }
4588}
drh0c2694b2009-09-03 16:23:44 +00004589static const sqlite3_io_methods
4590 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004591
4592#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4593
drh7708e972008-11-29 00:56:52 +00004594/*
4595** An abstract type for a pointer to a IO method finder function:
4596*/
drh0c2694b2009-09-03 16:23:44 +00004597typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004598
aswiftaebf4132008-11-21 00:10:35 +00004599
drh734c9862008-11-28 15:37:20 +00004600/****************************************************************************
4601**************************** sqlite3_vfs methods ****************************
4602**
4603** This division contains the implementation of methods on the
4604** sqlite3_vfs object.
4605*/
4606
danielk1977a3d4c882007-03-23 10:08:38 +00004607/*
danielk1977e339d652008-06-28 11:23:00 +00004608** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004609*/
4610static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004611 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004612 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004613 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004614 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004615 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004616){
drh7708e972008-11-29 00:56:52 +00004617 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004618 unixFile *pNew = (unixFile *)pId;
4619 int rc = SQLITE_OK;
4620
drh8af6c222010-05-14 12:43:01 +00004621 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004622
dan00157392010-10-05 11:33:15 +00004623 /* Usually the path zFilename should not be a relative pathname. The
4624 ** exception is when opening the proxy "conch" file in builds that
4625 ** include the special Apple locking styles.
4626 */
dan00157392010-10-05 11:33:15 +00004627#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004628 assert( zFilename==0 || zFilename[0]=='/'
4629 || pVfs->pAppData==(void*)&autolockIoFinder );
4630#else
4631 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004632#endif
dan00157392010-10-05 11:33:15 +00004633
drhb07028f2011-10-14 21:49:18 +00004634 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004635 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004636
drh308c2a52010-05-14 11:30:18 +00004637 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004638 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004639 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004640 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004641 pNew->ctrlFlags = (u8)ctrlFlags;
4642 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4643 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004644 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004645 }
drha7e61d82011-03-12 17:02:57 +00004646 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004647 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004648 }
drh339eb0b2008-03-07 15:34:11 +00004649
drh6c7d5c52008-11-21 20:32:33 +00004650#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004651 pNew->pId = vxworksFindFileId(zFilename);
4652 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004653 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004654 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004655 }
4656#endif
4657
drhc02a43a2012-01-10 23:18:38 +00004658 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004659 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004660 }else{
drh0c2694b2009-09-03 16:23:44 +00004661 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004662#if SQLITE_ENABLE_LOCKING_STYLE
4663 /* Cache zFilename in the locking context (AFP and dotlock override) for
4664 ** proxyLock activation is possible (remote proxy is based on db name)
4665 ** zFilename remains valid until file is closed, to support */
4666 pNew->lockingContext = (void*)zFilename;
4667#endif
drhda0e7682008-07-30 15:27:54 +00004668 }
danielk1977e339d652008-06-28 11:23:00 +00004669
drh7ed97b92010-01-20 13:07:21 +00004670 if( pLockingStyle == &posixIoMethods
4671#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4672 || pLockingStyle == &nfsIoMethods
4673#endif
4674 ){
drh7708e972008-11-29 00:56:52 +00004675 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004676 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004677 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004678 /* If an error occured in findInodeInfo(), close the file descriptor
4679 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004680 ** in two scenarios:
4681 **
4682 ** (a) A call to fstat() failed.
4683 ** (b) A malloc failed.
4684 **
4685 ** Scenario (b) may only occur if the process is holding no other
4686 ** file descriptors open on the same file. If there were other file
4687 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004688 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004689 ** handle h - as it is guaranteed that no posix locks will be released
4690 ** by doing so.
4691 **
4692 ** If scenario (a) caused the error then things are not so safe. The
4693 ** implicit assumption here is that if fstat() fails, things are in
4694 ** such bad shape that dropping a lock or two doesn't matter much.
4695 */
drh0e9365c2011-03-02 02:08:13 +00004696 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004697 h = -1;
4698 }
drh7708e972008-11-29 00:56:52 +00004699 unixLeaveMutex();
4700 }
danielk1977e339d652008-06-28 11:23:00 +00004701
drhd2cb50b2009-01-09 21:41:17 +00004702#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004703 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004704 /* AFP locking uses the file path so it needs to be included in
4705 ** the afpLockingContext.
4706 */
4707 afpLockingContext *pCtx;
4708 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4709 if( pCtx==0 ){
4710 rc = SQLITE_NOMEM;
4711 }else{
4712 /* NB: zFilename exists and remains valid until the file is closed
4713 ** according to requirement F11141. So we do not need to make a
4714 ** copy of the filename. */
4715 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004716 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004717 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004718 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004719 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004720 if( rc!=SQLITE_OK ){
4721 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004722 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004723 h = -1;
4724 }
drh7708e972008-11-29 00:56:52 +00004725 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004726 }
drh7708e972008-11-29 00:56:52 +00004727 }
4728#endif
danielk1977e339d652008-06-28 11:23:00 +00004729
drh7708e972008-11-29 00:56:52 +00004730 else if( pLockingStyle == &dotlockIoMethods ){
4731 /* Dotfile locking uses the file path so it needs to be included in
4732 ** the dotlockLockingContext
4733 */
4734 char *zLockFile;
4735 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004736 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004737 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004738 zLockFile = (char *)sqlite3_malloc(nFilename);
4739 if( zLockFile==0 ){
4740 rc = SQLITE_NOMEM;
4741 }else{
4742 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004743 }
drh7708e972008-11-29 00:56:52 +00004744 pNew->lockingContext = zLockFile;
4745 }
danielk1977e339d652008-06-28 11:23:00 +00004746
drh6c7d5c52008-11-21 20:32:33 +00004747#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004748 else if( pLockingStyle == &semIoMethods ){
4749 /* Named semaphore locking uses the file path so it needs to be
4750 ** included in the semLockingContext
4751 */
4752 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004753 rc = findInodeInfo(pNew, &pNew->pInode);
4754 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4755 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004756 int n;
drh2238dcc2009-08-27 17:56:20 +00004757 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004758 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004759 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004760 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004761 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4762 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004763 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004764 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004765 }
chw97185482008-11-17 08:05:31 +00004766 }
drh7708e972008-11-29 00:56:52 +00004767 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004768 }
drh7708e972008-11-29 00:56:52 +00004769#endif
aswift5b1a2562008-08-22 00:22:35 +00004770
4771 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004772#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004773 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004774 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004775 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004776 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004777 isDelete = 0;
4778 }
drhc02a43a2012-01-10 23:18:38 +00004779 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004780#endif
danielk1977e339d652008-06-28 11:23:00 +00004781 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004782 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004783 }else{
drh7708e972008-11-29 00:56:52 +00004784 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004785 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004786 }
danielk1977e339d652008-06-28 11:23:00 +00004787 return rc;
drh054889e2005-11-30 03:20:31 +00004788}
drh9c06c952005-11-26 00:25:00 +00004789
danielk1977ad94b582007-08-20 06:44:22 +00004790/*
drh8b3cf822010-06-01 21:02:51 +00004791** Return the name of a directory in which to put temporary files.
4792** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004793*/
drh7234c6d2010-06-19 15:10:09 +00004794static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004795 static const char *azDirs[] = {
4796 0,
aswiftaebf4132008-11-21 00:10:35 +00004797 0,
danielk197717b90b52008-06-06 11:11:25 +00004798 "/var/tmp",
4799 "/usr/tmp",
4800 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004801 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004802 };
drh8b3cf822010-06-01 21:02:51 +00004803 unsigned int i;
4804 struct stat buf;
4805 const char *zDir = 0;
4806
4807 azDirs[0] = sqlite3_temp_directory;
4808 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004809 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004810 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004811 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004812 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004813 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004814 break;
4815 }
4816 return zDir;
4817}
4818
4819/*
4820** Create a temporary file name in zBuf. zBuf must be allocated
4821** by the calling process and must be big enough to hold at least
4822** pVfs->mxPathname bytes.
4823*/
4824static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004825 static const unsigned char zChars[] =
4826 "abcdefghijklmnopqrstuvwxyz"
4827 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4828 "0123456789";
drh41022642008-11-21 00:24:42 +00004829 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004830 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004831
4832 /* It's odd to simulate an io-error here, but really this is just
4833 ** using the io-error infrastructure to test that SQLite handles this
4834 ** function failing.
4835 */
4836 SimulateIOError( return SQLITE_IOERR );
4837
drh7234c6d2010-06-19 15:10:09 +00004838 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004839 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004840
4841 /* Check that the output buffer is large enough for the temporary file
4842 ** name. If it is not, return SQLITE_ERROR.
4843 */
drhc02a43a2012-01-10 23:18:38 +00004844 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004845 return SQLITE_ERROR;
4846 }
4847
4848 do{
drhc02a43a2012-01-10 23:18:38 +00004849 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004850 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004851 sqlite3_randomness(15, &zBuf[j]);
4852 for(i=0; i<15; i++, j++){
4853 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4854 }
4855 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00004856 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00004857 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004858 return SQLITE_OK;
4859}
4860
drhd2cb50b2009-01-09 21:41:17 +00004861#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004862/*
4863** Routine to transform a unixFile into a proxy-locking unixFile.
4864** Implementation in the proxy-lock division, but used by unixOpen()
4865** if SQLITE_PREFER_PROXY_LOCKING is defined.
4866*/
4867static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004868#endif
drhc66d5b62008-12-03 22:48:32 +00004869
dan08da86a2009-08-21 17:18:03 +00004870/*
4871** Search for an unused file descriptor that was opened on the database
4872** file (not a journal or master-journal file) identified by pathname
4873** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4874** argument to this function.
4875**
4876** Such a file descriptor may exist if a database connection was closed
4877** but the associated file descriptor could not be closed because some
4878** other file descriptor open on the same file is holding a file-lock.
4879** Refer to comments in the unixClose() function and the lengthy comment
4880** describing "Posix Advisory Locking" at the start of this file for
4881** further details. Also, ticket #4018.
4882**
4883** If a suitable file descriptor is found, then it is returned. If no
4884** such file descriptor is located, -1 is returned.
4885*/
dane946c392009-08-22 11:39:46 +00004886static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4887 UnixUnusedFd *pUnused = 0;
4888
4889 /* Do not search for an unused file descriptor on vxworks. Not because
4890 ** vxworks would not benefit from the change (it might, we're not sure),
4891 ** but because no way to test it is currently available. It is better
4892 ** not to risk breaking vxworks support for the sake of such an obscure
4893 ** feature. */
4894#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004895 struct stat sStat; /* Results of stat() call */
4896
4897 /* A stat() call may fail for various reasons. If this happens, it is
4898 ** almost certain that an open() call on the same path will also fail.
4899 ** For this reason, if an error occurs in the stat() call here, it is
4900 ** ignored and -1 is returned. The caller will try to open a new file
4901 ** descriptor on the same path, fail, and return an error to SQLite.
4902 **
4903 ** Even if a subsequent open() call does succeed, the consequences of
4904 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004905 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004906 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004907
4908 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004909 pInode = inodeList;
4910 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4911 || pInode->fileId.ino!=sStat.st_ino) ){
4912 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004913 }
drh8af6c222010-05-14 12:43:01 +00004914 if( pInode ){
dane946c392009-08-22 11:39:46 +00004915 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004916 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004917 pUnused = *pp;
4918 if( pUnused ){
4919 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004920 }
4921 }
4922 unixLeaveMutex();
4923 }
dane946c392009-08-22 11:39:46 +00004924#endif /* if !OS_VXWORKS */
4925 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004926}
danielk197717b90b52008-06-06 11:11:25 +00004927
4928/*
danddb0ac42010-07-14 14:48:58 +00004929** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004930** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004931** and a value suitable for passing as the third argument to open(2) is
4932** written to *pMode. If an IO error occurs, an SQLite error code is
4933** returned and the value of *pMode is not modified.
4934**
drh8c815d12012-02-13 20:16:37 +00004935** In most cases cases, this routine sets *pMode to 0, which will become
4936** an indication to robust_open() to create the file using
4937** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
4938** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00004939** this function queries the file-system for the permissions on the
4940** corresponding database file and sets *pMode to this value. Whenever
4941** possible, WAL and journal files are created using the same permissions
4942** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004943**
4944** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4945** original filename is unavailable. But 8_3_NAMES is only used for
4946** FAT filesystems and permissions do not matter there, so just use
4947** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004948*/
4949static int findCreateFileMode(
4950 const char *zPath, /* Path of file (possibly) being created */
4951 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00004952 mode_t *pMode, /* OUT: Permissions to open file with */
4953 uid_t *pUid, /* OUT: uid to set on the file */
4954 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00004955){
4956 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00004957 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00004958 *pUid = 0;
4959 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00004960 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004961 char zDb[MAX_PATHNAME+1]; /* Database file path */
4962 int nDb; /* Number of valid bytes in zDb */
4963 struct stat sStat; /* Output of stat() on database file */
4964
dana0c989d2010-11-05 18:07:37 +00004965 /* zPath is a path to a WAL or journal file. The following block derives
4966 ** the path to the associated database file from zPath. This block handles
4967 ** the following naming conventions:
4968 **
4969 ** "<path to db>-journal"
4970 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004971 ** "<path to db>-journalNN"
4972 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004973 **
drhd337c5b2011-10-20 18:23:35 +00004974 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004975 ** used by the test_multiplex.c module.
4976 */
4977 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004978#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004979 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004980 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004981#else
4982 while( zPath[nDb]!='-' ){
4983 assert( nDb>0 );
4984 assert( zPath[nDb]!='\n' );
4985 nDb--;
4986 }
4987#endif
danddb0ac42010-07-14 14:48:58 +00004988 memcpy(zDb, zPath, nDb);
4989 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004990
drh58384f12011-07-28 00:14:45 +00004991 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004992 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00004993 *pUid = sStat.st_uid;
4994 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00004995 }else{
4996 rc = SQLITE_IOERR_FSTAT;
4997 }
4998 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4999 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005000 }
5001 return rc;
5002}
5003
5004/*
danielk1977ad94b582007-08-20 06:44:22 +00005005** Open the file zPath.
5006**
danielk1977b4b47412007-08-17 15:53:36 +00005007** Previously, the SQLite OS layer used three functions in place of this
5008** one:
5009**
5010** sqlite3OsOpenReadWrite();
5011** sqlite3OsOpenReadOnly();
5012** sqlite3OsOpenExclusive();
5013**
5014** These calls correspond to the following combinations of flags:
5015**
5016** ReadWrite() -> (READWRITE | CREATE)
5017** ReadOnly() -> (READONLY)
5018** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5019**
5020** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5021** true, the file was configured to be automatically deleted when the
5022** file handle closed. To achieve the same effect using this new
5023** interface, add the DELETEONCLOSE flag to those specified above for
5024** OpenExclusive().
5025*/
5026static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005027 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5028 const char *zPath, /* Pathname of file to be opened */
5029 sqlite3_file *pFile, /* The file descriptor to be filled in */
5030 int flags, /* Input flags to control the opening */
5031 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005032){
dan08da86a2009-08-21 17:18:03 +00005033 unixFile *p = (unixFile *)pFile;
5034 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005035 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005036 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005037 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005038 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005039 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005040
5041 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5042 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5043 int isCreate = (flags & SQLITE_OPEN_CREATE);
5044 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5045 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005046#if SQLITE_ENABLE_LOCKING_STYLE
5047 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5048#endif
drh3d4435b2011-08-26 20:55:50 +00005049#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5050 struct statfs fsInfo;
5051#endif
danielk1977b4b47412007-08-17 15:53:36 +00005052
danielk1977fee2d252007-08-18 10:59:19 +00005053 /* If creating a master or main-file journal, this function will open
5054 ** a file-descriptor on the directory too. The first time unixSync()
5055 ** is called the directory file descriptor will be fsync()ed and close()d.
5056 */
drh0059eae2011-08-08 23:48:40 +00005057 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005058 eType==SQLITE_OPEN_MASTER_JOURNAL
5059 || eType==SQLITE_OPEN_MAIN_JOURNAL
5060 || eType==SQLITE_OPEN_WAL
5061 ));
danielk1977fee2d252007-08-18 10:59:19 +00005062
danielk197717b90b52008-06-06 11:11:25 +00005063 /* If argument zPath is a NULL pointer, this function is required to open
5064 ** a temporary file. Use this buffer to store the file name in.
5065 */
drhc02a43a2012-01-10 23:18:38 +00005066 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005067 const char *zName = zPath;
5068
danielk1977fee2d252007-08-18 10:59:19 +00005069 /* Check the following statements are true:
5070 **
5071 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5072 ** (b) if CREATE is set, then READWRITE must also be set, and
5073 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005074 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005075 */
danielk1977b4b47412007-08-17 15:53:36 +00005076 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005077 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005078 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005079 assert(isDelete==0 || isCreate);
5080
danddb0ac42010-07-14 14:48:58 +00005081 /* The main DB, main journal, WAL file and master journal are never
5082 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005083 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5084 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5085 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005086 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005087
danielk1977fee2d252007-08-18 10:59:19 +00005088 /* Assert that the upper layer has set one of the "file-type" flags. */
5089 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5090 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5091 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005092 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005093 );
5094
dan08da86a2009-08-21 17:18:03 +00005095 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005096
dan08da86a2009-08-21 17:18:03 +00005097 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005098 UnixUnusedFd *pUnused;
5099 pUnused = findReusableFd(zName, flags);
5100 if( pUnused ){
5101 fd = pUnused->fd;
5102 }else{
dan6aa657f2009-08-24 18:57:58 +00005103 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005104 if( !pUnused ){
5105 return SQLITE_NOMEM;
5106 }
5107 }
5108 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005109
5110 /* Database filenames are double-zero terminated if they are not
5111 ** URIs with parameters. Hence, they can always be passed into
5112 ** sqlite3_uri_parameter(). */
5113 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5114
dan08da86a2009-08-21 17:18:03 +00005115 }else if( !zName ){
5116 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005117 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005118 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005119 if( rc!=SQLITE_OK ){
5120 return rc;
5121 }
5122 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005123
5124 /* Generated temporary filenames are always double-zero terminated
5125 ** for use by sqlite3_uri_parameter(). */
5126 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005127 }
5128
dan08da86a2009-08-21 17:18:03 +00005129 /* Determine the value of the flags parameter passed to POSIX function
5130 ** open(). These must be calculated even if open() is not called, as
5131 ** they may be stored as part of the file handle and used by the
5132 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005133 if( isReadonly ) openFlags |= O_RDONLY;
5134 if( isReadWrite ) openFlags |= O_RDWR;
5135 if( isCreate ) openFlags |= O_CREAT;
5136 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5137 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005138
danielk1977b4b47412007-08-17 15:53:36 +00005139 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005140 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005141 uid_t uid; /* Userid for the file */
5142 gid_t gid; /* Groupid for the file */
5143 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005144 if( rc!=SQLITE_OK ){
5145 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005146 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005147 return rc;
5148 }
drhad4f1e52011-03-04 15:43:57 +00005149 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005150 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005151 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5152 /* Failed to open the file for read/write access. Try read-only. */
5153 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005154 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005155 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005156 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005157 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005158 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005159 }
5160 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005161 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005162 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005163 }
drhac7c3ac2012-02-11 19:23:48 +00005164
5165 /* If this process is running as root and if creating a new rollback
5166 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005167 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005168 */
5169 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005170 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005171 }
danielk1977b4b47412007-08-17 15:53:36 +00005172 }
dan08da86a2009-08-21 17:18:03 +00005173 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005174 if( pOutFlags ){
5175 *pOutFlags = flags;
5176 }
5177
dane946c392009-08-22 11:39:46 +00005178 if( p->pUnused ){
5179 p->pUnused->fd = fd;
5180 p->pUnused->flags = flags;
5181 }
5182
danielk1977b4b47412007-08-17 15:53:36 +00005183 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005184#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005185 zPath = zName;
5186#else
drh036ac7f2011-08-08 23:18:05 +00005187 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005188#endif
danielk1977b4b47412007-08-17 15:53:36 +00005189 }
drh41022642008-11-21 00:24:42 +00005190#if SQLITE_ENABLE_LOCKING_STYLE
5191 else{
dan08da86a2009-08-21 17:18:03 +00005192 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005193 }
5194#endif
5195
drhda0e7682008-07-30 15:27:54 +00005196 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005197
drh7ed97b92010-01-20 13:07:21 +00005198
5199#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005200 if( fstatfs(fd, &fsInfo) == -1 ){
5201 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005202 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005203 return SQLITE_IOERR_ACCESS;
5204 }
5205 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5206 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5207 }
5208#endif
drhc02a43a2012-01-10 23:18:38 +00005209
5210 /* Set up appropriate ctrlFlags */
5211 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5212 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5213 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5214 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5215 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5216
drh7ed97b92010-01-20 13:07:21 +00005217#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005218#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005219 isAutoProxy = 1;
5220#endif
5221 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005222 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5223 int useProxy = 0;
5224
dan08da86a2009-08-21 17:18:03 +00005225 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5226 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005227 if( envforce!=NULL ){
5228 useProxy = atoi(envforce)>0;
5229 }else{
aswiftaebf4132008-11-21 00:10:35 +00005230 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005231 /* In theory, the close(fd) call is sub-optimal. If the file opened
5232 ** with fd is a database file, and there are other connections open
5233 ** on that file that are currently holding advisory locks on it,
5234 ** then the call to close() will cancel those locks. In practice,
5235 ** we're assuming that statfs() doesn't fail very often. At least
5236 ** not while other file descriptors opened by the same process on
5237 ** the same file are working. */
5238 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005239 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005240 rc = SQLITE_IOERR_ACCESS;
5241 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005242 }
5243 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5244 }
5245 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005246 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005247 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005248 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005249 if( rc!=SQLITE_OK ){
5250 /* Use unixClose to clean up the resources added in fillInUnixFile
5251 ** and clear all the structure's references. Specifically,
5252 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5253 */
5254 unixClose(pFile);
5255 return rc;
5256 }
aswiftaebf4132008-11-21 00:10:35 +00005257 }
dane946c392009-08-22 11:39:46 +00005258 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005259 }
5260 }
5261#endif
5262
drhc02a43a2012-01-10 23:18:38 +00005263 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5264
dane946c392009-08-22 11:39:46 +00005265open_finished:
5266 if( rc!=SQLITE_OK ){
5267 sqlite3_free(p->pUnused);
5268 }
5269 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005270}
5271
dane946c392009-08-22 11:39:46 +00005272
danielk1977b4b47412007-08-17 15:53:36 +00005273/*
danielk1977fee2d252007-08-18 10:59:19 +00005274** Delete the file at zPath. If the dirSync argument is true, fsync()
5275** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005276*/
drh6b9d6dd2008-12-03 19:34:47 +00005277static int unixDelete(
5278 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5279 const char *zPath, /* Name of file to be deleted */
5280 int dirSync /* If true, fsync() directory after deleting file */
5281){
danielk1977fee2d252007-08-18 10:59:19 +00005282 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005283 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005284 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005285 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005286 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005287 }
danielk1977d39fa702008-10-16 13:27:40 +00005288#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005289 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005290 int fd;
drh90315a22011-08-10 01:52:12 +00005291 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005292 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005293#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005294 if( fsync(fd)==-1 )
5295#else
5296 if( fsync(fd) )
5297#endif
5298 {
dane18d4952011-02-21 11:46:24 +00005299 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005300 }
drh0e9365c2011-03-02 02:08:13 +00005301 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005302 }else if( rc==SQLITE_CANTOPEN ){
5303 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005304 }
5305 }
danielk1977d138dd82008-10-15 16:02:48 +00005306#endif
danielk1977fee2d252007-08-18 10:59:19 +00005307 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005308}
5309
danielk197790949c22007-08-17 16:50:38 +00005310/*
5311** Test the existance of or access permissions of file zPath. The
5312** test performed depends on the value of flags:
5313**
5314** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5315** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5316** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5317**
5318** Otherwise return 0.
5319*/
danielk1977861f7452008-06-05 11:39:11 +00005320static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005321 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5322 const char *zPath, /* Path of the file to examine */
5323 int flags, /* What do we want to learn about the zPath file? */
5324 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005325){
rse25c0d1a2007-09-20 08:38:14 +00005326 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005327 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005328 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005329 switch( flags ){
5330 case SQLITE_ACCESS_EXISTS:
5331 amode = F_OK;
5332 break;
5333 case SQLITE_ACCESS_READWRITE:
5334 amode = W_OK|R_OK;
5335 break;
drh50d3f902007-08-27 21:10:36 +00005336 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005337 amode = R_OK;
5338 break;
5339
5340 default:
5341 assert(!"Invalid flags argument");
5342 }
drh99ab3b12011-03-02 15:09:07 +00005343 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005344 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5345 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005346 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005347 *pResOut = 0;
5348 }
5349 }
danielk1977861f7452008-06-05 11:39:11 +00005350 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005351}
5352
danielk1977b4b47412007-08-17 15:53:36 +00005353
5354/*
5355** Turn a relative pathname into a full pathname. The relative path
5356** is stored as a nul-terminated string in the buffer pointed to by
5357** zPath.
5358**
5359** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5360** (in this case, MAX_PATHNAME bytes). The full-path is written to
5361** this buffer before returning.
5362*/
danielk1977adfb9b02007-09-17 07:02:56 +00005363static int unixFullPathname(
5364 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5365 const char *zPath, /* Possibly relative input path */
5366 int nOut, /* Size of output buffer in bytes */
5367 char *zOut /* Output buffer */
5368){
danielk1977843e65f2007-09-01 16:16:15 +00005369
5370 /* It's odd to simulate an io-error here, but really this is just
5371 ** using the io-error infrastructure to test that SQLite handles this
5372 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005373 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005374 */
5375 SimulateIOError( return SQLITE_ERROR );
5376
drh153c62c2007-08-24 03:51:33 +00005377 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005378 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005379
drh3c7f2dc2007-12-06 13:26:20 +00005380 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005381 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005382 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005383 }else{
5384 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005385 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005386 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005387 }
drhea678832008-12-10 19:26:22 +00005388 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005389 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005390 }
5391 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005392}
5393
drh0ccebe72005-06-07 22:22:50 +00005394
drh761df872006-12-21 01:29:22 +00005395#ifndef SQLITE_OMIT_LOAD_EXTENSION
5396/*
5397** Interfaces for opening a shared library, finding entry points
5398** within the shared library, and closing the shared library.
5399*/
5400#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005401static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5402 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005403 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5404}
danielk197795c8a542007-09-01 06:51:27 +00005405
5406/*
5407** SQLite calls this function immediately after a call to unixDlSym() or
5408** unixDlOpen() fails (returns a null pointer). If a more detailed error
5409** message is available, it is written to zBufOut. If no error message
5410** is available, zBufOut is left unmodified and SQLite uses a default
5411** error message.
5412*/
danielk1977397d65f2008-11-19 11:35:39 +00005413static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005414 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005415 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005416 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005417 zErr = dlerror();
5418 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005419 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005420 }
drh6c7d5c52008-11-21 20:32:33 +00005421 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005422}
drh1875f7a2008-12-08 18:19:17 +00005423static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5424 /*
5425 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5426 ** cast into a pointer to a function. And yet the library dlsym() routine
5427 ** returns a void* which is really a pointer to a function. So how do we
5428 ** use dlsym() with -pedantic-errors?
5429 **
5430 ** Variable x below is defined to be a pointer to a function taking
5431 ** parameters void* and const char* and returning a pointer to a function.
5432 ** We initialize x by assigning it a pointer to the dlsym() function.
5433 ** (That assignment requires a cast.) Then we call the function that
5434 ** x points to.
5435 **
5436 ** This work-around is unlikely to work correctly on any system where
5437 ** you really cannot cast a function pointer into void*. But then, on the
5438 ** other hand, dlsym() will not work on such a system either, so we have
5439 ** not really lost anything.
5440 */
5441 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005442 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005443 x = (void(*(*)(void*,const char*))(void))dlsym;
5444 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005445}
danielk1977397d65f2008-11-19 11:35:39 +00005446static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5447 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005448 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005449}
danielk1977b4b47412007-08-17 15:53:36 +00005450#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5451 #define unixDlOpen 0
5452 #define unixDlError 0
5453 #define unixDlSym 0
5454 #define unixDlClose 0
5455#endif
5456
5457/*
danielk197790949c22007-08-17 16:50:38 +00005458** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005459*/
danielk1977397d65f2008-11-19 11:35:39 +00005460static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5461 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005462 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005463
drhbbd42a62004-05-22 17:41:58 +00005464 /* We have to initialize zBuf to prevent valgrind from reporting
5465 ** errors. The reports issued by valgrind are incorrect - we would
5466 ** prefer that the randomness be increased by making use of the
5467 ** uninitialized space in zBuf - but valgrind errors tend to worry
5468 ** some users. Rather than argue, it seems easier just to initialize
5469 ** the whole array and silence valgrind, even if that means less randomness
5470 ** in the random seed.
5471 **
5472 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005473 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005474 ** tests repeatable.
5475 */
danielk1977b4b47412007-08-17 15:53:36 +00005476 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005477#if !defined(SQLITE_TEST)
5478 {
drhc18b4042012-02-10 03:10:27 +00005479 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005480 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005481 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005482 time_t t;
5483 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005484 memcpy(zBuf, &t, sizeof(t));
5485 pid = getpid();
5486 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005487 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005488 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005489 }else{
drhc18b4042012-02-10 03:10:27 +00005490 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005491 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005492 }
drhbbd42a62004-05-22 17:41:58 +00005493 }
5494#endif
drh72cbd072008-10-14 17:58:38 +00005495 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005496}
5497
danielk1977b4b47412007-08-17 15:53:36 +00005498
drhbbd42a62004-05-22 17:41:58 +00005499/*
5500** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005501** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005502** The return value is the number of microseconds of sleep actually
5503** requested from the underlying operating system, a number which
5504** might be greater than or equal to the argument, but not less
5505** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005506*/
danielk1977397d65f2008-11-19 11:35:39 +00005507static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005508#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005509 struct timespec sp;
5510
5511 sp.tv_sec = microseconds / 1000000;
5512 sp.tv_nsec = (microseconds % 1000000) * 1000;
5513 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005514 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005515 return microseconds;
5516#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005517 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005518 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005519 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005520#else
danielk1977b4b47412007-08-17 15:53:36 +00005521 int seconds = (microseconds+999999)/1000000;
5522 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005523 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005524 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005525#endif
drh88f474a2006-01-02 20:00:12 +00005526}
5527
5528/*
drh6b9d6dd2008-12-03 19:34:47 +00005529** The following variable, if set to a non-zero value, is interpreted as
5530** the number of seconds since 1970 and is used to set the result of
5531** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005532*/
5533#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005534int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005535#endif
5536
5537/*
drhb7e8ea22010-05-03 14:32:30 +00005538** Find the current time (in Universal Coordinated Time). Write into *piNow
5539** the current time and date as a Julian Day number times 86_400_000. In
5540** other words, write into *piNow the number of milliseconds since the Julian
5541** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5542** proleptic Gregorian calendar.
5543**
drh31702252011-10-12 23:13:43 +00005544** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5545** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005546*/
5547static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5548 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005549 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005550#if defined(NO_GETTOD)
5551 time_t t;
5552 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005553 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005554#elif OS_VXWORKS
5555 struct timespec sNow;
5556 clock_gettime(CLOCK_REALTIME, &sNow);
5557 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5558#else
5559 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005560 if( gettimeofday(&sNow, 0)==0 ){
5561 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5562 }else{
5563 rc = SQLITE_ERROR;
5564 }
drhb7e8ea22010-05-03 14:32:30 +00005565#endif
5566
5567#ifdef SQLITE_TEST
5568 if( sqlite3_current_time ){
5569 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5570 }
5571#endif
5572 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005573 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005574}
5575
5576/*
drhbbd42a62004-05-22 17:41:58 +00005577** Find the current time (in Universal Coordinated Time). Write the
5578** current time and date as a Julian Day number into *prNow and
5579** return 0. Return 1 if the time and date cannot be found.
5580*/
danielk1977397d65f2008-11-19 11:35:39 +00005581static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005582 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005583 int rc;
drhff828942010-06-26 21:34:06 +00005584 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005585 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005586 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005587 return rc;
drhbbd42a62004-05-22 17:41:58 +00005588}
danielk1977b4b47412007-08-17 15:53:36 +00005589
drh6b9d6dd2008-12-03 19:34:47 +00005590/*
5591** We added the xGetLastError() method with the intention of providing
5592** better low-level error messages when operating-system problems come up
5593** during SQLite operation. But so far, none of that has been implemented
5594** in the core. So this routine is never called. For now, it is merely
5595** a place-holder.
5596*/
danielk1977397d65f2008-11-19 11:35:39 +00005597static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5598 UNUSED_PARAMETER(NotUsed);
5599 UNUSED_PARAMETER(NotUsed2);
5600 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005601 return 0;
5602}
5603
drhf2424c52010-04-26 00:04:55 +00005604
5605/*
drh734c9862008-11-28 15:37:20 +00005606************************ End of sqlite3_vfs methods ***************************
5607******************************************************************************/
5608
drh715ff302008-12-03 22:32:44 +00005609/******************************************************************************
5610************************** Begin Proxy Locking ********************************
5611**
5612** Proxy locking is a "uber-locking-method" in this sense: It uses the
5613** other locking methods on secondary lock files. Proxy locking is a
5614** meta-layer over top of the primitive locking implemented above. For
5615** this reason, the division that implements of proxy locking is deferred
5616** until late in the file (here) after all of the other I/O methods have
5617** been defined - so that the primitive locking methods are available
5618** as services to help with the implementation of proxy locking.
5619**
5620****
5621**
5622** The default locking schemes in SQLite use byte-range locks on the
5623** database file to coordinate safe, concurrent access by multiple readers
5624** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5625** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5626** as POSIX read & write locks over fixed set of locations (via fsctl),
5627** on AFP and SMB only exclusive byte-range locks are available via fsctl
5628** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5629** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5630** address in the shared range is taken for a SHARED lock, the entire
5631** shared range is taken for an EXCLUSIVE lock):
5632**
drhf2f105d2012-08-20 15:53:54 +00005633** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00005634** RESERVED_BYTE 0x40000001
5635** SHARED_RANGE 0x40000002 -> 0x40000200
5636**
5637** This works well on the local file system, but shows a nearly 100x
5638** slowdown in read performance on AFP because the AFP client disables
5639** the read cache when byte-range locks are present. Enabling the read
5640** cache exposes a cache coherency problem that is present on all OS X
5641** supported network file systems. NFS and AFP both observe the
5642** close-to-open semantics for ensuring cache coherency
5643** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5644** address the requirements for concurrent database access by multiple
5645** readers and writers
5646** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5647**
5648** To address the performance and cache coherency issues, proxy file locking
5649** changes the way database access is controlled by limiting access to a
5650** single host at a time and moving file locks off of the database file
5651** and onto a proxy file on the local file system.
5652**
5653**
5654** Using proxy locks
5655** -----------------
5656**
5657** C APIs
5658**
5659** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5660** <proxy_path> | ":auto:");
5661** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5662**
5663**
5664** SQL pragmas
5665**
5666** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5667** PRAGMA [database.]lock_proxy_file
5668**
5669** Specifying ":auto:" means that if there is a conch file with a matching
5670** host ID in it, the proxy path in the conch file will be used, otherwise
5671** a proxy path based on the user's temp dir
5672** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5673** actual proxy file name is generated from the name and path of the
5674** database file. For example:
5675**
5676** For database path "/Users/me/foo.db"
5677** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5678**
5679** Once a lock proxy is configured for a database connection, it can not
5680** be removed, however it may be switched to a different proxy path via
5681** the above APIs (assuming the conch file is not being held by another
5682** connection or process).
5683**
5684**
5685** How proxy locking works
5686** -----------------------
5687**
5688** Proxy file locking relies primarily on two new supporting files:
5689**
5690** * conch file to limit access to the database file to a single host
5691** at a time
5692**
5693** * proxy file to act as a proxy for the advisory locks normally
5694** taken on the database
5695**
5696** The conch file - to use a proxy file, sqlite must first "hold the conch"
5697** by taking an sqlite-style shared lock on the conch file, reading the
5698** contents and comparing the host's unique host ID (see below) and lock
5699** proxy path against the values stored in the conch. The conch file is
5700** stored in the same directory as the database file and the file name
5701** is patterned after the database file name as ".<databasename>-conch".
5702** If the conch file does not exist, or it's contents do not match the
5703** host ID and/or proxy path, then the lock is escalated to an exclusive
5704** lock and the conch file contents is updated with the host ID and proxy
5705** path and the lock is downgraded to a shared lock again. If the conch
5706** is held by another process (with a shared lock), the exclusive lock
5707** will fail and SQLITE_BUSY is returned.
5708**
5709** The proxy file - a single-byte file used for all advisory file locks
5710** normally taken on the database file. This allows for safe sharing
5711** of the database file for multiple readers and writers on the same
5712** host (the conch ensures that they all use the same local lock file).
5713**
drh715ff302008-12-03 22:32:44 +00005714** Requesting the lock proxy does not immediately take the conch, it is
5715** only taken when the first request to lock database file is made.
5716** This matches the semantics of the traditional locking behavior, where
5717** opening a connection to a database file does not take a lock on it.
5718** The shared lock and an open file descriptor are maintained until
5719** the connection to the database is closed.
5720**
5721** The proxy file and the lock file are never deleted so they only need
5722** to be created the first time they are used.
5723**
5724** Configuration options
5725** ---------------------
5726**
5727** SQLITE_PREFER_PROXY_LOCKING
5728**
5729** Database files accessed on non-local file systems are
5730** automatically configured for proxy locking, lock files are
5731** named automatically using the same logic as
5732** PRAGMA lock_proxy_file=":auto:"
5733**
5734** SQLITE_PROXY_DEBUG
5735**
5736** Enables the logging of error messages during host id file
5737** retrieval and creation
5738**
drh715ff302008-12-03 22:32:44 +00005739** LOCKPROXYDIR
5740**
5741** Overrides the default directory used for lock proxy files that
5742** are named automatically via the ":auto:" setting
5743**
5744** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5745**
5746** Permissions to use when creating a directory for storing the
5747** lock proxy files, only used when LOCKPROXYDIR is not set.
5748**
5749**
5750** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5751** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5752** force proxy locking to be used for every database file opened, and 0
5753** will force automatic proxy locking to be disabled for all database
5754** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5755** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5756*/
5757
5758/*
5759** Proxy locking is only available on MacOSX
5760*/
drhd2cb50b2009-01-09 21:41:17 +00005761#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005762
drh715ff302008-12-03 22:32:44 +00005763/*
5764** The proxyLockingContext has the path and file structures for the remote
5765** and local proxy files in it
5766*/
5767typedef struct proxyLockingContext proxyLockingContext;
5768struct proxyLockingContext {
5769 unixFile *conchFile; /* Open conch file */
5770 char *conchFilePath; /* Name of the conch file */
5771 unixFile *lockProxy; /* Open proxy lock file */
5772 char *lockProxyPath; /* Name of the proxy lock file */
5773 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005774 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005775 void *oldLockingContext; /* Original lockingcontext to restore on close */
5776 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5777};
5778
drh7ed97b92010-01-20 13:07:21 +00005779/*
5780** The proxy lock file path for the database at dbPath is written into lPath,
5781** which must point to valid, writable memory large enough for a maxLen length
5782** file path.
drh715ff302008-12-03 22:32:44 +00005783*/
drh715ff302008-12-03 22:32:44 +00005784static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5785 int len;
5786 int dbLen;
5787 int i;
5788
5789#ifdef LOCKPROXYDIR
5790 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5791#else
5792# ifdef _CS_DARWIN_USER_TEMP_DIR
5793 {
drh7ed97b92010-01-20 13:07:21 +00005794 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005795 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5796 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005797 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005798 }
drh7ed97b92010-01-20 13:07:21 +00005799 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005800 }
5801# else
5802 len = strlcpy(lPath, "/tmp/", maxLen);
5803# endif
5804#endif
5805
5806 if( lPath[len-1]!='/' ){
5807 len = strlcat(lPath, "/", maxLen);
5808 }
5809
5810 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005811 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005812 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005813 char c = dbPath[i];
5814 lPath[i+len] = (c=='/')?'_':c;
5815 }
5816 lPath[i+len]='\0';
5817 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005818 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005819 return SQLITE_OK;
5820}
5821
drh7ed97b92010-01-20 13:07:21 +00005822/*
5823 ** Creates the lock file and any missing directories in lockPath
5824 */
5825static int proxyCreateLockPath(const char *lockPath){
5826 int i, len;
5827 char buf[MAXPATHLEN];
5828 int start = 0;
5829
5830 assert(lockPath!=NULL);
5831 /* try to create all the intermediate directories */
5832 len = (int)strlen(lockPath);
5833 buf[0] = lockPath[0];
5834 for( i=1; i<len; i++ ){
5835 if( lockPath[i] == '/' && (i - start > 0) ){
5836 /* only mkdir if leaf dir != "." or "/" or ".." */
5837 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5838 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5839 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005840 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005841 int err=errno;
5842 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005843 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005844 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005845 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005846 return err;
5847 }
5848 }
5849 }
5850 start=i+1;
5851 }
5852 buf[i] = lockPath[i];
5853 }
drh308c2a52010-05-14 11:30:18 +00005854 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005855 return 0;
5856}
5857
drh715ff302008-12-03 22:32:44 +00005858/*
5859** Create a new VFS file descriptor (stored in memory obtained from
5860** sqlite3_malloc) and open the file named "path" in the file descriptor.
5861**
5862** The caller is responsible not only for closing the file descriptor
5863** but also for freeing the memory associated with the file descriptor.
5864*/
drh7ed97b92010-01-20 13:07:21 +00005865static int proxyCreateUnixFile(
5866 const char *path, /* path for the new unixFile */
5867 unixFile **ppFile, /* unixFile created and returned by ref */
5868 int islockfile /* if non zero missing dirs will be created */
5869) {
5870 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005871 unixFile *pNew;
5872 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005873 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005874 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005875 int terrno = 0;
5876 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005877
drh7ed97b92010-01-20 13:07:21 +00005878 /* 1. first try to open/create the file
5879 ** 2. if that fails, and this is a lock file (not-conch), try creating
5880 ** the parent directories and then try again.
5881 ** 3. if that fails, try to open the file read-only
5882 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5883 */
5884 pUnused = findReusableFd(path, openFlags);
5885 if( pUnused ){
5886 fd = pUnused->fd;
5887 }else{
5888 pUnused = sqlite3_malloc(sizeof(*pUnused));
5889 if( !pUnused ){
5890 return SQLITE_NOMEM;
5891 }
5892 }
5893 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00005894 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005895 terrno = errno;
5896 if( fd<0 && errno==ENOENT && islockfile ){
5897 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00005898 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005899 }
5900 }
5901 }
5902 if( fd<0 ){
5903 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00005904 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00005905 terrno = errno;
5906 }
5907 if( fd<0 ){
5908 if( islockfile ){
5909 return SQLITE_BUSY;
5910 }
5911 switch (terrno) {
5912 case EACCES:
5913 return SQLITE_PERM;
5914 case EIO:
5915 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5916 default:
drh9978c972010-02-23 17:36:32 +00005917 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005918 }
5919 }
5920
5921 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5922 if( pNew==NULL ){
5923 rc = SQLITE_NOMEM;
5924 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005925 }
5926 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005927 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005928 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005929 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005930 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005931 pUnused->fd = fd;
5932 pUnused->flags = openFlags;
5933 pNew->pUnused = pUnused;
5934
drhc02a43a2012-01-10 23:18:38 +00005935 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00005936 if( rc==SQLITE_OK ){
5937 *ppFile = pNew;
5938 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005939 }
drh7ed97b92010-01-20 13:07:21 +00005940end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005941 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005942 sqlite3_free(pNew);
5943 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005944 return rc;
5945}
5946
drh7ed97b92010-01-20 13:07:21 +00005947#ifdef SQLITE_TEST
5948/* simulate multiple hosts by creating unique hostid file paths */
5949int sqlite3_hostid_num = 0;
5950#endif
5951
5952#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5953
drh0ab216a2010-07-02 17:10:40 +00005954/* Not always defined in the headers as it ought to be */
5955extern int gethostuuid(uuid_t id, const struct timespec *wait);
5956
drh7ed97b92010-01-20 13:07:21 +00005957/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5958** bytes of writable memory.
5959*/
5960static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005961 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5962 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005963#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5964 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005965 {
5966 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5967 if( gethostuuid(pHostID, &timeout) ){
5968 int err = errno;
5969 if( pError ){
5970 *pError = err;
5971 }
5972 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005973 }
drh7ed97b92010-01-20 13:07:21 +00005974 }
drh3d4435b2011-08-26 20:55:50 +00005975#else
5976 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005977#endif
drh7ed97b92010-01-20 13:07:21 +00005978#ifdef SQLITE_TEST
5979 /* simulate multiple hosts by creating unique hostid file paths */
5980 if( sqlite3_hostid_num != 0){
5981 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5982 }
5983#endif
5984
5985 return SQLITE_OK;
5986}
5987
5988/* The conch file contains the header, host id and lock file path
5989 */
5990#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5991#define PROXY_HEADERLEN 1 /* conch file header length */
5992#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5993#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5994
5995/*
5996** Takes an open conch file, copies the contents to a new path and then moves
5997** it back. The newly created file's file descriptor is assigned to the
5998** conch file structure and finally the original conch file descriptor is
5999** closed. Returns zero if successful.
6000*/
6001static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6002 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6003 unixFile *conchFile = pCtx->conchFile;
6004 char tPath[MAXPATHLEN];
6005 char buf[PROXY_MAXCONCHLEN];
6006 char *cPath = pCtx->conchFilePath;
6007 size_t readLen = 0;
6008 size_t pathLen = 0;
6009 char errmsg[64] = "";
6010 int fd = -1;
6011 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006012 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006013
6014 /* create a new path by replace the trailing '-conch' with '-break' */
6015 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6016 if( pathLen>MAXPATHLEN || pathLen<6 ||
6017 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006018 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006019 goto end_breaklock;
6020 }
6021 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006022 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006023 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006024 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006025 goto end_breaklock;
6026 }
6027 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006028 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006029 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006030 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006031 goto end_breaklock;
6032 }
drhe562be52011-03-02 18:01:10 +00006033 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006034 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006035 goto end_breaklock;
6036 }
6037 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006038 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006039 goto end_breaklock;
6040 }
6041 rc = 0;
6042 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006043 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006044 conchFile->h = fd;
6045 conchFile->openFlags = O_RDWR | O_CREAT;
6046
6047end_breaklock:
6048 if( rc ){
6049 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006050 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006051 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006052 }
6053 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6054 }
6055 return rc;
6056}
6057
6058/* Take the requested lock on the conch file and break a stale lock if the
6059** host id matches.
6060*/
6061static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6062 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6063 unixFile *conchFile = pCtx->conchFile;
6064 int rc = SQLITE_OK;
6065 int nTries = 0;
6066 struct timespec conchModTime;
6067
drh3d4435b2011-08-26 20:55:50 +00006068 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006069 do {
6070 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6071 nTries ++;
6072 if( rc==SQLITE_BUSY ){
6073 /* If the lock failed (busy):
6074 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6075 * 2nd try: fail if the mod time changed or host id is different, wait
6076 * 10 sec and try again
6077 * 3rd try: break the lock unless the mod time has changed.
6078 */
6079 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006080 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006081 pFile->lastErrno = errno;
6082 return SQLITE_IOERR_LOCK;
6083 }
6084
6085 if( nTries==1 ){
6086 conchModTime = buf.st_mtimespec;
6087 usleep(500000); /* wait 0.5 sec and try the lock again*/
6088 continue;
6089 }
6090
6091 assert( nTries>1 );
6092 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6093 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6094 return SQLITE_BUSY;
6095 }
6096
6097 if( nTries==2 ){
6098 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006099 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006100 if( len<0 ){
6101 pFile->lastErrno = errno;
6102 return SQLITE_IOERR_LOCK;
6103 }
6104 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6105 /* don't break the lock if the host id doesn't match */
6106 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6107 return SQLITE_BUSY;
6108 }
6109 }else{
6110 /* don't break the lock on short read or a version mismatch */
6111 return SQLITE_BUSY;
6112 }
6113 usleep(10000000); /* wait 10 sec and try the lock again */
6114 continue;
6115 }
6116
6117 assert( nTries==3 );
6118 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6119 rc = SQLITE_OK;
6120 if( lockType==EXCLUSIVE_LOCK ){
6121 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6122 }
6123 if( !rc ){
6124 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6125 }
6126 }
6127 }
6128 } while( rc==SQLITE_BUSY && nTries<3 );
6129
6130 return rc;
6131}
6132
6133/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006134** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6135** lockPath means that the lockPath in the conch file will be used if the
6136** host IDs match, or a new lock path will be generated automatically
6137** and written to the conch file.
6138*/
6139static int proxyTakeConch(unixFile *pFile){
6140 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6141
drh7ed97b92010-01-20 13:07:21 +00006142 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006143 return SQLITE_OK;
6144 }else{
6145 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006146 uuid_t myHostID;
6147 int pError = 0;
6148 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006149 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006150 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006151 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006152 int createConch = 0;
6153 int hostIdMatch = 0;
6154 int readLen = 0;
6155 int tryOldLockPath = 0;
6156 int forceNewLockPath = 0;
6157
drh308c2a52010-05-14 11:30:18 +00006158 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6159 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006160
drh7ed97b92010-01-20 13:07:21 +00006161 rc = proxyGetHostID(myHostID, &pError);
6162 if( (rc&0xff)==SQLITE_IOERR ){
6163 pFile->lastErrno = pError;
6164 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006165 }
drh7ed97b92010-01-20 13:07:21 +00006166 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006167 if( rc!=SQLITE_OK ){
6168 goto end_takeconch;
6169 }
drh7ed97b92010-01-20 13:07:21 +00006170 /* read the existing conch file */
6171 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6172 if( readLen<0 ){
6173 /* I/O error: lastErrno set by seekAndRead */
6174 pFile->lastErrno = conchFile->lastErrno;
6175 rc = SQLITE_IOERR_READ;
6176 goto end_takeconch;
6177 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6178 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6179 /* a short read or version format mismatch means we need to create a new
6180 ** conch file.
6181 */
6182 createConch = 1;
6183 }
6184 /* if the host id matches and the lock path already exists in the conch
6185 ** we'll try to use the path there, if we can't open that path, we'll
6186 ** retry with a new auto-generated path
6187 */
6188 do { /* in case we need to try again for an :auto: named lock file */
6189
6190 if( !createConch && !forceNewLockPath ){
6191 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6192 PROXY_HOSTIDLEN);
6193 /* if the conch has data compare the contents */
6194 if( !pCtx->lockProxyPath ){
6195 /* for auto-named local lock file, just check the host ID and we'll
6196 ** use the local lock file path that's already in there
6197 */
6198 if( hostIdMatch ){
6199 size_t pathLen = (readLen - PROXY_PATHINDEX);
6200
6201 if( pathLen>=MAXPATHLEN ){
6202 pathLen=MAXPATHLEN-1;
6203 }
6204 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6205 lockPath[pathLen] = 0;
6206 tempLockPath = lockPath;
6207 tryOldLockPath = 1;
6208 /* create a copy of the lock path if the conch is taken */
6209 goto end_takeconch;
6210 }
6211 }else if( hostIdMatch
6212 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6213 readLen-PROXY_PATHINDEX)
6214 ){
6215 /* conch host and lock path match */
6216 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006217 }
drh7ed97b92010-01-20 13:07:21 +00006218 }
6219
6220 /* if the conch isn't writable and doesn't match, we can't take it */
6221 if( (conchFile->openFlags&O_RDWR) == 0 ){
6222 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006223 goto end_takeconch;
6224 }
drh7ed97b92010-01-20 13:07:21 +00006225
6226 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006227 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006228 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6229 tempLockPath = lockPath;
6230 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006231 }
drh7ed97b92010-01-20 13:07:21 +00006232
6233 /* update conch with host and path (this will fail if other process
6234 ** has a shared lock already), if the host id matches, use the big
6235 ** stick.
drh715ff302008-12-03 22:32:44 +00006236 */
drh7ed97b92010-01-20 13:07:21 +00006237 futimes(conchFile->h, NULL);
6238 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006239 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006240 /* We are trying for an exclusive lock but another thread in this
6241 ** same process is still holding a shared lock. */
6242 rc = SQLITE_BUSY;
6243 } else {
6244 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006245 }
drh715ff302008-12-03 22:32:44 +00006246 }else{
drh7ed97b92010-01-20 13:07:21 +00006247 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006248 }
drh7ed97b92010-01-20 13:07:21 +00006249 if( rc==SQLITE_OK ){
6250 char writeBuffer[PROXY_MAXCONCHLEN];
6251 int writeSize = 0;
6252
6253 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6254 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6255 if( pCtx->lockProxyPath!=NULL ){
6256 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6257 }else{
6258 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6259 }
6260 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006261 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006262 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6263 fsync(conchFile->h);
6264 /* If we created a new conch file (not just updated the contents of a
6265 ** valid conch file), try to match the permissions of the database
6266 */
6267 if( rc==SQLITE_OK && createConch ){
6268 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006269 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006270 if( err==0 ){
6271 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6272 S_IROTH|S_IWOTH);
6273 /* try to match the database file R/W permissions, ignore failure */
6274#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006275 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006276#else
drhff812312011-02-23 13:33:46 +00006277 do{
drhe562be52011-03-02 18:01:10 +00006278 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006279 }while( rc==(-1) && errno==EINTR );
6280 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006281 int code = errno;
6282 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6283 cmode, code, strerror(code));
6284 } else {
6285 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6286 }
6287 }else{
6288 int code = errno;
6289 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6290 err, code, strerror(code));
6291#endif
6292 }
drh715ff302008-12-03 22:32:44 +00006293 }
6294 }
drh7ed97b92010-01-20 13:07:21 +00006295 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6296
6297 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006298 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006299 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006300 int fd;
drh7ed97b92010-01-20 13:07:21 +00006301 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006302 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006303 }
6304 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006305 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006306 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006307 if( fd>=0 ){
6308 pFile->h = fd;
6309 }else{
drh9978c972010-02-23 17:36:32 +00006310 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006311 during locking */
6312 }
6313 }
6314 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6315 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6316 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6317 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6318 /* we couldn't create the proxy lock file with the old lock file path
6319 ** so try again via auto-naming
6320 */
6321 forceNewLockPath = 1;
6322 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006323 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006324 }
6325 }
6326 if( rc==SQLITE_OK ){
6327 /* Need to make a copy of path if we extracted the value
6328 ** from the conch file or the path was allocated on the stack
6329 */
6330 if( tempLockPath ){
6331 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6332 if( !pCtx->lockProxyPath ){
6333 rc = SQLITE_NOMEM;
6334 }
6335 }
6336 }
6337 if( rc==SQLITE_OK ){
6338 pCtx->conchHeld = 1;
6339
6340 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6341 afpLockingContext *afpCtx;
6342 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6343 afpCtx->dbPath = pCtx->lockProxyPath;
6344 }
6345 } else {
6346 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6347 }
drh308c2a52010-05-14 11:30:18 +00006348 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6349 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006350 return rc;
drh308c2a52010-05-14 11:30:18 +00006351 } while (1); /* in case we need to retry the :auto: lock file -
6352 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006353 }
6354}
6355
6356/*
6357** If pFile holds a lock on a conch file, then release that lock.
6358*/
6359static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006360 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006361 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6362 unixFile *conchFile; /* Name of the conch file */
6363
6364 pCtx = (proxyLockingContext *)pFile->lockingContext;
6365 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006366 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006367 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006368 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006369 if( pCtx->conchHeld>0 ){
6370 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6371 }
drh715ff302008-12-03 22:32:44 +00006372 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006373 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6374 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006375 return rc;
6376}
6377
6378/*
6379** Given the name of a database file, compute the name of its conch file.
6380** Store the conch filename in memory obtained from sqlite3_malloc().
6381** Make *pConchPath point to the new name. Return SQLITE_OK on success
6382** or SQLITE_NOMEM if unable to obtain memory.
6383**
6384** The caller is responsible for ensuring that the allocated memory
6385** space is eventually freed.
6386**
6387** *pConchPath is set to NULL if a memory allocation error occurs.
6388*/
6389static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6390 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006391 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006392 char *conchPath; /* buffer in which to construct conch name */
6393
6394 /* Allocate space for the conch filename and initialize the name to
6395 ** the name of the original database file. */
6396 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6397 if( conchPath==0 ){
6398 return SQLITE_NOMEM;
6399 }
6400 memcpy(conchPath, dbPath, len+1);
6401
6402 /* now insert a "." before the last / character */
6403 for( i=(len-1); i>=0; i-- ){
6404 if( conchPath[i]=='/' ){
6405 i++;
6406 break;
6407 }
6408 }
6409 conchPath[i]='.';
6410 while ( i<len ){
6411 conchPath[i+1]=dbPath[i];
6412 i++;
6413 }
6414
6415 /* append the "-conch" suffix to the file */
6416 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006417 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006418
6419 return SQLITE_OK;
6420}
6421
6422
6423/* Takes a fully configured proxy locking-style unix file and switches
6424** the local lock file path
6425*/
6426static int switchLockProxyPath(unixFile *pFile, const char *path) {
6427 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6428 char *oldPath = pCtx->lockProxyPath;
6429 int rc = SQLITE_OK;
6430
drh308c2a52010-05-14 11:30:18 +00006431 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006432 return SQLITE_BUSY;
6433 }
6434
6435 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6436 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6437 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6438 return SQLITE_OK;
6439 }else{
6440 unixFile *lockProxy = pCtx->lockProxy;
6441 pCtx->lockProxy=NULL;
6442 pCtx->conchHeld = 0;
6443 if( lockProxy!=NULL ){
6444 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6445 if( rc ) return rc;
6446 sqlite3_free(lockProxy);
6447 }
6448 sqlite3_free(oldPath);
6449 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6450 }
6451
6452 return rc;
6453}
6454
6455/*
6456** pFile is a file that has been opened by a prior xOpen call. dbPath
6457** is a string buffer at least MAXPATHLEN+1 characters in size.
6458**
6459** This routine find the filename associated with pFile and writes it
6460** int dbPath.
6461*/
6462static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006463#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006464 if( pFile->pMethod == &afpIoMethods ){
6465 /* afp style keeps a reference to the db path in the filePath field
6466 ** of the struct */
drhea678832008-12-10 19:26:22 +00006467 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006468 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6469 } else
drh715ff302008-12-03 22:32:44 +00006470#endif
6471 if( pFile->pMethod == &dotlockIoMethods ){
6472 /* dot lock style uses the locking context to store the dot lock
6473 ** file path */
6474 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6475 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6476 }else{
6477 /* all other styles use the locking context to store the db file path */
6478 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006479 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006480 }
6481 return SQLITE_OK;
6482}
6483
6484/*
6485** Takes an already filled in unix file and alters it so all file locking
6486** will be performed on the local proxy lock file. The following fields
6487** are preserved in the locking context so that they can be restored and
6488** the unix structure properly cleaned up at close time:
6489** ->lockingContext
6490** ->pMethod
6491*/
6492static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6493 proxyLockingContext *pCtx;
6494 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6495 char *lockPath=NULL;
6496 int rc = SQLITE_OK;
6497
drh308c2a52010-05-14 11:30:18 +00006498 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006499 return SQLITE_BUSY;
6500 }
6501 proxyGetDbPathForUnixFile(pFile, dbPath);
6502 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6503 lockPath=NULL;
6504 }else{
6505 lockPath=(char *)path;
6506 }
6507
drh308c2a52010-05-14 11:30:18 +00006508 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6509 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006510
6511 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6512 if( pCtx==0 ){
6513 return SQLITE_NOMEM;
6514 }
6515 memset(pCtx, 0, sizeof(*pCtx));
6516
6517 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6518 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006519 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6520 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6521 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6522 ** (c) the file system is read-only, then enable no-locking access.
6523 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6524 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6525 */
6526 struct statfs fsInfo;
6527 struct stat conchInfo;
6528 int goLockless = 0;
6529
drh99ab3b12011-03-02 15:09:07 +00006530 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006531 int err = errno;
6532 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6533 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6534 }
6535 }
6536 if( goLockless ){
6537 pCtx->conchHeld = -1; /* read only FS/ lockless */
6538 rc = SQLITE_OK;
6539 }
6540 }
drh715ff302008-12-03 22:32:44 +00006541 }
6542 if( rc==SQLITE_OK && lockPath ){
6543 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6544 }
6545
6546 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006547 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6548 if( pCtx->dbPath==NULL ){
6549 rc = SQLITE_NOMEM;
6550 }
6551 }
6552 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006553 /* all memory is allocated, proxys are created and assigned,
6554 ** switch the locking context and pMethod then return.
6555 */
drh715ff302008-12-03 22:32:44 +00006556 pCtx->oldLockingContext = pFile->lockingContext;
6557 pFile->lockingContext = pCtx;
6558 pCtx->pOldMethod = pFile->pMethod;
6559 pFile->pMethod = &proxyIoMethods;
6560 }else{
6561 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006562 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006563 sqlite3_free(pCtx->conchFile);
6564 }
drhd56b1212010-08-11 06:14:15 +00006565 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006566 sqlite3_free(pCtx->conchFilePath);
6567 sqlite3_free(pCtx);
6568 }
drh308c2a52010-05-14 11:30:18 +00006569 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6570 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006571 return rc;
6572}
6573
6574
6575/*
6576** This routine handles sqlite3_file_control() calls that are specific
6577** to proxy locking.
6578*/
6579static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6580 switch( op ){
6581 case SQLITE_GET_LOCKPROXYFILE: {
6582 unixFile *pFile = (unixFile*)id;
6583 if( pFile->pMethod == &proxyIoMethods ){
6584 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6585 proxyTakeConch(pFile);
6586 if( pCtx->lockProxyPath ){
6587 *(const char **)pArg = pCtx->lockProxyPath;
6588 }else{
6589 *(const char **)pArg = ":auto: (not held)";
6590 }
6591 } else {
6592 *(const char **)pArg = NULL;
6593 }
6594 return SQLITE_OK;
6595 }
6596 case SQLITE_SET_LOCKPROXYFILE: {
6597 unixFile *pFile = (unixFile*)id;
6598 int rc = SQLITE_OK;
6599 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6600 if( pArg==NULL || (const char *)pArg==0 ){
6601 if( isProxyStyle ){
6602 /* turn off proxy locking - not supported */
6603 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6604 }else{
6605 /* turn off proxy locking - already off - NOOP */
6606 rc = SQLITE_OK;
6607 }
6608 }else{
6609 const char *proxyPath = (const char *)pArg;
6610 if( isProxyStyle ){
6611 proxyLockingContext *pCtx =
6612 (proxyLockingContext*)pFile->lockingContext;
6613 if( !strcmp(pArg, ":auto:")
6614 || (pCtx->lockProxyPath &&
6615 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6616 ){
6617 rc = SQLITE_OK;
6618 }else{
6619 rc = switchLockProxyPath(pFile, proxyPath);
6620 }
6621 }else{
6622 /* turn on proxy file locking */
6623 rc = proxyTransformUnixFile(pFile, proxyPath);
6624 }
6625 }
6626 return rc;
6627 }
6628 default: {
6629 assert( 0 ); /* The call assures that only valid opcodes are sent */
6630 }
6631 }
6632 /*NOTREACHED*/
6633 return SQLITE_ERROR;
6634}
6635
6636/*
6637** Within this division (the proxying locking implementation) the procedures
6638** above this point are all utilities. The lock-related methods of the
6639** proxy-locking sqlite3_io_method object follow.
6640*/
6641
6642
6643/*
6644** This routine checks if there is a RESERVED lock held on the specified
6645** file by this or any other process. If such a lock is held, set *pResOut
6646** to a non-zero value otherwise *pResOut is set to zero. The return value
6647** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6648*/
6649static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6650 unixFile *pFile = (unixFile*)id;
6651 int rc = proxyTakeConch(pFile);
6652 if( rc==SQLITE_OK ){
6653 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006654 if( pCtx->conchHeld>0 ){
6655 unixFile *proxy = pCtx->lockProxy;
6656 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6657 }else{ /* conchHeld < 0 is lockless */
6658 pResOut=0;
6659 }
drh715ff302008-12-03 22:32:44 +00006660 }
6661 return rc;
6662}
6663
6664/*
drh308c2a52010-05-14 11:30:18 +00006665** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006666** of the following:
6667**
6668** (1) SHARED_LOCK
6669** (2) RESERVED_LOCK
6670** (3) PENDING_LOCK
6671** (4) EXCLUSIVE_LOCK
6672**
6673** Sometimes when requesting one lock state, additional lock states
6674** are inserted in between. The locking might fail on one of the later
6675** transitions leaving the lock state different from what it started but
6676** still short of its goal. The following chart shows the allowed
6677** transitions and the inserted intermediate states:
6678**
6679** UNLOCKED -> SHARED
6680** SHARED -> RESERVED
6681** SHARED -> (PENDING) -> EXCLUSIVE
6682** RESERVED -> (PENDING) -> EXCLUSIVE
6683** PENDING -> EXCLUSIVE
6684**
6685** This routine will only increase a lock. Use the sqlite3OsUnlock()
6686** routine to lower a locking level.
6687*/
drh308c2a52010-05-14 11:30:18 +00006688static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006689 unixFile *pFile = (unixFile*)id;
6690 int rc = proxyTakeConch(pFile);
6691 if( rc==SQLITE_OK ){
6692 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006693 if( pCtx->conchHeld>0 ){
6694 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006695 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6696 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006697 }else{
6698 /* conchHeld < 0 is lockless */
6699 }
drh715ff302008-12-03 22:32:44 +00006700 }
6701 return rc;
6702}
6703
6704
6705/*
drh308c2a52010-05-14 11:30:18 +00006706** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006707** must be either NO_LOCK or SHARED_LOCK.
6708**
6709** If the locking level of the file descriptor is already at or below
6710** the requested locking level, this routine is a no-op.
6711*/
drh308c2a52010-05-14 11:30:18 +00006712static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006713 unixFile *pFile = (unixFile*)id;
6714 int rc = proxyTakeConch(pFile);
6715 if( rc==SQLITE_OK ){
6716 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006717 if( pCtx->conchHeld>0 ){
6718 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006719 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6720 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006721 }else{
6722 /* conchHeld < 0 is lockless */
6723 }
drh715ff302008-12-03 22:32:44 +00006724 }
6725 return rc;
6726}
6727
6728/*
6729** Close a file that uses proxy locks.
6730*/
6731static int proxyClose(sqlite3_file *id) {
6732 if( id ){
6733 unixFile *pFile = (unixFile*)id;
6734 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6735 unixFile *lockProxy = pCtx->lockProxy;
6736 unixFile *conchFile = pCtx->conchFile;
6737 int rc = SQLITE_OK;
6738
6739 if( lockProxy ){
6740 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6741 if( rc ) return rc;
6742 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6743 if( rc ) return rc;
6744 sqlite3_free(lockProxy);
6745 pCtx->lockProxy = 0;
6746 }
6747 if( conchFile ){
6748 if( pCtx->conchHeld ){
6749 rc = proxyReleaseConch(pFile);
6750 if( rc ) return rc;
6751 }
6752 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6753 if( rc ) return rc;
6754 sqlite3_free(conchFile);
6755 }
drhd56b1212010-08-11 06:14:15 +00006756 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006757 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006758 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006759 /* restore the original locking context and pMethod then close it */
6760 pFile->lockingContext = pCtx->oldLockingContext;
6761 pFile->pMethod = pCtx->pOldMethod;
6762 sqlite3_free(pCtx);
6763 return pFile->pMethod->xClose(id);
6764 }
6765 return SQLITE_OK;
6766}
6767
6768
6769
drhd2cb50b2009-01-09 21:41:17 +00006770#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006771/*
6772** The proxy locking style is intended for use with AFP filesystems.
6773** And since AFP is only supported on MacOSX, the proxy locking is also
6774** restricted to MacOSX.
6775**
6776**
6777******************* End of the proxy lock implementation **********************
6778******************************************************************************/
6779
drh734c9862008-11-28 15:37:20 +00006780/*
danielk1977e339d652008-06-28 11:23:00 +00006781** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006782**
6783** This routine registers all VFS implementations for unix-like operating
6784** systems. This routine, and the sqlite3_os_end() routine that follows,
6785** should be the only routines in this file that are visible from other
6786** files.
drh6b9d6dd2008-12-03 19:34:47 +00006787**
6788** This routine is called once during SQLite initialization and by a
6789** single thread. The memory allocation and mutex subsystems have not
6790** necessarily been initialized when this routine is called, and so they
6791** should not be used.
drh153c62c2007-08-24 03:51:33 +00006792*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006793int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006794 /*
6795 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006796 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6797 ** to the "finder" function. (pAppData is a pointer to a pointer because
6798 ** silly C90 rules prohibit a void* from being cast to a function pointer
6799 ** and so we have to go through the intermediate pointer to avoid problems
6800 ** when compiling with -pedantic-errors on GCC.)
6801 **
6802 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006803 ** finder-function. The finder-function returns a pointer to the
6804 ** sqlite_io_methods object that implements the desired locking
6805 ** behaviors. See the division above that contains the IOMETHODS
6806 ** macro for addition information on finder-functions.
6807 **
6808 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6809 ** object. But the "autolockIoFinder" available on MacOSX does a little
6810 ** more than that; it looks at the filesystem type that hosts the
6811 ** database file and tries to choose an locking method appropriate for
6812 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006813 */
drh7708e972008-11-29 00:56:52 +00006814 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006815 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006816 sizeof(unixFile), /* szOsFile */ \
6817 MAX_PATHNAME, /* mxPathname */ \
6818 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006819 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006820 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006821 unixOpen, /* xOpen */ \
6822 unixDelete, /* xDelete */ \
6823 unixAccess, /* xAccess */ \
6824 unixFullPathname, /* xFullPathname */ \
6825 unixDlOpen, /* xDlOpen */ \
6826 unixDlError, /* xDlError */ \
6827 unixDlSym, /* xDlSym */ \
6828 unixDlClose, /* xDlClose */ \
6829 unixRandomness, /* xRandomness */ \
6830 unixSleep, /* xSleep */ \
6831 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006832 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006833 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006834 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006835 unixGetSystemCall, /* xGetSystemCall */ \
6836 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006837 }
6838
drh6b9d6dd2008-12-03 19:34:47 +00006839 /*
6840 ** All default VFSes for unix are contained in the following array.
6841 **
6842 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6843 ** by the SQLite core when the VFS is registered. So the following
6844 ** array cannot be const.
6845 */
danielk1977e339d652008-06-28 11:23:00 +00006846 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006847#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006848 UNIXVFS("unix", autolockIoFinder ),
6849#else
6850 UNIXVFS("unix", posixIoFinder ),
6851#endif
6852 UNIXVFS("unix-none", nolockIoFinder ),
6853 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006854 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006855#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006856 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006857#endif
6858#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006859 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006860#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006861 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006862#endif
chw78a13182009-04-07 05:35:03 +00006863#endif
drhd2cb50b2009-01-09 21:41:17 +00006864#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006865 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006866 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006867 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006868#endif
drh153c62c2007-08-24 03:51:33 +00006869 };
drh6b9d6dd2008-12-03 19:34:47 +00006870 unsigned int i; /* Loop counter */
6871
drh2aa5a002011-04-13 13:42:25 +00006872 /* Double-check that the aSyscall[] array has been constructed
6873 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh8c815d12012-02-13 20:16:37 +00006874 assert( ArraySize(aSyscall)==22 );
drh2aa5a002011-04-13 13:42:25 +00006875
drh6b9d6dd2008-12-03 19:34:47 +00006876 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006877 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006878 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006879 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006880 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006881}
danielk1977e339d652008-06-28 11:23:00 +00006882
6883/*
drh6b9d6dd2008-12-03 19:34:47 +00006884** Shutdown the operating system interface.
6885**
6886** Some operating systems might need to do some cleanup in this routine,
6887** to release dynamically allocated objects. But not on unix.
6888** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006889*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006890int sqlite3_os_end(void){
6891 return SQLITE_OK;
6892}
drhdce8bdb2007-08-16 13:01:44 +00006893
danielk197729bafea2008-06-26 10:41:19 +00006894#endif /* SQLITE_OS_UNIX */