blob: b717a08d72b7c8a2ca7e7ba61111a50d75a7cb86 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
drh1da88f02011-12-17 16:09:16 +0000125
danielk1977e339d652008-06-28 11:23:00 +0000126
drh40bbb0a2008-09-23 10:23:26 +0000127#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000129# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <semaphore.h>
131# include <limits.h>
132# else
drh9b35ea62008-11-29 02:20:26 +0000133# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000135# endif
drhbfe66312006-10-03 17:40:40 +0000136#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000137
drhf8b4d8c2010-03-05 13:53:22 +0000138#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000139# include <sys/mount.h>
140#endif
141
drhdbe4b882011-06-20 18:00:17 +0000142#ifdef HAVE_UTIME
143# include <utime.h>
144#endif
145
drh9cbe6352005-11-29 03:13:21 +0000146/*
drh7ed97b92010-01-20 13:07:21 +0000147** Allowed values of unixFile.fsFlags
148*/
149#define SQLITE_FSFLAGS_IS_MSDOS 0x1
150
151/*
drhf1a221e2006-01-15 17:27:17 +0000152** If we are to be thread-safe, include the pthreads header and define
153** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000154*/
drhd677b3d2007-08-20 22:48:41 +0000155#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000156# include <pthread.h>
157# define SQLITE_UNIX_THREADS 1
158#endif
159
160/*
161** Default permissions when creating a new file
162*/
163#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
164# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
165#endif
166
danielk1977b4b47412007-08-17 15:53:36 +0000167/*
aswiftaebf4132008-11-21 00:10:35 +0000168 ** Default permissions when creating auto proxy dir
169 */
170#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
171# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
172#endif
173
174/*
danielk1977b4b47412007-08-17 15:53:36 +0000175** Maximum supported path-length.
176*/
177#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000178
drh734c9862008-11-28 15:37:20 +0000179/*
drh734c9862008-11-28 15:37:20 +0000180** Only set the lastErrno if the error code is a real error and not
181** a normal expected return code of SQLITE_BUSY or SQLITE_OK
182*/
183#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
184
drhd91c68f2010-05-14 14:52:25 +0000185/* Forward references */
186typedef struct unixShm unixShm; /* Connection shared memory */
187typedef struct unixShmNode unixShmNode; /* Shared memory instance */
188typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
189typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000190
191/*
dane946c392009-08-22 11:39:46 +0000192** Sometimes, after a file handle is closed by SQLite, the file descriptor
193** cannot be closed immediately. In these cases, instances of the following
194** structure are used to store the file descriptor while waiting for an
195** opportunity to either close or reuse it.
196*/
dane946c392009-08-22 11:39:46 +0000197struct UnixUnusedFd {
198 int fd; /* File descriptor to close */
199 int flags; /* Flags this file descriptor was opened with */
200 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
201};
202
203/*
drh9b35ea62008-11-29 02:20:26 +0000204** The unixFile structure is subclass of sqlite3_file specific to the unix
205** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000206*/
drh054889e2005-11-30 03:20:31 +0000207typedef struct unixFile unixFile;
208struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000209 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000210 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000211 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000212 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000213 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000214 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000215 int lastErrno; /* The unix errno from last I/O error */
216 void *lockingContext; /* Locking style specific state */
217 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000218 const char *zPath; /* Name of the file */
219 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000220 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000221#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000222 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000223#endif
drh7ed97b92010-01-20 13:07:21 +0000224#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000225 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000226#endif
227#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000228 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000229#endif
drh8f941bc2009-01-14 23:03:40 +0000230#ifndef NDEBUG
231 /* The next group of variables are used to track whether or not the
232 ** transaction counter in bytes 24-27 of database files are updated
233 ** whenever any part of the database changes. An assertion fault will
234 ** occur if a file is updated without also updating the transaction
235 ** counter. This test is made to avoid new problems similar to the
236 ** one described by ticket #3584.
237 */
238 unsigned char transCntrChng; /* True if the transaction counter changed */
239 unsigned char dbUpdate; /* True if any part of database file changed */
240 unsigned char inNormalWrite; /* True if in a normal write operation */
241#endif
danielk1977967a4a12007-08-20 14:23:44 +0000242#ifdef SQLITE_TEST
243 /* In test mode, increase the size of this structure a bit so that
244 ** it is larger than the struct CrashFile defined in test6.c.
245 */
246 char aPadding[32];
247#endif
drh9cbe6352005-11-29 03:13:21 +0000248};
249
drh0ccebe72005-06-07 22:22:50 +0000250/*
drha7e61d82011-03-12 17:02:57 +0000251** Allowed values for the unixFile.ctrlFlags bitmask:
252*/
drhf0b190d2011-07-26 16:03:07 +0000253#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
254#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
255#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000256#ifndef SQLITE_DISABLE_DIRSYNC
257# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
258#else
259# define UNIXFILE_DIRSYNC 0x00
260#endif
drhcb15f352011-12-23 01:04:17 +0000261#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000262#define UNIXFILE_DELETE 0x20 /* Delete on close */
263#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
264#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
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
drh90315a22011-08-10 01:52:12 +0000310/* Forward reference */
311static int openDirectory(const char*, int*);
312
drh9a3baf12011-04-25 18:01:27 +0000313/*
drh99ab3b12011-03-02 15:09:07 +0000314** Many system calls are accessed through pointer-to-functions so that
315** they may be overridden at runtime to facilitate fault injection during
316** testing and sandboxing. The following array holds the names and pointers
317** to all overrideable system calls.
318*/
319static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000320 const char *zName; /* Name of the sytem call */
321 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
322 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000323} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000324 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
325#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000326
drh58ad5802011-03-23 22:02:23 +0000327 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000328#define osClose ((int(*)(int))aSyscall[1].pCurrent)
329
drh58ad5802011-03-23 22:02:23 +0000330 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000331#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
332
drh58ad5802011-03-23 22:02:23 +0000333 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000334#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
335
drh58ad5802011-03-23 22:02:23 +0000336 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000337#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
338
339/*
340** The DJGPP compiler environment looks mostly like Unix, but it
341** lacks the fcntl() system call. So redefine fcntl() to be something
342** that always succeeds. This means that locking does not occur under
343** DJGPP. But it is DOS - what did you expect?
344*/
345#ifdef __DJGPP__
346 { "fstat", 0, 0 },
347#define osFstat(a,b,c) 0
348#else
drh58ad5802011-03-23 22:02:23 +0000349 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000350#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
351#endif
352
drh58ad5802011-03-23 22:02:23 +0000353 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000354#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
355
drh58ad5802011-03-23 22:02:23 +0000356 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000357#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000358
drh58ad5802011-03-23 22:02:23 +0000359 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000360#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
361
drhd4a80312011-04-15 14:33:20 +0000362#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000363 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000364#else
drh58ad5802011-03-23 22:02:23 +0000365 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000366#endif
367#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
368
369#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000370 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000371#else
drh58ad5802011-03-23 22:02:23 +0000372 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000373#endif
374#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
375
drh58ad5802011-03-23 22:02:23 +0000376 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000377#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
378
drhd4a80312011-04-15 14:33:20 +0000379#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000380 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000381#else
drh58ad5802011-03-23 22:02:23 +0000382 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000383#endif
384#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
385 aSyscall[12].pCurrent)
386
387#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000388 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000389#else
drh58ad5802011-03-23 22:02:23 +0000390 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000391#endif
392#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
393 aSyscall[13].pCurrent)
394
drha6c47492011-04-11 18:35:09 +0000395#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000396 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000397#else
398 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000399#endif
drh2aa5a002011-04-13 13:42:25 +0000400#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000401
402#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000403 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000404#else
drh58ad5802011-03-23 22:02:23 +0000405 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000406#endif
dan0fd7d862011-03-29 10:04:23 +0000407#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000408
drh036ac7f2011-08-08 23:18:05 +0000409 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
410#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
411
drh90315a22011-08-10 01:52:12 +0000412 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
413#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
414
drh9ef6bc42011-11-04 02:24:02 +0000415 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
416#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
417
418 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
419#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
420
drhe562be52011-03-02 18:01:10 +0000421}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000422
423/*
424** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000425** "unix" VFSes. Return SQLITE_OK opon successfully updating the
426** system call pointer, or SQLITE_NOTFOUND if there is no configurable
427** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000428*/
429static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000430 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
431 const char *zName, /* Name of system call to override */
432 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000433){
drh58ad5802011-03-23 22:02:23 +0000434 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000435 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000436
437 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000438 if( zName==0 ){
439 /* If no zName is given, restore all system calls to their default
440 ** settings and return NULL
441 */
dan51438a72011-04-02 17:00:47 +0000442 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000443 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
444 if( aSyscall[i].pDefault ){
445 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000446 }
447 }
448 }else{
449 /* If zName is specified, operate on only the one system call
450 ** specified.
451 */
452 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
453 if( strcmp(zName, aSyscall[i].zName)==0 ){
454 if( aSyscall[i].pDefault==0 ){
455 aSyscall[i].pDefault = aSyscall[i].pCurrent;
456 }
drh1df30962011-03-02 19:06:42 +0000457 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000458 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
459 aSyscall[i].pCurrent = pNewFunc;
460 break;
461 }
462 }
463 }
464 return rc;
465}
466
drh1df30962011-03-02 19:06:42 +0000467/*
468** Return the value of a system call. Return NULL if zName is not a
469** recognized system call name. NULL is also returned if the system call
470** is currently undefined.
471*/
drh58ad5802011-03-23 22:02:23 +0000472static sqlite3_syscall_ptr unixGetSystemCall(
473 sqlite3_vfs *pNotUsed,
474 const char *zName
475){
476 unsigned int i;
477
478 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000479 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
480 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
481 }
482 return 0;
483}
484
485/*
486** Return the name of the first system call after zName. If zName==NULL
487** then return the name of the first system call. Return NULL if zName
488** is the last system call or if zName is not the name of a valid
489** system call.
490*/
491static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000492 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000493
494 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000495 if( zName ){
496 for(i=0; i<ArraySize(aSyscall)-1; i++){
497 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000498 }
499 }
dan0fd7d862011-03-29 10:04:23 +0000500 for(i++; i<ArraySize(aSyscall); i++){
501 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000502 }
503 return 0;
504}
505
drhad4f1e52011-03-04 15:43:57 +0000506/*
507** Retry open() calls that fail due to EINTR
508*/
509static int robust_open(const char *z, int f, int m){
510 int rc;
511 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
512 return rc;
513}
danielk197713adf8a2004-06-03 16:08:41 +0000514
drh107886a2008-11-21 22:21:50 +0000515/*
dan9359c7b2009-08-21 08:29:10 +0000516** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000517** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000518** vxworksFileId objects used by this file, all of which may be
519** shared by multiple threads.
520**
521** Function unixMutexHeld() is used to assert() that the global mutex
522** is held when required. This function is only used as part of assert()
523** statements. e.g.
524**
525** unixEnterMutex()
526** assert( unixMutexHeld() );
527** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000528*/
529static void unixEnterMutex(void){
530 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
531}
532static void unixLeaveMutex(void){
533 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
534}
dan9359c7b2009-08-21 08:29:10 +0000535#ifdef SQLITE_DEBUG
536static int unixMutexHeld(void) {
537 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
538}
539#endif
drh107886a2008-11-21 22:21:50 +0000540
drh734c9862008-11-28 15:37:20 +0000541
drh30ddce62011-10-15 00:16:30 +0000542#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000543/*
544** Helper function for printing out trace information from debugging
545** binaries. This returns the string represetation of the supplied
546** integer lock-type.
547*/
drh308c2a52010-05-14 11:30:18 +0000548static const char *azFileLock(int eFileLock){
549 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000550 case NO_LOCK: return "NONE";
551 case SHARED_LOCK: return "SHARED";
552 case RESERVED_LOCK: return "RESERVED";
553 case PENDING_LOCK: return "PENDING";
554 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000555 }
556 return "ERROR";
557}
558#endif
559
560#ifdef SQLITE_LOCK_TRACE
561/*
562** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000563**
drh734c9862008-11-28 15:37:20 +0000564** This routine is used for troubleshooting locks on multithreaded
565** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
566** command-line option on the compiler. This code is normally
567** turned off.
568*/
569static int lockTrace(int fd, int op, struct flock *p){
570 char *zOpName, *zType;
571 int s;
572 int savedErrno;
573 if( op==F_GETLK ){
574 zOpName = "GETLK";
575 }else if( op==F_SETLK ){
576 zOpName = "SETLK";
577 }else{
drh99ab3b12011-03-02 15:09:07 +0000578 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000579 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
580 return s;
581 }
582 if( p->l_type==F_RDLCK ){
583 zType = "RDLCK";
584 }else if( p->l_type==F_WRLCK ){
585 zType = "WRLCK";
586 }else if( p->l_type==F_UNLCK ){
587 zType = "UNLCK";
588 }else{
589 assert( 0 );
590 }
591 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000592 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000593 savedErrno = errno;
594 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
595 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
596 (int)p->l_pid, s);
597 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
598 struct flock l2;
599 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000600 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000601 if( l2.l_type==F_RDLCK ){
602 zType = "RDLCK";
603 }else if( l2.l_type==F_WRLCK ){
604 zType = "WRLCK";
605 }else if( l2.l_type==F_UNLCK ){
606 zType = "UNLCK";
607 }else{
608 assert( 0 );
609 }
610 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
611 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
612 }
613 errno = savedErrno;
614 return s;
615}
drh99ab3b12011-03-02 15:09:07 +0000616#undef osFcntl
617#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000618#endif /* SQLITE_LOCK_TRACE */
619
drhff812312011-02-23 13:33:46 +0000620/*
621** Retry ftruncate() calls that fail due to EINTR
622*/
drhff812312011-02-23 13:33:46 +0000623static int robust_ftruncate(int h, sqlite3_int64 sz){
624 int rc;
drh99ab3b12011-03-02 15:09:07 +0000625 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000626 return rc;
627}
drh734c9862008-11-28 15:37:20 +0000628
629/*
630** This routine translates a standard POSIX errno code into something
631** useful to the clients of the sqlite3 functions. Specifically, it is
632** intended to translate a variety of "try again" errors into SQLITE_BUSY
633** and a variety of "please close the file descriptor NOW" errors into
634** SQLITE_IOERR
635**
636** Errors during initialization of locks, or file system support for locks,
637** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
638*/
639static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
640 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000641#if 0
642 /* At one point this code was not commented out. In theory, this branch
643 ** should never be hit, as this function should only be called after
644 ** a locking-related function (i.e. fcntl()) has returned non-zero with
645 ** the value of errno as the first argument. Since a system call has failed,
646 ** errno should be non-zero.
647 **
648 ** Despite this, if errno really is zero, we still don't want to return
649 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
650 ** propagated back to the caller. Commenting this branch out means errno==0
651 ** will be handled by the "default:" case below.
652 */
drh734c9862008-11-28 15:37:20 +0000653 case 0:
654 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000655#endif
656
drh734c9862008-11-28 15:37:20 +0000657 case EAGAIN:
658 case ETIMEDOUT:
659 case EBUSY:
660 case EINTR:
661 case ENOLCK:
662 /* random NFS retry error, unless during file system support
663 * introspection, in which it actually means what it says */
664 return SQLITE_BUSY;
665
666 case EACCES:
667 /* EACCES is like EAGAIN during locking operations, but not any other time*/
668 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
669 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
670 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
671 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
672 return SQLITE_BUSY;
673 }
674 /* else fall through */
675 case EPERM:
676 return SQLITE_PERM;
677
danea83bc62011-04-01 11:56:32 +0000678 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
679 ** this module never makes such a call. And the code in SQLite itself
680 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
681 ** this case is also commented out. If the system does set errno to EDEADLK,
682 ** the default SQLITE_IOERR_XXX code will be returned. */
683#if 0
drh734c9862008-11-28 15:37:20 +0000684 case EDEADLK:
685 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000686#endif
drh734c9862008-11-28 15:37:20 +0000687
688#if EOPNOTSUPP!=ENOTSUP
689 case EOPNOTSUPP:
690 /* something went terribly awry, unless during file system support
691 * introspection, in which it actually means what it says */
692#endif
693#ifdef ENOTSUP
694 case ENOTSUP:
695 /* invalid fd, unless during file system support introspection, in which
696 * it actually means what it says */
697#endif
698 case EIO:
699 case EBADF:
700 case EINVAL:
701 case ENOTCONN:
702 case ENODEV:
703 case ENXIO:
704 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000705#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000706 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000707#endif
drh734c9862008-11-28 15:37:20 +0000708 case ENOSYS:
709 /* these should force the client to close the file and reconnect */
710
711 default:
712 return sqliteIOErr;
713 }
714}
715
716
717
718/******************************************************************************
719****************** Begin Unique File ID Utility Used By VxWorks ***************
720**
721** On most versions of unix, we can get a unique ID for a file by concatenating
722** the device number and the inode number. But this does not work on VxWorks.
723** On VxWorks, a unique file id must be based on the canonical filename.
724**
725** A pointer to an instance of the following structure can be used as a
726** unique file ID in VxWorks. Each instance of this structure contains
727** a copy of the canonical filename. There is also a reference count.
728** The structure is reclaimed when the number of pointers to it drops to
729** zero.
730**
731** There are never very many files open at one time and lookups are not
732** a performance-critical path, so it is sufficient to put these
733** structures on a linked list.
734*/
735struct vxworksFileId {
736 struct vxworksFileId *pNext; /* Next in a list of them all */
737 int nRef; /* Number of references to this one */
738 int nName; /* Length of the zCanonicalName[] string */
739 char *zCanonicalName; /* Canonical filename */
740};
741
742#if OS_VXWORKS
743/*
drh9b35ea62008-11-29 02:20:26 +0000744** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000745** variable:
746*/
747static struct vxworksFileId *vxworksFileList = 0;
748
749/*
750** Simplify a filename into its canonical form
751** by making the following changes:
752**
753** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000754** * convert /./ into just /
755** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000756**
757** Changes are made in-place. Return the new name length.
758**
759** The original filename is in z[0..n-1]. Return the number of
760** characters in the simplified name.
761*/
762static int vxworksSimplifyName(char *z, int n){
763 int i, j;
764 while( n>1 && z[n-1]=='/' ){ n--; }
765 for(i=j=0; i<n; i++){
766 if( z[i]=='/' ){
767 if( z[i+1]=='/' ) continue;
768 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
769 i += 1;
770 continue;
771 }
772 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
773 while( j>0 && z[j-1]!='/' ){ j--; }
774 if( j>0 ){ j--; }
775 i += 2;
776 continue;
777 }
778 }
779 z[j++] = z[i];
780 }
781 z[j] = 0;
782 return j;
783}
784
785/*
786** Find a unique file ID for the given absolute pathname. Return
787** a pointer to the vxworksFileId object. This pointer is the unique
788** file ID.
789**
790** The nRef field of the vxworksFileId object is incremented before
791** the object is returned. A new vxworksFileId object is created
792** and added to the global list if necessary.
793**
794** If a memory allocation error occurs, return NULL.
795*/
796static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
797 struct vxworksFileId *pNew; /* search key and new file ID */
798 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
799 int n; /* Length of zAbsoluteName string */
800
801 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000802 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000803 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
804 if( pNew==0 ) return 0;
805 pNew->zCanonicalName = (char*)&pNew[1];
806 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
807 n = vxworksSimplifyName(pNew->zCanonicalName, n);
808
809 /* Search for an existing entry that matching the canonical name.
810 ** If found, increment the reference count and return a pointer to
811 ** the existing file ID.
812 */
813 unixEnterMutex();
814 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
815 if( pCandidate->nName==n
816 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
817 ){
818 sqlite3_free(pNew);
819 pCandidate->nRef++;
820 unixLeaveMutex();
821 return pCandidate;
822 }
823 }
824
825 /* No match was found. We will make a new file ID */
826 pNew->nRef = 1;
827 pNew->nName = n;
828 pNew->pNext = vxworksFileList;
829 vxworksFileList = pNew;
830 unixLeaveMutex();
831 return pNew;
832}
833
834/*
835** Decrement the reference count on a vxworksFileId object. Free
836** the object when the reference count reaches zero.
837*/
838static void vxworksReleaseFileId(struct vxworksFileId *pId){
839 unixEnterMutex();
840 assert( pId->nRef>0 );
841 pId->nRef--;
842 if( pId->nRef==0 ){
843 struct vxworksFileId **pp;
844 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
845 assert( *pp==pId );
846 *pp = pId->pNext;
847 sqlite3_free(pId);
848 }
849 unixLeaveMutex();
850}
851#endif /* OS_VXWORKS */
852/*************** End of Unique File ID Utility Used By VxWorks ****************
853******************************************************************************/
854
855
856/******************************************************************************
857*************************** Posix Advisory Locking ****************************
858**
drh9b35ea62008-11-29 02:20:26 +0000859** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000860** section 6.5.2.2 lines 483 through 490 specify that when a process
861** sets or clears a lock, that operation overrides any prior locks set
862** by the same process. It does not explicitly say so, but this implies
863** that it overrides locks set by the same process using a different
864** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000865**
866** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000867** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
868**
869** Suppose ./file1 and ./file2 are really the same file (because
870** one is a hard or symbolic link to the other) then if you set
871** an exclusive lock on fd1, then try to get an exclusive lock
872** on fd2, it works. I would have expected the second lock to
873** fail since there was already a lock on the file due to fd1.
874** But not so. Since both locks came from the same process, the
875** second overrides the first, even though they were on different
876** file descriptors opened on different file names.
877**
drh734c9862008-11-28 15:37:20 +0000878** This means that we cannot use POSIX locks to synchronize file access
879** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000880** to synchronize access for threads in separate processes, but not
881** threads within the same process.
882**
883** To work around the problem, SQLite has to manage file locks internally
884** on its own. Whenever a new database is opened, we have to find the
885** specific inode of the database file (the inode is determined by the
886** st_dev and st_ino fields of the stat structure that fstat() fills in)
887** and check for locks already existing on that inode. When locks are
888** created or removed, we have to look at our own internal record of the
889** locks to see if another thread has previously set a lock on that same
890** inode.
891**
drh9b35ea62008-11-29 02:20:26 +0000892** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
893** For VxWorks, we have to use the alternative unique ID system based on
894** canonical filename and implemented in the previous division.)
895**
danielk1977ad94b582007-08-20 06:44:22 +0000896** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000897** descriptor. It is now a structure that holds the integer file
898** descriptor and a pointer to a structure that describes the internal
899** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000900** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000901** point to the same locking structure. The locking structure keeps
902** a reference count (so we will know when to delete it) and a "cnt"
903** field that tells us its internal lock status. cnt==0 means the
904** file is unlocked. cnt==-1 means the file has an exclusive lock.
905** cnt>0 means there are cnt shared locks on the file.
906**
907** Any attempt to lock or unlock a file first checks the locking
908** structure. The fcntl() system call is only invoked to set a
909** POSIX lock if the internal lock structure transitions between
910** a locked and an unlocked state.
911**
drh734c9862008-11-28 15:37:20 +0000912** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000913**
914** If you close a file descriptor that points to a file that has locks,
915** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000916** released. To work around this problem, each unixInodeInfo object
917** maintains a count of the number of pending locks on tha inode.
918** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000919** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000920** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000921** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000922** be closed and that list is walked (and cleared) when the last lock
923** clears.
924**
drh9b35ea62008-11-29 02:20:26 +0000925** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000926**
drh9b35ea62008-11-29 02:20:26 +0000927** Many older versions of linux use the LinuxThreads library which is
928** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000929** A cannot be modified or overridden by a different thread B.
930** Only thread A can modify the lock. Locking behavior is correct
931** if the appliation uses the newer Native Posix Thread Library (NPTL)
932** on linux - with NPTL a lock created by thread A can override locks
933** in thread B. But there is no way to know at compile-time which
934** threading library is being used. So there is no way to know at
935** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000936** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000937** current process.
drh5fdae772004-06-29 03:29:00 +0000938**
drh8af6c222010-05-14 12:43:01 +0000939** SQLite used to support LinuxThreads. But support for LinuxThreads
940** was dropped beginning with version 3.7.0. SQLite will still work with
941** LinuxThreads provided that (1) there is no more than one connection
942** per database file in the same process and (2) database connections
943** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000944*/
945
946/*
947** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000948** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000949*/
950struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000951 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000952#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000953 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000954#else
drh107886a2008-11-21 22:21:50 +0000955 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000956#endif
957};
958
959/*
drhbbd42a62004-05-22 17:41:58 +0000960** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000961** inode. Or, on LinuxThreads, there is one of these structures for
962** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000963**
danielk1977ad94b582007-08-20 06:44:22 +0000964** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000965** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000966** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000967*/
drh8af6c222010-05-14 12:43:01 +0000968struct unixInodeInfo {
969 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000970 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000971 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
972 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000973 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000974 unixShmNode *pShmNode; /* Shared memory associated with this inode */
975 int nLock; /* Number of outstanding file locks */
976 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
977 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
978 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000979#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000980 unsigned long long sharedByte; /* for AFP simulated shared lock */
981#endif
drh6c7d5c52008-11-21 20:32:33 +0000982#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000983 sem_t *pSem; /* Named POSIX semaphore */
984 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000985#endif
drhbbd42a62004-05-22 17:41:58 +0000986};
987
drhda0e7682008-07-30 15:27:54 +0000988/*
drh8af6c222010-05-14 12:43:01 +0000989** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000990*/
drhd91c68f2010-05-14 14:52:25 +0000991static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000992
drh5fdae772004-06-29 03:29:00 +0000993/*
dane18d4952011-02-21 11:46:24 +0000994**
995** This function - unixLogError_x(), is only ever called via the macro
996** unixLogError().
997**
998** It is invoked after an error occurs in an OS function and errno has been
999** set. It logs a message using sqlite3_log() containing the current value of
1000** errno and, if possible, the human-readable equivalent from strerror() or
1001** strerror_r().
1002**
1003** The first argument passed to the macro should be the error code that
1004** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1005** The two subsequent arguments should be the name of the OS function that
1006** failed (e.g. "unlink", "open") and the the associated file-system path,
1007** if any.
1008*/
drh0e9365c2011-03-02 02:08:13 +00001009#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1010static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001011 int errcode, /* SQLite error code */
1012 const char *zFunc, /* Name of OS function that failed */
1013 const char *zPath, /* File path associated with error */
1014 int iLine /* Source line number where error occurred */
1015){
1016 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001017 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001018
1019 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1020 ** the strerror() function to obtain the human-readable error message
1021 ** equivalent to errno. Otherwise, use strerror_r().
1022 */
1023#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1024 char aErr[80];
1025 memset(aErr, 0, sizeof(aErr));
1026 zErr = aErr;
1027
1028 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1029 ** assume that the system provides the the GNU version of strerror_r() that
1030 ** returns a pointer to a buffer containing the error message. That pointer
1031 ** may point to aErr[], or it may point to some static storage somewhere.
1032 ** Otherwise, assume that the system provides the POSIX version of
1033 ** strerror_r(), which always writes an error message into aErr[].
1034 **
1035 ** If the code incorrectly assumes that it is the POSIX version that is
1036 ** available, the error message will often be an empty string. Not a
1037 ** huge problem. Incorrectly concluding that the GNU version is available
1038 ** could lead to a segfault though.
1039 */
1040#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1041 zErr =
1042# endif
drh0e9365c2011-03-02 02:08:13 +00001043 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001044
1045#elif SQLITE_THREADSAFE
1046 /* This is a threadsafe build, but strerror_r() is not available. */
1047 zErr = "";
1048#else
1049 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001050 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001051#endif
1052
1053 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001054 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001055 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001056 "os_unix.c:%d: (%d) %s(%s) - %s",
1057 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001058 );
1059
1060 return errcode;
1061}
1062
drh0e9365c2011-03-02 02:08:13 +00001063/*
1064** Close a file descriptor.
1065**
1066** We assume that close() almost always works, since it is only in a
1067** very sick application or on a very sick platform that it might fail.
1068** If it does fail, simply leak the file descriptor, but do log the
1069** error.
1070**
1071** Note that it is not safe to retry close() after EINTR since the
1072** file descriptor might have already been reused by another thread.
1073** So we don't even try to recover from an EINTR. Just log the error
1074** and move on.
1075*/
1076static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001077 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001078 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1079 pFile ? pFile->zPath : 0, lineno);
1080 }
1081}
dane18d4952011-02-21 11:46:24 +00001082
1083/*
danb0ac3e32010-06-16 10:55:42 +00001084** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001085*/
drh0e9365c2011-03-02 02:08:13 +00001086static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001087 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001088 UnixUnusedFd *p;
1089 UnixUnusedFd *pNext;
1090 for(p=pInode->pUnused; p; p=pNext){
1091 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001092 robust_close(pFile, p->fd, __LINE__);
1093 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001094 }
drh0e9365c2011-03-02 02:08:13 +00001095 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001096}
1097
1098/*
drh8af6c222010-05-14 12:43:01 +00001099** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001100**
1101** The mutex entered using the unixEnterMutex() function must be held
1102** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001103*/
danb0ac3e32010-06-16 10:55:42 +00001104static void releaseInodeInfo(unixFile *pFile){
1105 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001106 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001107 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001108 pInode->nRef--;
1109 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001110 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001111 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001112 if( pInode->pPrev ){
1113 assert( pInode->pPrev->pNext==pInode );
1114 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001115 }else{
drh8af6c222010-05-14 12:43:01 +00001116 assert( inodeList==pInode );
1117 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001118 }
drh8af6c222010-05-14 12:43:01 +00001119 if( pInode->pNext ){
1120 assert( pInode->pNext->pPrev==pInode );
1121 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001122 }
drh8af6c222010-05-14 12:43:01 +00001123 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001124 }
drhbbd42a62004-05-22 17:41:58 +00001125 }
1126}
1127
1128/*
drh8af6c222010-05-14 12:43:01 +00001129** Given a file descriptor, locate the unixInodeInfo object that
1130** describes that file descriptor. Create a new one if necessary. The
1131** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001132**
dan9359c7b2009-08-21 08:29:10 +00001133** The mutex entered using the unixEnterMutex() function must be held
1134** when this function is called.
1135**
drh6c7d5c52008-11-21 20:32:33 +00001136** Return an appropriate error code.
1137*/
drh8af6c222010-05-14 12:43:01 +00001138static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001139 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001140 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001141){
1142 int rc; /* System call return code */
1143 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001144 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1145 struct stat statbuf; /* Low-level file information */
1146 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001147
dan9359c7b2009-08-21 08:29:10 +00001148 assert( unixMutexHeld() );
1149
drh6c7d5c52008-11-21 20:32:33 +00001150 /* Get low-level information about the file that we can used to
1151 ** create a unique name for the file.
1152 */
1153 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001154 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001155 if( rc!=0 ){
1156 pFile->lastErrno = errno;
1157#ifdef EOVERFLOW
1158 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1159#endif
1160 return SQLITE_IOERR;
1161 }
1162
drheb0d74f2009-02-03 15:27:02 +00001163#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001164 /* On OS X on an msdos filesystem, the inode number is reported
1165 ** incorrectly for zero-size files. See ticket #3260. To work
1166 ** around this problem (we consider it a bug in OS X, not SQLite)
1167 ** we always increase the file size to 1 by writing a single byte
1168 ** prior to accessing the inode number. The one byte written is
1169 ** an ASCII 'S' character which also happens to be the first byte
1170 ** in the header of every SQLite database. In this way, if there
1171 ** is a race condition such that another thread has already populated
1172 ** the first page of the database, no damage is done.
1173 */
drh7ed97b92010-01-20 13:07:21 +00001174 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001175 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001176 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001177 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001178 return SQLITE_IOERR;
1179 }
drh99ab3b12011-03-02 15:09:07 +00001180 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001181 if( rc!=0 ){
1182 pFile->lastErrno = errno;
1183 return SQLITE_IOERR;
1184 }
1185 }
drheb0d74f2009-02-03 15:27:02 +00001186#endif
drh6c7d5c52008-11-21 20:32:33 +00001187
drh8af6c222010-05-14 12:43:01 +00001188 memset(&fileId, 0, sizeof(fileId));
1189 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001190#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001191 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001192#else
drh8af6c222010-05-14 12:43:01 +00001193 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001194#endif
drh8af6c222010-05-14 12:43:01 +00001195 pInode = inodeList;
1196 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1197 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001198 }
drh8af6c222010-05-14 12:43:01 +00001199 if( pInode==0 ){
1200 pInode = sqlite3_malloc( sizeof(*pInode) );
1201 if( pInode==0 ){
1202 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001203 }
drh8af6c222010-05-14 12:43:01 +00001204 memset(pInode, 0, sizeof(*pInode));
1205 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1206 pInode->nRef = 1;
1207 pInode->pNext = inodeList;
1208 pInode->pPrev = 0;
1209 if( inodeList ) inodeList->pPrev = pInode;
1210 inodeList = pInode;
1211 }else{
1212 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001213 }
drh8af6c222010-05-14 12:43:01 +00001214 *ppInode = pInode;
1215 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001216}
drh6c7d5c52008-11-21 20:32:33 +00001217
aswift5b1a2562008-08-22 00:22:35 +00001218
1219/*
danielk197713adf8a2004-06-03 16:08:41 +00001220** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001221** file by this or any other process. If such a lock is held, set *pResOut
1222** to a non-zero value otherwise *pResOut is set to zero. The return value
1223** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001224*/
danielk1977861f7452008-06-05 11:39:11 +00001225static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001226 int rc = SQLITE_OK;
1227 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001228 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001229
danielk1977861f7452008-06-05 11:39:11 +00001230 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1231
drh054889e2005-11-30 03:20:31 +00001232 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001233 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001234
1235 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001236 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001237 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001238 }
1239
drh2ac3ee92004-06-07 16:27:46 +00001240 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001241 */
danielk197709480a92009-02-09 05:32:32 +00001242#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001243 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001244 struct flock lock;
1245 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001246 lock.l_start = RESERVED_BYTE;
1247 lock.l_len = 1;
1248 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001249 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1250 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1251 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001252 } else if( lock.l_type!=F_UNLCK ){
1253 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001254 }
1255 }
danielk197709480a92009-02-09 05:32:32 +00001256#endif
danielk197713adf8a2004-06-03 16:08:41 +00001257
drh6c7d5c52008-11-21 20:32:33 +00001258 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001259 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001260
aswift5b1a2562008-08-22 00:22:35 +00001261 *pResOut = reserved;
1262 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001263}
1264
1265/*
drha7e61d82011-03-12 17:02:57 +00001266** Attempt to set a system-lock on the file pFile. The lock is
1267** described by pLock.
1268**
drh77197112011-03-15 19:08:48 +00001269** If the pFile was opened read/write from unix-excl, then the only lock
1270** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001271** the first time any lock is attempted. All subsequent system locking
1272** operations become no-ops. Locking operations still happen internally,
1273** in order to coordinate access between separate database connections
1274** within this process, but all of that is handled in memory and the
1275** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001276**
1277** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1278** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1279** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001280**
1281** Zero is returned if the call completes successfully, or -1 if a call
1282** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001283*/
1284static int unixFileLock(unixFile *pFile, struct flock *pLock){
1285 int rc;
drh3cb93392011-03-12 18:10:44 +00001286 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001287 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001288 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001289 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1290 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1291 ){
drh3cb93392011-03-12 18:10:44 +00001292 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001293 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001294 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001295 lock.l_whence = SEEK_SET;
1296 lock.l_start = SHARED_FIRST;
1297 lock.l_len = SHARED_SIZE;
1298 lock.l_type = F_WRLCK;
1299 rc = osFcntl(pFile->h, F_SETLK, &lock);
1300 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001301 pInode->bProcessLock = 1;
1302 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001303 }else{
1304 rc = 0;
1305 }
1306 }else{
1307 rc = osFcntl(pFile->h, F_SETLK, pLock);
1308 }
1309 return rc;
1310}
1311
1312/*
drh308c2a52010-05-14 11:30:18 +00001313** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001314** of the following:
1315**
drh2ac3ee92004-06-07 16:27:46 +00001316** (1) SHARED_LOCK
1317** (2) RESERVED_LOCK
1318** (3) PENDING_LOCK
1319** (4) EXCLUSIVE_LOCK
1320**
drhb3e04342004-06-08 00:47:47 +00001321** Sometimes when requesting one lock state, additional lock states
1322** are inserted in between. The locking might fail on one of the later
1323** transitions leaving the lock state different from what it started but
1324** still short of its goal. The following chart shows the allowed
1325** transitions and the inserted intermediate states:
1326**
1327** UNLOCKED -> SHARED
1328** SHARED -> RESERVED
1329** SHARED -> (PENDING) -> EXCLUSIVE
1330** RESERVED -> (PENDING) -> EXCLUSIVE
1331** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001332**
drha6abd042004-06-09 17:37:22 +00001333** This routine will only increase a lock. Use the sqlite3OsUnlock()
1334** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001335*/
drh308c2a52010-05-14 11:30:18 +00001336static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001337 /* The following describes the implementation of the various locks and
1338 ** lock transitions in terms of the POSIX advisory shared and exclusive
1339 ** lock primitives (called read-locks and write-locks below, to avoid
1340 ** confusion with SQLite lock names). The algorithms are complicated
1341 ** slightly in order to be compatible with windows systems simultaneously
1342 ** accessing the same database file, in case that is ever required.
1343 **
1344 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1345 ** byte', each single bytes at well known offsets, and the 'shared byte
1346 ** range', a range of 510 bytes at a well known offset.
1347 **
1348 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1349 ** byte'. If this is successful, a random byte from the 'shared byte
1350 ** range' is read-locked and the lock on the 'pending byte' released.
1351 **
danielk197790ba3bd2004-06-25 08:32:25 +00001352 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1353 ** A RESERVED lock is implemented by grabbing a write-lock on the
1354 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001355 **
1356 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001357 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1358 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1359 ** obtained, but existing SHARED locks are allowed to persist. A process
1360 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1361 ** This property is used by the algorithm for rolling back a journal file
1362 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001363 **
danielk197790ba3bd2004-06-25 08:32:25 +00001364 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1365 ** implemented by obtaining a write-lock on the entire 'shared byte
1366 ** range'. Since all other locks require a read-lock on one of the bytes
1367 ** within this range, this ensures that no other locks are held on the
1368 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001369 **
1370 ** The reason a single byte cannot be used instead of the 'shared byte
1371 ** range' is that some versions of windows do not support read-locks. By
1372 ** locking a random byte from a range, concurrent SHARED locks may exist
1373 ** even if the locking primitive used is always a write-lock.
1374 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001375 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001376 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001377 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001378 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001379 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001380
drh054889e2005-11-30 03:20:31 +00001381 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001382 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1383 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001384 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001385
1386 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001387 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001388 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001389 */
drh308c2a52010-05-14 11:30:18 +00001390 if( pFile->eFileLock>=eFileLock ){
1391 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1392 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001393 return SQLITE_OK;
1394 }
1395
drh0c2694b2009-09-03 16:23:44 +00001396 /* Make sure the locking sequence is correct.
1397 ** (1) We never move from unlocked to anything higher than shared lock.
1398 ** (2) SQLite never explicitly requests a pendig lock.
1399 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001400 */
drh308c2a52010-05-14 11:30:18 +00001401 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1402 assert( eFileLock!=PENDING_LOCK );
1403 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001404
drh8af6c222010-05-14 12:43:01 +00001405 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001406 */
drh6c7d5c52008-11-21 20:32:33 +00001407 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001408 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001409
danielk1977ad94b582007-08-20 06:44:22 +00001410 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001411 ** handle that precludes the requested lock, return BUSY.
1412 */
drh8af6c222010-05-14 12:43:01 +00001413 if( (pFile->eFileLock!=pInode->eFileLock &&
1414 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001415 ){
1416 rc = SQLITE_BUSY;
1417 goto end_lock;
1418 }
1419
1420 /* If a SHARED lock is requested, and some thread using this PID already
1421 ** has a SHARED or RESERVED lock, then increment reference counts and
1422 ** return SQLITE_OK.
1423 */
drh308c2a52010-05-14 11:30:18 +00001424 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001425 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001426 assert( eFileLock==SHARED_LOCK );
1427 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001428 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001429 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001430 pInode->nShared++;
1431 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001432 goto end_lock;
1433 }
1434
danielk19779a1d0ab2004-06-01 14:09:28 +00001435
drh3cde3bb2004-06-12 02:17:14 +00001436 /* A PENDING lock is needed before acquiring a SHARED lock and before
1437 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1438 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001439 */
drh0c2694b2009-09-03 16:23:44 +00001440 lock.l_len = 1L;
1441 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001442 if( eFileLock==SHARED_LOCK
1443 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001444 ){
drh308c2a52010-05-14 11:30:18 +00001445 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001446 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001447 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001448 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001449 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001450 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001451 pFile->lastErrno = tErrno;
1452 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001453 goto end_lock;
1454 }
drh3cde3bb2004-06-12 02:17:14 +00001455 }
1456
1457
1458 /* If control gets to this point, then actually go ahead and make
1459 ** operating system calls for the specified lock.
1460 */
drh308c2a52010-05-14 11:30:18 +00001461 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001462 assert( pInode->nShared==0 );
1463 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001464 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001465
drh2ac3ee92004-06-07 16:27:46 +00001466 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001467 lock.l_start = SHARED_FIRST;
1468 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001469 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001470 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001471 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001472 }
dan661d71a2011-03-30 19:08:03 +00001473
drh2ac3ee92004-06-07 16:27:46 +00001474 /* Drop the temporary PENDING lock */
1475 lock.l_start = PENDING_BYTE;
1476 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001477 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001478 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1479 /* This could happen with a network mount */
1480 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001481 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001482 }
dan661d71a2011-03-30 19:08:03 +00001483
1484 if( rc ){
1485 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001486 pFile->lastErrno = tErrno;
1487 }
dan661d71a2011-03-30 19:08:03 +00001488 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001489 }else{
drh308c2a52010-05-14 11:30:18 +00001490 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001491 pInode->nLock++;
1492 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001493 }
drh8af6c222010-05-14 12:43:01 +00001494 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001495 /* We are trying for an exclusive lock but another thread in this
1496 ** same process is still holding a shared lock. */
1497 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001498 }else{
drh3cde3bb2004-06-12 02:17:14 +00001499 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001500 ** assumed that there is a SHARED or greater lock on the file
1501 ** already.
1502 */
drh308c2a52010-05-14 11:30:18 +00001503 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001504 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001505
1506 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1507 if( eFileLock==RESERVED_LOCK ){
1508 lock.l_start = RESERVED_BYTE;
1509 lock.l_len = 1L;
1510 }else{
1511 lock.l_start = SHARED_FIRST;
1512 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001513 }
dan661d71a2011-03-30 19:08:03 +00001514
1515 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001516 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001517 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001518 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001519 pFile->lastErrno = tErrno;
1520 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001521 }
drhbbd42a62004-05-22 17:41:58 +00001522 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001523
drh8f941bc2009-01-14 23:03:40 +00001524
1525#ifndef NDEBUG
1526 /* Set up the transaction-counter change checking flags when
1527 ** transitioning from a SHARED to a RESERVED lock. The change
1528 ** from SHARED to RESERVED marks the beginning of a normal
1529 ** write operation (not a hot journal rollback).
1530 */
1531 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001532 && pFile->eFileLock<=SHARED_LOCK
1533 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001534 ){
1535 pFile->transCntrChng = 0;
1536 pFile->dbUpdate = 0;
1537 pFile->inNormalWrite = 1;
1538 }
1539#endif
1540
1541
danielk1977ecb2a962004-06-02 06:30:16 +00001542 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001543 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001544 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001545 }else if( eFileLock==EXCLUSIVE_LOCK ){
1546 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001547 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001548 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001549
1550end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001551 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001552 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1553 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001554 return rc;
1555}
1556
1557/*
dan08da86a2009-08-21 17:18:03 +00001558** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001559** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001560*/
1561static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001562 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001563 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001564 p->pNext = pInode->pUnused;
1565 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001566 pFile->h = -1;
1567 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001568}
1569
1570/*
drh308c2a52010-05-14 11:30:18 +00001571** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001572** must be either NO_LOCK or SHARED_LOCK.
1573**
1574** If the locking level of the file descriptor is already at or below
1575** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001576**
1577** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1578** the byte range is divided into 2 parts and the first part is unlocked then
1579** set to a read lock, then the other part is simply unlocked. This works
1580** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1581** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001582*/
drha7e61d82011-03-12 17:02:57 +00001583static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001584 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001585 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001586 struct flock lock;
1587 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001588
drh054889e2005-11-30 03:20:31 +00001589 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001590 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001591 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001592 getpid()));
drha6abd042004-06-09 17:37:22 +00001593
drh308c2a52010-05-14 11:30:18 +00001594 assert( eFileLock<=SHARED_LOCK );
1595 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001596 return SQLITE_OK;
1597 }
drh6c7d5c52008-11-21 20:32:33 +00001598 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001599 pInode = pFile->pInode;
1600 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001601 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001602 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001603
1604#ifndef NDEBUG
1605 /* When reducing a lock such that other processes can start
1606 ** reading the database file again, make sure that the
1607 ** transaction counter was updated if any part of the database
1608 ** file changed. If the transaction counter is not updated,
1609 ** other connections to the same file might not realize that
1610 ** the file has changed and hence might not know to flush their
1611 ** cache. The use of a stale cache can lead to database corruption.
1612 */
drh8f941bc2009-01-14 23:03:40 +00001613 pFile->inNormalWrite = 0;
1614#endif
1615
drh7ed97b92010-01-20 13:07:21 +00001616 /* downgrading to a shared lock on NFS involves clearing the write lock
1617 ** before establishing the readlock - to avoid a race condition we downgrade
1618 ** the lock in 2 blocks, so that part of the range will be covered by a
1619 ** write lock until the rest is covered by a read lock:
1620 ** 1: [WWWWW]
1621 ** 2: [....W]
1622 ** 3: [RRRRW]
1623 ** 4: [RRRR.]
1624 */
drh308c2a52010-05-14 11:30:18 +00001625 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001626
1627#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001628 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001629 assert( handleNFSUnlock==0 );
1630#endif
1631#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001632 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001633 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001634 off_t divSize = SHARED_SIZE - 1;
1635
1636 lock.l_type = F_UNLCK;
1637 lock.l_whence = SEEK_SET;
1638 lock.l_start = SHARED_FIRST;
1639 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001640 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001641 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001642 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001643 if( IS_LOCK_ERROR(rc) ){
1644 pFile->lastErrno = tErrno;
1645 }
1646 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001647 }
drh7ed97b92010-01-20 13:07:21 +00001648 lock.l_type = F_RDLCK;
1649 lock.l_whence = SEEK_SET;
1650 lock.l_start = SHARED_FIRST;
1651 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001652 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001653 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001654 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1655 if( IS_LOCK_ERROR(rc) ){
1656 pFile->lastErrno = tErrno;
1657 }
1658 goto end_unlock;
1659 }
1660 lock.l_type = F_UNLCK;
1661 lock.l_whence = SEEK_SET;
1662 lock.l_start = SHARED_FIRST+divSize;
1663 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001664 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001665 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001666 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001667 if( IS_LOCK_ERROR(rc) ){
1668 pFile->lastErrno = tErrno;
1669 }
1670 goto end_unlock;
1671 }
drh30f776f2011-02-25 03:25:07 +00001672 }else
1673#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1674 {
drh7ed97b92010-01-20 13:07:21 +00001675 lock.l_type = F_RDLCK;
1676 lock.l_whence = SEEK_SET;
1677 lock.l_start = SHARED_FIRST;
1678 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001679 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001680 /* In theory, the call to unixFileLock() cannot fail because another
1681 ** process is holding an incompatible lock. If it does, this
1682 ** indicates that the other process is not following the locking
1683 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1684 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1685 ** an assert to fail). */
1686 rc = SQLITE_IOERR_RDLOCK;
1687 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001688 goto end_unlock;
1689 }
drh9c105bb2004-10-02 20:38:28 +00001690 }
1691 }
drhbbd42a62004-05-22 17:41:58 +00001692 lock.l_type = F_UNLCK;
1693 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001694 lock.l_start = PENDING_BYTE;
1695 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001696 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001697 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001698 }else{
danea83bc62011-04-01 11:56:32 +00001699 rc = SQLITE_IOERR_UNLOCK;
1700 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001701 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001702 }
drhbbd42a62004-05-22 17:41:58 +00001703 }
drh308c2a52010-05-14 11:30:18 +00001704 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001705 /* Decrement the shared lock counter. Release the lock using an
1706 ** OS call only when all threads in this same process have released
1707 ** the lock.
1708 */
drh8af6c222010-05-14 12:43:01 +00001709 pInode->nShared--;
1710 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001711 lock.l_type = F_UNLCK;
1712 lock.l_whence = SEEK_SET;
1713 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001714 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001715 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001716 }else{
danea83bc62011-04-01 11:56:32 +00001717 rc = SQLITE_IOERR_UNLOCK;
1718 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001719 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001720 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001721 }
drha6abd042004-06-09 17:37:22 +00001722 }
1723
drhbbd42a62004-05-22 17:41:58 +00001724 /* Decrement the count of locks against this same file. When the
1725 ** count reaches zero, close any other file descriptors whose close
1726 ** was deferred because of outstanding locks.
1727 */
drh8af6c222010-05-14 12:43:01 +00001728 pInode->nLock--;
1729 assert( pInode->nLock>=0 );
1730 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001731 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001732 }
1733 }
aswift5b1a2562008-08-22 00:22:35 +00001734
1735end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001736 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001737 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001738 return rc;
drhbbd42a62004-05-22 17:41:58 +00001739}
1740
1741/*
drh308c2a52010-05-14 11:30:18 +00001742** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001743** must be either NO_LOCK or SHARED_LOCK.
1744**
1745** If the locking level of the file descriptor is already at or below
1746** the requested locking level, this routine is a no-op.
1747*/
drh308c2a52010-05-14 11:30:18 +00001748static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001749 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001750}
1751
1752/*
danielk1977e339d652008-06-28 11:23:00 +00001753** This function performs the parts of the "close file" operation
1754** common to all locking schemes. It closes the directory and file
1755** handles, if they are valid, and sets all fields of the unixFile
1756** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001757**
1758** It is *not* necessary to hold the mutex when this routine is called,
1759** even on VxWorks. A mutex will be acquired on VxWorks by the
1760** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001761*/
1762static int closeUnixFile(sqlite3_file *id){
1763 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001764 if( pFile->h>=0 ){
1765 robust_close(pFile, pFile->h, __LINE__);
1766 pFile->h = -1;
1767 }
1768#if OS_VXWORKS
1769 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001770 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001771 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001772 }
1773 vxworksReleaseFileId(pFile->pId);
1774 pFile->pId = 0;
1775 }
1776#endif
1777 OSTRACE(("CLOSE %-3d\n", pFile->h));
1778 OpenCounter(-1);
1779 sqlite3_free(pFile->pUnused);
1780 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001781 return SQLITE_OK;
1782}
1783
1784/*
danielk1977e3026632004-06-22 11:29:02 +00001785** Close a file.
1786*/
danielk197762079062007-08-15 17:08:46 +00001787static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001788 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001789 unixFile *pFile = (unixFile *)id;
1790 unixUnlock(id, NO_LOCK);
1791 unixEnterMutex();
1792
1793 /* unixFile.pInode is always valid here. Otherwise, a different close
1794 ** routine (e.g. nolockClose()) would be called instead.
1795 */
1796 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1797 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1798 /* If there are outstanding locks, do not actually close the file just
1799 ** yet because that would clear those locks. Instead, add the file
1800 ** descriptor to pInode->pUnused list. It will be automatically closed
1801 ** when the last lock is cleared.
1802 */
1803 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001804 }
dan661d71a2011-03-30 19:08:03 +00001805 releaseInodeInfo(pFile);
1806 rc = closeUnixFile(id);
1807 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001808 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001809}
1810
drh734c9862008-11-28 15:37:20 +00001811/************** End of the posix advisory lock implementation *****************
1812******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001813
drh734c9862008-11-28 15:37:20 +00001814/******************************************************************************
1815****************************** No-op Locking **********************************
1816**
1817** Of the various locking implementations available, this is by far the
1818** simplest: locking is ignored. No attempt is made to lock the database
1819** file for reading or writing.
1820**
1821** This locking mode is appropriate for use on read-only databases
1822** (ex: databases that are burned into CD-ROM, for example.) It can
1823** also be used if the application employs some external mechanism to
1824** prevent simultaneous access of the same database by two or more
1825** database connections. But there is a serious risk of database
1826** corruption if this locking mode is used in situations where multiple
1827** database connections are accessing the same database file at the same
1828** time and one or more of those connections are writing.
1829*/
drhbfe66312006-10-03 17:40:40 +00001830
drh734c9862008-11-28 15:37:20 +00001831static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1832 UNUSED_PARAMETER(NotUsed);
1833 *pResOut = 0;
1834 return SQLITE_OK;
1835}
drh734c9862008-11-28 15:37:20 +00001836static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1837 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1838 return SQLITE_OK;
1839}
drh734c9862008-11-28 15:37:20 +00001840static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1841 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1842 return SQLITE_OK;
1843}
1844
1845/*
drh9b35ea62008-11-29 02:20:26 +00001846** Close the file.
drh734c9862008-11-28 15:37:20 +00001847*/
1848static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001849 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001850}
1851
1852/******************* End of the no-op lock implementation *********************
1853******************************************************************************/
1854
1855/******************************************************************************
1856************************* Begin dot-file Locking ******************************
1857**
drh0c2694b2009-09-03 16:23:44 +00001858** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001859** files (really a directory) to control access to the database. This works
1860** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001861**
1862** (1) There is zero concurrency. A single reader blocks all other
1863** connections from reading or writing the database.
1864**
1865** (2) An application crash or power loss can leave stale lock files
1866** sitting around that need to be cleared manually.
1867**
1868** Nevertheless, a dotlock is an appropriate locking mode for use if no
1869** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001870**
drh9ef6bc42011-11-04 02:24:02 +00001871** Dotfile locking works by creating a subdirectory in the same directory as
1872** the database and with the same name but with a ".lock" extension added.
1873** The existance of a lock directory implies an EXCLUSIVE lock. All other
1874** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001875*/
1876
1877/*
1878** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001879** lock directory.
drh734c9862008-11-28 15:37:20 +00001880*/
1881#define DOTLOCK_SUFFIX ".lock"
1882
drh7708e972008-11-29 00:56:52 +00001883/*
1884** This routine checks if there is a RESERVED lock held on the specified
1885** file by this or any other process. If such a lock is held, set *pResOut
1886** to a non-zero value otherwise *pResOut is set to zero. The return value
1887** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1888**
1889** In dotfile locking, either a lock exists or it does not. So in this
1890** variation of CheckReservedLock(), *pResOut is set to true if any lock
1891** is held on the file and false if the file is unlocked.
1892*/
drh734c9862008-11-28 15:37:20 +00001893static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1894 int rc = SQLITE_OK;
1895 int reserved = 0;
1896 unixFile *pFile = (unixFile*)id;
1897
1898 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1899
1900 assert( pFile );
1901
1902 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001903 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001904 /* Either this connection or some other connection in the same process
1905 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001906 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001907 }else{
1908 /* The lock is held if and only if the lockfile exists */
1909 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001910 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001911 }
drh308c2a52010-05-14 11:30:18 +00001912 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001913 *pResOut = reserved;
1914 return rc;
1915}
1916
drh7708e972008-11-29 00:56:52 +00001917/*
drh308c2a52010-05-14 11:30:18 +00001918** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001919** of the following:
1920**
1921** (1) SHARED_LOCK
1922** (2) RESERVED_LOCK
1923** (3) PENDING_LOCK
1924** (4) EXCLUSIVE_LOCK
1925**
1926** Sometimes when requesting one lock state, additional lock states
1927** are inserted in between. The locking might fail on one of the later
1928** transitions leaving the lock state different from what it started but
1929** still short of its goal. The following chart shows the allowed
1930** transitions and the inserted intermediate states:
1931**
1932** UNLOCKED -> SHARED
1933** SHARED -> RESERVED
1934** SHARED -> (PENDING) -> EXCLUSIVE
1935** RESERVED -> (PENDING) -> EXCLUSIVE
1936** PENDING -> EXCLUSIVE
1937**
1938** This routine will only increase a lock. Use the sqlite3OsUnlock()
1939** routine to lower a locking level.
1940**
1941** With dotfile locking, we really only support state (4): EXCLUSIVE.
1942** But we track the other locking levels internally.
1943*/
drh308c2a52010-05-14 11:30:18 +00001944static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001945 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001946 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001947 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001948
drh7708e972008-11-29 00:56:52 +00001949
1950 /* If we have any lock, then the lock file already exists. All we have
1951 ** to do is adjust our internal record of the lock level.
1952 */
drh308c2a52010-05-14 11:30:18 +00001953 if( pFile->eFileLock > NO_LOCK ){
1954 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001955 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001956#ifdef HAVE_UTIME
1957 utime(zLockFile, NULL);
1958#else
drh734c9862008-11-28 15:37:20 +00001959 utimes(zLockFile, NULL);
1960#endif
drh7708e972008-11-29 00:56:52 +00001961 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001962 }
1963
1964 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00001965 rc = osMkdir(zLockFile, 0777);
1966 if( rc<0 ){
1967 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00001968 int tErrno = errno;
1969 if( EEXIST == tErrno ){
1970 rc = SQLITE_BUSY;
1971 } else {
1972 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1973 if( IS_LOCK_ERROR(rc) ){
1974 pFile->lastErrno = tErrno;
1975 }
1976 }
drh7708e972008-11-29 00:56:52 +00001977 return rc;
drh734c9862008-11-28 15:37:20 +00001978 }
drh734c9862008-11-28 15:37:20 +00001979
1980 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001981 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001982 return rc;
1983}
1984
drh7708e972008-11-29 00:56:52 +00001985/*
drh308c2a52010-05-14 11:30:18 +00001986** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001987** must be either NO_LOCK or SHARED_LOCK.
1988**
1989** If the locking level of the file descriptor is already at or below
1990** the requested locking level, this routine is a no-op.
1991**
1992** When the locking level reaches NO_LOCK, delete the lock file.
1993*/
drh308c2a52010-05-14 11:30:18 +00001994static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001995 unixFile *pFile = (unixFile*)id;
1996 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00001997 int rc;
drh734c9862008-11-28 15:37:20 +00001998
1999 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002000 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2001 pFile->eFileLock, getpid()));
2002 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002003
2004 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002005 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002006 return SQLITE_OK;
2007 }
drh7708e972008-11-29 00:56:52 +00002008
2009 /* To downgrade to shared, simply update our internal notion of the
2010 ** lock state. No need to mess with the file on disk.
2011 */
drh308c2a52010-05-14 11:30:18 +00002012 if( eFileLock==SHARED_LOCK ){
2013 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002014 return SQLITE_OK;
2015 }
2016
drh7708e972008-11-29 00:56:52 +00002017 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002018 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002019 rc = osRmdir(zLockFile);
2020 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2021 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002022 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002023 rc = 0;
drh734c9862008-11-28 15:37:20 +00002024 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002025 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002026 }
2027 if( IS_LOCK_ERROR(rc) ){
2028 pFile->lastErrno = tErrno;
2029 }
2030 return rc;
2031 }
drh308c2a52010-05-14 11:30:18 +00002032 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002033 return SQLITE_OK;
2034}
2035
2036/*
drh9b35ea62008-11-29 02:20:26 +00002037** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002038*/
2039static int dotlockClose(sqlite3_file *id) {
2040 int rc;
2041 if( id ){
2042 unixFile *pFile = (unixFile*)id;
2043 dotlockUnlock(id, NO_LOCK);
2044 sqlite3_free(pFile->lockingContext);
2045 }
drh734c9862008-11-28 15:37:20 +00002046 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002047 return rc;
2048}
2049/****************** End of the dot-file lock implementation *******************
2050******************************************************************************/
2051
2052/******************************************************************************
2053************************** Begin flock Locking ********************************
2054**
2055** Use the flock() system call to do file locking.
2056**
drh6b9d6dd2008-12-03 19:34:47 +00002057** flock() locking is like dot-file locking in that the various
2058** fine-grain locking levels supported by SQLite are collapsed into
2059** a single exclusive lock. In other words, SHARED, RESERVED, and
2060** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2061** still works when you do this, but concurrency is reduced since
2062** only a single process can be reading the database at a time.
2063**
drh734c9862008-11-28 15:37:20 +00002064** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2065** compiling for VXWORKS.
2066*/
2067#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002068
drh6b9d6dd2008-12-03 19:34:47 +00002069/*
drhff812312011-02-23 13:33:46 +00002070** Retry flock() calls that fail with EINTR
2071*/
2072#ifdef EINTR
2073static int robust_flock(int fd, int op){
2074 int rc;
2075 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2076 return rc;
2077}
2078#else
drh5c819272011-02-23 14:00:12 +00002079# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002080#endif
2081
2082
2083/*
drh6b9d6dd2008-12-03 19:34:47 +00002084** This routine checks if there is a RESERVED lock held on the specified
2085** file by this or any other process. If such a lock is held, set *pResOut
2086** to a non-zero value otherwise *pResOut is set to zero. The return value
2087** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2088*/
drh734c9862008-11-28 15:37:20 +00002089static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2090 int rc = SQLITE_OK;
2091 int reserved = 0;
2092 unixFile *pFile = (unixFile*)id;
2093
2094 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2095
2096 assert( pFile );
2097
2098 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002099 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002100 reserved = 1;
2101 }
2102
2103 /* Otherwise see if some other process holds it. */
2104 if( !reserved ){
2105 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002106 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002107 if( !lrc ){
2108 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002109 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002110 if ( lrc ) {
2111 int tErrno = errno;
2112 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002113 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002114 if( IS_LOCK_ERROR(lrc) ){
2115 pFile->lastErrno = tErrno;
2116 rc = lrc;
2117 }
2118 }
2119 } else {
2120 int tErrno = errno;
2121 reserved = 1;
2122 /* someone else might have it reserved */
2123 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2124 if( IS_LOCK_ERROR(lrc) ){
2125 pFile->lastErrno = tErrno;
2126 rc = lrc;
2127 }
2128 }
2129 }
drh308c2a52010-05-14 11:30:18 +00002130 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002131
2132#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2133 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2134 rc = SQLITE_OK;
2135 reserved=1;
2136 }
2137#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2138 *pResOut = reserved;
2139 return rc;
2140}
2141
drh6b9d6dd2008-12-03 19:34:47 +00002142/*
drh308c2a52010-05-14 11:30:18 +00002143** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002144** of the following:
2145**
2146** (1) SHARED_LOCK
2147** (2) RESERVED_LOCK
2148** (3) PENDING_LOCK
2149** (4) EXCLUSIVE_LOCK
2150**
2151** Sometimes when requesting one lock state, additional lock states
2152** are inserted in between. The locking might fail on one of the later
2153** transitions leaving the lock state different from what it started but
2154** still short of its goal. The following chart shows the allowed
2155** transitions and the inserted intermediate states:
2156**
2157** UNLOCKED -> SHARED
2158** SHARED -> RESERVED
2159** SHARED -> (PENDING) -> EXCLUSIVE
2160** RESERVED -> (PENDING) -> EXCLUSIVE
2161** PENDING -> EXCLUSIVE
2162**
2163** flock() only really support EXCLUSIVE locks. We track intermediate
2164** lock states in the sqlite3_file structure, but all locks SHARED or
2165** above are really EXCLUSIVE locks and exclude all other processes from
2166** access the file.
2167**
2168** This routine will only increase a lock. Use the sqlite3OsUnlock()
2169** routine to lower a locking level.
2170*/
drh308c2a52010-05-14 11:30:18 +00002171static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002172 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002173 unixFile *pFile = (unixFile*)id;
2174
2175 assert( pFile );
2176
2177 /* if we already have a lock, it is exclusive.
2178 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002179 if (pFile->eFileLock > NO_LOCK) {
2180 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002181 return SQLITE_OK;
2182 }
2183
2184 /* grab an exclusive lock */
2185
drhff812312011-02-23 13:33:46 +00002186 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002187 int tErrno = errno;
2188 /* didn't get, must be busy */
2189 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2190 if( IS_LOCK_ERROR(rc) ){
2191 pFile->lastErrno = tErrno;
2192 }
2193 } else {
2194 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002195 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002196 }
drh308c2a52010-05-14 11:30:18 +00002197 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2198 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002199#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2200 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2201 rc = SQLITE_BUSY;
2202 }
2203#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2204 return rc;
2205}
2206
drh6b9d6dd2008-12-03 19:34:47 +00002207
2208/*
drh308c2a52010-05-14 11:30:18 +00002209** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002210** must be either NO_LOCK or SHARED_LOCK.
2211**
2212** If the locking level of the file descriptor is already at or below
2213** the requested locking level, this routine is a no-op.
2214*/
drh308c2a52010-05-14 11:30:18 +00002215static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002216 unixFile *pFile = (unixFile*)id;
2217
2218 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002219 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2220 pFile->eFileLock, getpid()));
2221 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002222
2223 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002224 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002225 return SQLITE_OK;
2226 }
2227
2228 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002229 if (eFileLock==SHARED_LOCK) {
2230 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002231 return SQLITE_OK;
2232 }
2233
2234 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002235 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002236#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002237 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002238#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002239 return SQLITE_IOERR_UNLOCK;
2240 }else{
drh308c2a52010-05-14 11:30:18 +00002241 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002242 return SQLITE_OK;
2243 }
2244}
2245
2246/*
2247** Close a file.
2248*/
2249static int flockClose(sqlite3_file *id) {
2250 if( id ){
2251 flockUnlock(id, NO_LOCK);
2252 }
2253 return closeUnixFile(id);
2254}
2255
2256#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2257
2258/******************* End of the flock lock implementation *********************
2259******************************************************************************/
2260
2261/******************************************************************************
2262************************ Begin Named Semaphore Locking ************************
2263**
2264** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002265**
2266** Semaphore locking is like dot-lock and flock in that it really only
2267** supports EXCLUSIVE locking. Only a single process can read or write
2268** the database file at a time. This reduces potential concurrency, but
2269** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002270*/
2271#if OS_VXWORKS
2272
drh6b9d6dd2008-12-03 19:34:47 +00002273/*
2274** This routine checks if there is a RESERVED lock held on the specified
2275** file by this or any other process. If such a lock is held, set *pResOut
2276** to a non-zero value otherwise *pResOut is set to zero. The return value
2277** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2278*/
drh734c9862008-11-28 15:37:20 +00002279static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2280 int rc = SQLITE_OK;
2281 int reserved = 0;
2282 unixFile *pFile = (unixFile*)id;
2283
2284 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2285
2286 assert( pFile );
2287
2288 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002289 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002290 reserved = 1;
2291 }
2292
2293 /* Otherwise see if some other process holds it. */
2294 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002295 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002296 struct stat statBuf;
2297
2298 if( sem_trywait(pSem)==-1 ){
2299 int tErrno = errno;
2300 if( EAGAIN != tErrno ){
2301 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2302 pFile->lastErrno = tErrno;
2303 } else {
2304 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002305 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002306 }
2307 }else{
2308 /* we could have it if we want it */
2309 sem_post(pSem);
2310 }
2311 }
drh308c2a52010-05-14 11:30:18 +00002312 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002313
2314 *pResOut = reserved;
2315 return rc;
2316}
2317
drh6b9d6dd2008-12-03 19:34:47 +00002318/*
drh308c2a52010-05-14 11:30:18 +00002319** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002320** of the following:
2321**
2322** (1) SHARED_LOCK
2323** (2) RESERVED_LOCK
2324** (3) PENDING_LOCK
2325** (4) EXCLUSIVE_LOCK
2326**
2327** Sometimes when requesting one lock state, additional lock states
2328** are inserted in between. The locking might fail on one of the later
2329** transitions leaving the lock state different from what it started but
2330** still short of its goal. The following chart shows the allowed
2331** transitions and the inserted intermediate states:
2332**
2333** UNLOCKED -> SHARED
2334** SHARED -> RESERVED
2335** SHARED -> (PENDING) -> EXCLUSIVE
2336** RESERVED -> (PENDING) -> EXCLUSIVE
2337** PENDING -> EXCLUSIVE
2338**
2339** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2340** lock states in the sqlite3_file structure, but all locks SHARED or
2341** above are really EXCLUSIVE locks and exclude all other processes from
2342** access the file.
2343**
2344** This routine will only increase a lock. Use the sqlite3OsUnlock()
2345** routine to lower a locking level.
2346*/
drh308c2a52010-05-14 11:30:18 +00002347static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002348 unixFile *pFile = (unixFile*)id;
2349 int fd;
drh8af6c222010-05-14 12:43:01 +00002350 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002351 int rc = SQLITE_OK;
2352
2353 /* if we already have a lock, it is exclusive.
2354 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002355 if (pFile->eFileLock > NO_LOCK) {
2356 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002357 rc = SQLITE_OK;
2358 goto sem_end_lock;
2359 }
2360
2361 /* lock semaphore now but bail out when already locked. */
2362 if( sem_trywait(pSem)==-1 ){
2363 rc = SQLITE_BUSY;
2364 goto sem_end_lock;
2365 }
2366
2367 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002368 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002369
2370 sem_end_lock:
2371 return rc;
2372}
2373
drh6b9d6dd2008-12-03 19:34:47 +00002374/*
drh308c2a52010-05-14 11:30:18 +00002375** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002376** must be either NO_LOCK or SHARED_LOCK.
2377**
2378** If the locking level of the file descriptor is already at or below
2379** the requested locking level, this routine is a no-op.
2380*/
drh308c2a52010-05-14 11:30:18 +00002381static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002382 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002383 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002384
2385 assert( pFile );
2386 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002387 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2388 pFile->eFileLock, getpid()));
2389 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002390
2391 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002392 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002393 return SQLITE_OK;
2394 }
2395
2396 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002397 if (eFileLock==SHARED_LOCK) {
2398 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002399 return SQLITE_OK;
2400 }
2401
2402 /* no, really unlock. */
2403 if ( sem_post(pSem)==-1 ) {
2404 int rc, tErrno = errno;
2405 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2406 if( IS_LOCK_ERROR(rc) ){
2407 pFile->lastErrno = tErrno;
2408 }
2409 return rc;
2410 }
drh308c2a52010-05-14 11:30:18 +00002411 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002412 return SQLITE_OK;
2413}
2414
2415/*
2416 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002417 */
drh734c9862008-11-28 15:37:20 +00002418static int semClose(sqlite3_file *id) {
2419 if( id ){
2420 unixFile *pFile = (unixFile*)id;
2421 semUnlock(id, NO_LOCK);
2422 assert( pFile );
2423 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002424 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002425 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002426 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002427 }
2428 return SQLITE_OK;
2429}
2430
2431#endif /* OS_VXWORKS */
2432/*
2433** Named semaphore locking is only available on VxWorks.
2434**
2435*************** End of the named semaphore lock implementation ****************
2436******************************************************************************/
2437
2438
2439/******************************************************************************
2440*************************** Begin AFP Locking *********************************
2441**
2442** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2443** on Apple Macintosh computers - both OS9 and OSX.
2444**
2445** Third-party implementations of AFP are available. But this code here
2446** only works on OSX.
2447*/
2448
drhd2cb50b2009-01-09 21:41:17 +00002449#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002450/*
2451** The afpLockingContext structure contains all afp lock specific state
2452*/
drhbfe66312006-10-03 17:40:40 +00002453typedef struct afpLockingContext afpLockingContext;
2454struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002455 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002456 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002457};
2458
2459struct ByteRangeLockPB2
2460{
2461 unsigned long long offset; /* offset to first byte to lock */
2462 unsigned long long length; /* nbr of bytes to lock */
2463 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2464 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2465 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2466 int fd; /* file desc to assoc this lock with */
2467};
2468
drhfd131da2007-08-07 17:13:03 +00002469#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002470
drh6b9d6dd2008-12-03 19:34:47 +00002471/*
2472** This is a utility for setting or clearing a bit-range lock on an
2473** AFP filesystem.
2474**
2475** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2476*/
2477static int afpSetLock(
2478 const char *path, /* Name of the file to be locked or unlocked */
2479 unixFile *pFile, /* Open file descriptor on path */
2480 unsigned long long offset, /* First byte to be locked */
2481 unsigned long long length, /* Number of bytes to lock */
2482 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002483){
drh6b9d6dd2008-12-03 19:34:47 +00002484 struct ByteRangeLockPB2 pb;
2485 int err;
drhbfe66312006-10-03 17:40:40 +00002486
2487 pb.unLockFlag = setLockFlag ? 0 : 1;
2488 pb.startEndFlag = 0;
2489 pb.offset = offset;
2490 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002491 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002492
drh308c2a52010-05-14 11:30:18 +00002493 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002494 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002495 offset, length));
drhbfe66312006-10-03 17:40:40 +00002496 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2497 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002498 int rc;
2499 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002500 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2501 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002502#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2503 rc = SQLITE_BUSY;
2504#else
drh734c9862008-11-28 15:37:20 +00002505 rc = sqliteErrorFromPosixError(tErrno,
2506 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002507#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002508 if( IS_LOCK_ERROR(rc) ){
2509 pFile->lastErrno = tErrno;
2510 }
2511 return rc;
drhbfe66312006-10-03 17:40:40 +00002512 } else {
aswift5b1a2562008-08-22 00:22:35 +00002513 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002514 }
2515}
2516
drh6b9d6dd2008-12-03 19:34:47 +00002517/*
2518** This routine checks if there is a RESERVED lock held on the specified
2519** file by this or any other process. If such a lock is held, set *pResOut
2520** to a non-zero value otherwise *pResOut is set to zero. The return value
2521** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2522*/
danielk1977e339d652008-06-28 11:23:00 +00002523static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002524 int rc = SQLITE_OK;
2525 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002526 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002527 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002528
aswift5b1a2562008-08-22 00:22:35 +00002529 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2530
2531 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002532 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002533 if( context->reserved ){
2534 *pResOut = 1;
2535 return SQLITE_OK;
2536 }
drh8af6c222010-05-14 12:43:01 +00002537 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002538
2539 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002540 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002541 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002542 }
2543
2544 /* Otherwise see if some other process holds it.
2545 */
aswift5b1a2562008-08-22 00:22:35 +00002546 if( !reserved ){
2547 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002548 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002549 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002550 /* if we succeeded in taking the reserved lock, unlock it to restore
2551 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002552 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002553 } else {
2554 /* if we failed to get the lock then someone else must have it */
2555 reserved = 1;
2556 }
2557 if( IS_LOCK_ERROR(lrc) ){
2558 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002559 }
2560 }
drhbfe66312006-10-03 17:40:40 +00002561
drh7ed97b92010-01-20 13:07:21 +00002562 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002563 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002564
2565 *pResOut = reserved;
2566 return rc;
drhbfe66312006-10-03 17:40:40 +00002567}
2568
drh6b9d6dd2008-12-03 19:34:47 +00002569/*
drh308c2a52010-05-14 11:30:18 +00002570** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002571** of the following:
2572**
2573** (1) SHARED_LOCK
2574** (2) RESERVED_LOCK
2575** (3) PENDING_LOCK
2576** (4) EXCLUSIVE_LOCK
2577**
2578** Sometimes when requesting one lock state, additional lock states
2579** are inserted in between. The locking might fail on one of the later
2580** transitions leaving the lock state different from what it started but
2581** still short of its goal. The following chart shows the allowed
2582** transitions and the inserted intermediate states:
2583**
2584** UNLOCKED -> SHARED
2585** SHARED -> RESERVED
2586** SHARED -> (PENDING) -> EXCLUSIVE
2587** RESERVED -> (PENDING) -> EXCLUSIVE
2588** PENDING -> EXCLUSIVE
2589**
2590** This routine will only increase a lock. Use the sqlite3OsUnlock()
2591** routine to lower a locking level.
2592*/
drh308c2a52010-05-14 11:30:18 +00002593static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002594 int rc = SQLITE_OK;
2595 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002596 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002597 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002598
2599 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002600 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2601 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002602 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002603
drhbfe66312006-10-03 17:40:40 +00002604 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002605 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002606 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002607 */
drh308c2a52010-05-14 11:30:18 +00002608 if( pFile->eFileLock>=eFileLock ){
2609 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2610 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002611 return SQLITE_OK;
2612 }
2613
2614 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002615 ** (1) We never move from unlocked to anything higher than shared lock.
2616 ** (2) SQLite never explicitly requests a pendig lock.
2617 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002618 */
drh308c2a52010-05-14 11:30:18 +00002619 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2620 assert( eFileLock!=PENDING_LOCK );
2621 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002622
drh8af6c222010-05-14 12:43:01 +00002623 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002624 */
drh6c7d5c52008-11-21 20:32:33 +00002625 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002626 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002627
2628 /* If some thread using this PID has a lock via a different unixFile*
2629 ** handle that precludes the requested lock, return BUSY.
2630 */
drh8af6c222010-05-14 12:43:01 +00002631 if( (pFile->eFileLock!=pInode->eFileLock &&
2632 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002633 ){
2634 rc = SQLITE_BUSY;
2635 goto afp_end_lock;
2636 }
2637
2638 /* If a SHARED lock is requested, and some thread using this PID already
2639 ** has a SHARED or RESERVED lock, then increment reference counts and
2640 ** return SQLITE_OK.
2641 */
drh308c2a52010-05-14 11:30:18 +00002642 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002643 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002644 assert( eFileLock==SHARED_LOCK );
2645 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002646 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002647 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002648 pInode->nShared++;
2649 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002650 goto afp_end_lock;
2651 }
drhbfe66312006-10-03 17:40:40 +00002652
2653 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002654 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2655 ** be released.
2656 */
drh308c2a52010-05-14 11:30:18 +00002657 if( eFileLock==SHARED_LOCK
2658 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002659 ){
2660 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002661 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002662 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002663 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002664 goto afp_end_lock;
2665 }
2666 }
2667
2668 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002669 ** operating system calls for the specified lock.
2670 */
drh308c2a52010-05-14 11:30:18 +00002671 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002672 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002673 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002674
drh8af6c222010-05-14 12:43:01 +00002675 assert( pInode->nShared==0 );
2676 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002677
2678 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002679 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002680 /* note that the quality of the randomness doesn't matter that much */
2681 lk = random();
drh8af6c222010-05-14 12:43:01 +00002682 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002683 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002684 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002685 if( IS_LOCK_ERROR(lrc1) ){
2686 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002687 }
aswift5b1a2562008-08-22 00:22:35 +00002688 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002689 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002690
aswift5b1a2562008-08-22 00:22:35 +00002691 if( IS_LOCK_ERROR(lrc1) ) {
2692 pFile->lastErrno = lrc1Errno;
2693 rc = lrc1;
2694 goto afp_end_lock;
2695 } else if( IS_LOCK_ERROR(lrc2) ){
2696 rc = lrc2;
2697 goto afp_end_lock;
2698 } else if( lrc1 != SQLITE_OK ) {
2699 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002700 } else {
drh308c2a52010-05-14 11:30:18 +00002701 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002702 pInode->nLock++;
2703 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002704 }
drh8af6c222010-05-14 12:43:01 +00002705 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002706 /* We are trying for an exclusive lock but another thread in this
2707 ** same process is still holding a shared lock. */
2708 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002709 }else{
2710 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2711 ** assumed that there is a SHARED or greater lock on the file
2712 ** already.
2713 */
2714 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002715 assert( 0!=pFile->eFileLock );
2716 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002717 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002718 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002719 if( !failed ){
2720 context->reserved = 1;
2721 }
drhbfe66312006-10-03 17:40:40 +00002722 }
drh308c2a52010-05-14 11:30:18 +00002723 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002724 /* Acquire an EXCLUSIVE lock */
2725
2726 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002727 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002728 */
drh6b9d6dd2008-12-03 19:34:47 +00002729 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002730 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002731 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002732 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002733 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002734 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002735 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002736 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002737 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2738 ** a critical I/O error
2739 */
2740 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2741 SQLITE_IOERR_LOCK;
2742 goto afp_end_lock;
2743 }
2744 }else{
aswift5b1a2562008-08-22 00:22:35 +00002745 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002746 }
2747 }
aswift5b1a2562008-08-22 00:22:35 +00002748 if( failed ){
2749 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002750 }
2751 }
2752
2753 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002754 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002755 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002756 }else if( eFileLock==EXCLUSIVE_LOCK ){
2757 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002758 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002759 }
2760
2761afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002762 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002763 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2764 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002765 return rc;
2766}
2767
2768/*
drh308c2a52010-05-14 11:30:18 +00002769** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002770** must be either NO_LOCK or SHARED_LOCK.
2771**
2772** If the locking level of the file descriptor is already at or below
2773** the requested locking level, this routine is a no-op.
2774*/
drh308c2a52010-05-14 11:30:18 +00002775static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002776 int rc = SQLITE_OK;
2777 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002778 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002779 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2780 int skipShared = 0;
2781#ifdef SQLITE_TEST
2782 int h = pFile->h;
2783#endif
drhbfe66312006-10-03 17:40:40 +00002784
2785 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002786 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002787 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002788 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002789
drh308c2a52010-05-14 11:30:18 +00002790 assert( eFileLock<=SHARED_LOCK );
2791 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002792 return SQLITE_OK;
2793 }
drh6c7d5c52008-11-21 20:32:33 +00002794 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002795 pInode = pFile->pInode;
2796 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002797 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002798 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002799 SimulateIOErrorBenign(1);
2800 SimulateIOError( h=(-1) )
2801 SimulateIOErrorBenign(0);
2802
2803#ifndef NDEBUG
2804 /* When reducing a lock such that other processes can start
2805 ** reading the database file again, make sure that the
2806 ** transaction counter was updated if any part of the database
2807 ** file changed. If the transaction counter is not updated,
2808 ** other connections to the same file might not realize that
2809 ** the file has changed and hence might not know to flush their
2810 ** cache. The use of a stale cache can lead to database corruption.
2811 */
2812 assert( pFile->inNormalWrite==0
2813 || pFile->dbUpdate==0
2814 || pFile->transCntrChng==1 );
2815 pFile->inNormalWrite = 0;
2816#endif
aswiftaebf4132008-11-21 00:10:35 +00002817
drh308c2a52010-05-14 11:30:18 +00002818 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002819 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002820 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002821 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002822 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002823 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2824 } else {
2825 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002826 }
2827 }
drh308c2a52010-05-14 11:30:18 +00002828 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002829 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002830 }
drh308c2a52010-05-14 11:30:18 +00002831 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002832 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2833 if( !rc ){
2834 context->reserved = 0;
2835 }
aswiftaebf4132008-11-21 00:10:35 +00002836 }
drh8af6c222010-05-14 12:43:01 +00002837 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2838 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002839 }
aswiftaebf4132008-11-21 00:10:35 +00002840 }
drh308c2a52010-05-14 11:30:18 +00002841 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002842
drh7ed97b92010-01-20 13:07:21 +00002843 /* Decrement the shared lock counter. Release the lock using an
2844 ** OS call only when all threads in this same process have released
2845 ** the lock.
2846 */
drh8af6c222010-05-14 12:43:01 +00002847 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2848 pInode->nShared--;
2849 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002850 SimulateIOErrorBenign(1);
2851 SimulateIOError( h=(-1) )
2852 SimulateIOErrorBenign(0);
2853 if( !skipShared ){
2854 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2855 }
2856 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002857 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002858 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002859 }
2860 }
2861 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002862 pInode->nLock--;
2863 assert( pInode->nLock>=0 );
2864 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002865 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002866 }
2867 }
drhbfe66312006-10-03 17:40:40 +00002868 }
drh7ed97b92010-01-20 13:07:21 +00002869
drh6c7d5c52008-11-21 20:32:33 +00002870 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002871 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002872 return rc;
2873}
2874
2875/*
drh339eb0b2008-03-07 15:34:11 +00002876** Close a file & cleanup AFP specific locking context
2877*/
danielk1977e339d652008-06-28 11:23:00 +00002878static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002879 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002880 if( id ){
2881 unixFile *pFile = (unixFile*)id;
2882 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002883 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002884 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002885 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002886 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002887 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002888 ** the last lock is cleared.
2889 */
dan08da86a2009-08-21 17:18:03 +00002890 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002891 }
danb0ac3e32010-06-16 10:55:42 +00002892 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002893 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002894 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002895 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002896 }
drh7ed97b92010-01-20 13:07:21 +00002897 return rc;
drhbfe66312006-10-03 17:40:40 +00002898}
2899
drhd2cb50b2009-01-09 21:41:17 +00002900#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002901/*
2902** The code above is the AFP lock implementation. The code is specific
2903** to MacOSX and does not work on other unix platforms. No alternative
2904** is available. If you don't compile for a mac, then the "unix-afp"
2905** VFS is not available.
2906**
2907********************* End of the AFP lock implementation **********************
2908******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002909
drh7ed97b92010-01-20 13:07:21 +00002910/******************************************************************************
2911*************************** Begin NFS Locking ********************************/
2912
2913#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2914/*
drh308c2a52010-05-14 11:30:18 +00002915 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002916 ** must be either NO_LOCK or SHARED_LOCK.
2917 **
2918 ** If the locking level of the file descriptor is already at or below
2919 ** the requested locking level, this routine is a no-op.
2920 */
drh308c2a52010-05-14 11:30:18 +00002921static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002922 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002923}
2924
2925#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2926/*
2927** The code above is the NFS lock implementation. The code is specific
2928** to MacOSX and does not work on other unix platforms. No alternative
2929** is available.
2930**
2931********************* End of the NFS lock implementation **********************
2932******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002933
2934/******************************************************************************
2935**************** Non-locking sqlite3_file methods *****************************
2936**
2937** The next division contains implementations for all methods of the
2938** sqlite3_file object other than the locking methods. The locking
2939** methods were defined in divisions above (one locking method per
2940** division). Those methods that are common to all locking modes
2941** are gather together into this division.
2942*/
drhbfe66312006-10-03 17:40:40 +00002943
2944/*
drh734c9862008-11-28 15:37:20 +00002945** Seek to the offset passed as the second argument, then read cnt
2946** bytes into pBuf. Return the number of bytes actually read.
2947**
2948** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2949** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2950** one system to another. Since SQLite does not define USE_PREAD
2951** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2952** See tickets #2741 and #2681.
2953**
2954** To avoid stomping the errno value on a failed read the lastErrno value
2955** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002956*/
drh734c9862008-11-28 15:37:20 +00002957static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2958 int got;
drh58024642011-11-07 18:16:00 +00002959 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00002960#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002961 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002962#endif
drh734c9862008-11-28 15:37:20 +00002963 TIMER_START;
drh58024642011-11-07 18:16:00 +00002964 do{
drh734c9862008-11-28 15:37:20 +00002965#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00002966 got = osPread(id->h, pBuf, cnt, offset);
2967 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002968#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00002969 got = osPread64(id->h, pBuf, cnt, offset);
2970 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002971#else
drh58024642011-11-07 18:16:00 +00002972 newOffset = lseek(id->h, offset, SEEK_SET);
2973 SimulateIOError( newOffset-- );
2974 if( newOffset!=offset ){
2975 if( newOffset == -1 ){
2976 ((unixFile*)id)->lastErrno = errno;
2977 }else{
2978 ((unixFile*)id)->lastErrno = 0;
2979 }
2980 return -1;
drh734c9862008-11-28 15:37:20 +00002981 }
drh58024642011-11-07 18:16:00 +00002982 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00002983#endif
drh58024642011-11-07 18:16:00 +00002984 if( got==cnt ) break;
2985 if( got<0 ){
2986 if( errno==EINTR ){ got = 1; continue; }
2987 prior = 0;
2988 ((unixFile*)id)->lastErrno = errno;
2989 break;
2990 }else if( got>0 ){
2991 cnt -= got;
2992 offset += got;
2993 prior += got;
2994 pBuf = (void*)(got + (char*)pBuf);
2995 }
2996 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00002997 TIMER_END;
drh58024642011-11-07 18:16:00 +00002998 OSTRACE(("READ %-3d %5d %7lld %llu\n",
2999 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3000 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003001}
3002
3003/*
drh734c9862008-11-28 15:37:20 +00003004** Read data from a file into a buffer. Return SQLITE_OK if all
3005** bytes were read successfully and SQLITE_IOERR if anything goes
3006** wrong.
drh339eb0b2008-03-07 15:34:11 +00003007*/
drh734c9862008-11-28 15:37:20 +00003008static int unixRead(
3009 sqlite3_file *id,
3010 void *pBuf,
3011 int amt,
3012 sqlite3_int64 offset
3013){
dan08da86a2009-08-21 17:18:03 +00003014 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003015 int got;
3016 assert( id );
drh08c6d442009-02-09 17:34:07 +00003017
dan08da86a2009-08-21 17:18:03 +00003018 /* If this is a database file (not a journal, master-journal or temp
3019 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003020#if 0
dane946c392009-08-22 11:39:46 +00003021 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003022 || offset>=PENDING_BYTE+512
3023 || offset+amt<=PENDING_BYTE
3024 );
dan7c246102010-04-12 19:00:29 +00003025#endif
drh08c6d442009-02-09 17:34:07 +00003026
dan08da86a2009-08-21 17:18:03 +00003027 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003028 if( got==amt ){
3029 return SQLITE_OK;
3030 }else if( got<0 ){
3031 /* lastErrno set by seekAndRead */
3032 return SQLITE_IOERR_READ;
3033 }else{
dan08da86a2009-08-21 17:18:03 +00003034 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003035 /* Unread parts of the buffer must be zero-filled */
3036 memset(&((char*)pBuf)[got], 0, amt-got);
3037 return SQLITE_IOERR_SHORT_READ;
3038 }
3039}
3040
3041/*
3042** Seek to the offset in id->offset then read cnt bytes into pBuf.
3043** Return the number of bytes actually read. Update the offset.
3044**
3045** To avoid stomping the errno value on a failed write the lastErrno value
3046** is set before returning.
3047*/
3048static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3049 int got;
drh7ed97b92010-01-20 13:07:21 +00003050#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003051 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003052#endif
drh734c9862008-11-28 15:37:20 +00003053 TIMER_START;
3054#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003055 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003056#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003057 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003058#else
drhbd1e50c2011-08-19 14:54:12 +00003059 do{
3060 newOffset = lseek(id->h, offset, SEEK_SET);
3061 SimulateIOError( newOffset-- );
3062 if( newOffset!=offset ){
3063 if( newOffset == -1 ){
3064 ((unixFile*)id)->lastErrno = errno;
3065 }else{
3066 ((unixFile*)id)->lastErrno = 0;
3067 }
3068 return -1;
drh734c9862008-11-28 15:37:20 +00003069 }
drhbd1e50c2011-08-19 14:54:12 +00003070 got = osWrite(id->h, pBuf, cnt);
3071 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003072#endif
3073 TIMER_END;
3074 if( got<0 ){
3075 ((unixFile*)id)->lastErrno = errno;
3076 }
3077
drh308c2a52010-05-14 11:30:18 +00003078 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003079 return got;
3080}
3081
3082
3083/*
3084** Write data from a buffer into a file. Return SQLITE_OK on success
3085** or some other error code on failure.
3086*/
3087static int unixWrite(
3088 sqlite3_file *id,
3089 const void *pBuf,
3090 int amt,
3091 sqlite3_int64 offset
3092){
dan08da86a2009-08-21 17:18:03 +00003093 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003094 int wrote = 0;
3095 assert( id );
3096 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003097
dan08da86a2009-08-21 17:18:03 +00003098 /* If this is a database file (not a journal, master-journal or temp
3099 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003100#if 0
dane946c392009-08-22 11:39:46 +00003101 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003102 || offset>=PENDING_BYTE+512
3103 || offset+amt<=PENDING_BYTE
3104 );
dan7c246102010-04-12 19:00:29 +00003105#endif
drh08c6d442009-02-09 17:34:07 +00003106
drh8f941bc2009-01-14 23:03:40 +00003107#ifndef NDEBUG
3108 /* If we are doing a normal write to a database file (as opposed to
3109 ** doing a hot-journal rollback or a write to some file other than a
3110 ** normal database file) then record the fact that the database
3111 ** has changed. If the transaction counter is modified, record that
3112 ** fact too.
3113 */
dan08da86a2009-08-21 17:18:03 +00003114 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003115 pFile->dbUpdate = 1; /* The database has been modified */
3116 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003117 int rc;
drh8f941bc2009-01-14 23:03:40 +00003118 char oldCntr[4];
3119 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003120 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003121 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003122 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003123 pFile->transCntrChng = 1; /* The transaction counter has changed */
3124 }
3125 }
3126 }
3127#endif
3128
dan08da86a2009-08-21 17:18:03 +00003129 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003130 amt -= wrote;
3131 offset += wrote;
3132 pBuf = &((char*)pBuf)[wrote];
3133 }
3134 SimulateIOError(( wrote=(-1), amt=1 ));
3135 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003136
drh734c9862008-11-28 15:37:20 +00003137 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003138 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003139 /* lastErrno set by seekAndWrite */
3140 return SQLITE_IOERR_WRITE;
3141 }else{
dan08da86a2009-08-21 17:18:03 +00003142 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003143 return SQLITE_FULL;
3144 }
3145 }
dan6e09d692010-07-27 18:34:15 +00003146
drh734c9862008-11-28 15:37:20 +00003147 return SQLITE_OK;
3148}
3149
3150#ifdef SQLITE_TEST
3151/*
3152** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003153** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003154*/
3155int sqlite3_sync_count = 0;
3156int sqlite3_fullsync_count = 0;
3157#endif
3158
3159/*
drh89240432009-03-25 01:06:01 +00003160** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003161** Others do no. To be safe, we will stick with the (slightly slower)
3162** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003163** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003164*/
drh20f8e132011-08-31 21:01:55 +00003165#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003166# define fdatasync fsync
3167#endif
3168
3169/*
3170** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3171** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3172** only available on Mac OS X. But that could change.
3173*/
3174#ifdef F_FULLFSYNC
3175# define HAVE_FULLFSYNC 1
3176#else
3177# define HAVE_FULLFSYNC 0
3178#endif
3179
3180
3181/*
3182** The fsync() system call does not work as advertised on many
3183** unix systems. The following procedure is an attempt to make
3184** it work better.
3185**
3186** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3187** for testing when we want to run through the test suite quickly.
3188** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3189** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3190** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003191**
3192** SQLite sets the dataOnly flag if the size of the file is unchanged.
3193** The idea behind dataOnly is that it should only write the file content
3194** to disk, not the inode. We only set dataOnly if the file size is
3195** unchanged since the file size is part of the inode. However,
3196** Ted Ts'o tells us that fdatasync() will also write the inode if the
3197** file size has changed. The only real difference between fdatasync()
3198** and fsync(), Ted tells us, is that fdatasync() will not flush the
3199** inode if the mtime or owner or other inode attributes have changed.
3200** We only care about the file size, not the other file attributes, so
3201** as far as SQLite is concerned, an fdatasync() is always adequate.
3202** So, we always use fdatasync() if it is available, regardless of
3203** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003204*/
3205static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003206 int rc;
drh734c9862008-11-28 15:37:20 +00003207
3208 /* The following "ifdef/elif/else/" block has the same structure as
3209 ** the one below. It is replicated here solely to avoid cluttering
3210 ** up the real code with the UNUSED_PARAMETER() macros.
3211 */
3212#ifdef SQLITE_NO_SYNC
3213 UNUSED_PARAMETER(fd);
3214 UNUSED_PARAMETER(fullSync);
3215 UNUSED_PARAMETER(dataOnly);
3216#elif HAVE_FULLFSYNC
3217 UNUSED_PARAMETER(dataOnly);
3218#else
3219 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003220 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003221#endif
3222
3223 /* Record the number of times that we do a normal fsync() and
3224 ** FULLSYNC. This is used during testing to verify that this procedure
3225 ** gets called with the correct arguments.
3226 */
3227#ifdef SQLITE_TEST
3228 if( fullSync ) sqlite3_fullsync_count++;
3229 sqlite3_sync_count++;
3230#endif
3231
3232 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3233 ** no-op
3234 */
3235#ifdef SQLITE_NO_SYNC
3236 rc = SQLITE_OK;
3237#elif HAVE_FULLFSYNC
3238 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003239 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003240 }else{
3241 rc = 1;
3242 }
3243 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003244 ** It shouldn't be possible for fullfsync to fail on the local
3245 ** file system (on OSX), so failure indicates that FULLFSYNC
3246 ** isn't supported for this file system. So, attempt an fsync
3247 ** and (for now) ignore the overhead of a superfluous fcntl call.
3248 ** It'd be better to detect fullfsync support once and avoid
3249 ** the fcntl call every time sync is called.
3250 */
drh734c9862008-11-28 15:37:20 +00003251 if( rc ) rc = fsync(fd);
3252
drh7ed97b92010-01-20 13:07:21 +00003253#elif defined(__APPLE__)
3254 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3255 ** so currently we default to the macro that redefines fdatasync to fsync
3256 */
3257 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003258#else
drh0b647ff2009-03-21 14:41:04 +00003259 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003260#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003261 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003262 rc = fsync(fd);
3263 }
drh0b647ff2009-03-21 14:41:04 +00003264#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003265#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3266
3267 if( OS_VXWORKS && rc!= -1 ){
3268 rc = 0;
3269 }
chw97185482008-11-17 08:05:31 +00003270 return rc;
drhbfe66312006-10-03 17:40:40 +00003271}
3272
drh734c9862008-11-28 15:37:20 +00003273/*
drh0059eae2011-08-08 23:48:40 +00003274** Open a file descriptor to the directory containing file zFilename.
3275** If successful, *pFd is set to the opened file descriptor and
3276** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3277** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3278** value.
3279**
drh90315a22011-08-10 01:52:12 +00003280** The directory file descriptor is used for only one thing - to
3281** fsync() a directory to make sure file creation and deletion events
3282** are flushed to disk. Such fsyncs are not needed on newer
3283** journaling filesystems, but are required on older filesystems.
3284**
3285** This routine can be overridden using the xSetSysCall interface.
3286** The ability to override this routine was added in support of the
3287** chromium sandbox. Opening a directory is a security risk (we are
3288** told) so making it overrideable allows the chromium sandbox to
3289** replace this routine with a harmless no-op. To make this routine
3290** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3291** *pFd set to a negative number.
3292**
drh0059eae2011-08-08 23:48:40 +00003293** If SQLITE_OK is returned, the caller is responsible for closing
3294** the file descriptor *pFd using close().
3295*/
3296static int openDirectory(const char *zFilename, int *pFd){
3297 int ii;
3298 int fd = -1;
3299 char zDirname[MAX_PATHNAME+1];
3300
3301 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3302 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3303 if( ii>0 ){
3304 zDirname[ii] = '\0';
3305 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3306 if( fd>=0 ){
3307#ifdef FD_CLOEXEC
3308 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3309#endif
3310 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3311 }
3312 }
3313 *pFd = fd;
3314 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3315}
3316
3317/*
drh734c9862008-11-28 15:37:20 +00003318** Make sure all writes to a particular file are committed to disk.
3319**
3320** If dataOnly==0 then both the file itself and its metadata (file
3321** size, access time, etc) are synced. If dataOnly!=0 then only the
3322** file data is synced.
3323**
3324** Under Unix, also make sure that the directory entry for the file
3325** has been created by fsync-ing the directory that contains the file.
3326** If we do not do this and we encounter a power failure, the directory
3327** entry for the journal might not exist after we reboot. The next
3328** SQLite to access the file will not know that the journal exists (because
3329** the directory entry for the journal was never created) and the transaction
3330** will not roll back - possibly leading to database corruption.
3331*/
3332static int unixSync(sqlite3_file *id, int flags){
3333 int rc;
3334 unixFile *pFile = (unixFile*)id;
3335
3336 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3337 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3338
3339 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3340 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3341 || (flags&0x0F)==SQLITE_SYNC_FULL
3342 );
3343
3344 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3345 ** line is to test that doing so does not cause any problems.
3346 */
3347 SimulateDiskfullError( return SQLITE_FULL );
3348
3349 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003350 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003351 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3352 SimulateIOError( rc=1 );
3353 if( rc ){
3354 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003355 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003356 }
drh0059eae2011-08-08 23:48:40 +00003357
3358 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003359 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3360 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003361 */
3362 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3363 int dirfd;
3364 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003365 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003366 rc = osOpenDirectory(pFile->zPath, &dirfd);
3367 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003368 full_fsync(dirfd, 0, 0);
3369 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003370 }else if( rc==SQLITE_CANTOPEN ){
3371 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003372 }
drh0059eae2011-08-08 23:48:40 +00003373 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003374 }
3375 return rc;
3376}
3377
3378/*
3379** Truncate an open file to a specified size
3380*/
3381static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003382 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003383 int rc;
dan6e09d692010-07-27 18:34:15 +00003384 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003385 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003386
3387 /* If the user has configured a chunk-size for this file, truncate the
3388 ** file so that it consists of an integer number of chunks (i.e. the
3389 ** actual file size after the operation may be larger than the requested
3390 ** size).
3391 */
3392 if( pFile->szChunk ){
3393 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3394 }
3395
drhff812312011-02-23 13:33:46 +00003396 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003397 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003398 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003399 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003400 }else{
drh3313b142009-11-06 04:13:18 +00003401#ifndef NDEBUG
3402 /* If we are doing a normal write to a database file (as opposed to
3403 ** doing a hot-journal rollback or a write to some file other than a
3404 ** normal database file) and we truncate the file to zero length,
3405 ** that effectively updates the change counter. This might happen
3406 ** when restoring a database using the backup API from a zero-length
3407 ** source.
3408 */
dan6e09d692010-07-27 18:34:15 +00003409 if( pFile->inNormalWrite && nByte==0 ){
3410 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003411 }
3412#endif
3413
drh734c9862008-11-28 15:37:20 +00003414 return SQLITE_OK;
3415 }
3416}
3417
3418/*
3419** Determine the current size of a file in bytes
3420*/
3421static int unixFileSize(sqlite3_file *id, i64 *pSize){
3422 int rc;
3423 struct stat buf;
3424 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003425 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003426 SimulateIOError( rc=1 );
3427 if( rc!=0 ){
3428 ((unixFile*)id)->lastErrno = errno;
3429 return SQLITE_IOERR_FSTAT;
3430 }
3431 *pSize = buf.st_size;
3432
drh8af6c222010-05-14 12:43:01 +00003433 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003434 ** writes a single byte into that file in order to work around a bug
3435 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3436 ** layers, we need to report this file size as zero even though it is
3437 ** really 1. Ticket #3260.
3438 */
3439 if( *pSize==1 ) *pSize = 0;
3440
3441
3442 return SQLITE_OK;
3443}
3444
drhd2cb50b2009-01-09 21:41:17 +00003445#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003446/*
3447** Handler for proxy-locking file-control verbs. Defined below in the
3448** proxying locking division.
3449*/
3450static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003451#endif
drh715ff302008-12-03 22:32:44 +00003452
dan502019c2010-07-28 14:26:17 +00003453/*
3454** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003455** file-control operation. Enlarge the database to nBytes in size
3456** (rounded up to the next chunk-size). If the database is already
3457** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003458*/
3459static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003460 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003461 i64 nSize; /* Required file size */
3462 struct stat buf; /* Used to hold return values of fstat() */
3463
drh99ab3b12011-03-02 15:09:07 +00003464 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003465
3466 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3467 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003468
dan502019c2010-07-28 14:26:17 +00003469#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003470 /* The code below is handling the return value of osFallocate()
3471 ** correctly. posix_fallocate() is defined to "returns zero on success,
3472 ** or an error number on failure". See the manpage for details. */
3473 int err;
drhff812312011-02-23 13:33:46 +00003474 do{
dan661d71a2011-03-30 19:08:03 +00003475 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3476 }while( err==EINTR );
3477 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003478#else
3479 /* If the OS does not have posix_fallocate(), fake it. First use
3480 ** ftruncate() to set the file size, then write a single byte to
3481 ** the last byte in each block within the extended region. This
3482 ** is the same technique used by glibc to implement posix_fallocate()
3483 ** on systems that do not have a real fallocate() system call.
3484 */
3485 int nBlk = buf.st_blksize; /* File-system block size */
3486 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003487
drhff812312011-02-23 13:33:46 +00003488 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003489 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003490 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003491 }
3492 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003493 while( iWrite<nSize ){
3494 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3495 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003496 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003497 }
dan502019c2010-07-28 14:26:17 +00003498#endif
3499 }
3500 }
3501
3502 return SQLITE_OK;
3503}
danielk1977ad94b582007-08-20 06:44:22 +00003504
danielk1977e3026632004-06-22 11:29:02 +00003505/*
drhf12b3f62011-12-21 14:42:29 +00003506** If *pArg is inititially negative then this is a query. Set *pArg to
3507** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3508**
3509** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3510*/
3511static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3512 if( *pArg<0 ){
3513 *pArg = (pFile->ctrlFlags & mask)!=0;
3514 }else if( (*pArg)==0 ){
3515 pFile->ctrlFlags &= ~mask;
3516 }else{
3517 pFile->ctrlFlags |= mask;
3518 }
3519}
3520
3521/*
drh9e33c2c2007-08-31 18:34:59 +00003522** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003523*/
drhcc6bb3e2007-08-31 16:11:35 +00003524static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003525 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003526 switch( op ){
3527 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003528 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003529 return SQLITE_OK;
3530 }
drh7708e972008-11-29 00:56:52 +00003531 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003532 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003533 return SQLITE_OK;
3534 }
dan6e09d692010-07-27 18:34:15 +00003535 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003536 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003537 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003538 }
drh9ff27ec2010-05-19 19:26:05 +00003539 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003540 int rc;
3541 SimulateIOErrorBenign(1);
3542 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3543 SimulateIOErrorBenign(0);
3544 return rc;
drhf0b190d2011-07-26 16:03:07 +00003545 }
3546 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003547 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3548 return SQLITE_OK;
3549 }
drhcb15f352011-12-23 01:04:17 +00003550 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3551 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003552 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003553 }
drhde60fc22011-12-14 17:53:36 +00003554 case SQLITE_FCNTL_VFSNAME: {
3555 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3556 return SQLITE_OK;
3557 }
drh8f941bc2009-01-14 23:03:40 +00003558#ifndef NDEBUG
3559 /* The pager calls this method to signal that it has done
3560 ** a rollback and that the database is therefore unchanged and
3561 ** it hence it is OK for the transaction change counter to be
3562 ** unchanged.
3563 */
3564 case SQLITE_FCNTL_DB_UNCHANGED: {
3565 ((unixFile*)id)->dbUpdate = 0;
3566 return SQLITE_OK;
3567 }
3568#endif
drhd2cb50b2009-01-09 21:41:17 +00003569#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003570 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003571 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003572 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003573 }
drhd2cb50b2009-01-09 21:41:17 +00003574#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003575 }
drh0b52b7d2011-01-26 19:46:22 +00003576 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003577}
3578
3579/*
danielk1977a3d4c882007-03-23 10:08:38 +00003580** Return the sector size in bytes of the underlying block device for
3581** the specified file. This is almost always 512 bytes, but may be
3582** larger for some devices.
3583**
3584** SQLite code assumes this function cannot fail. It also assumes that
3585** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003586** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003587** same for both.
3588*/
drh1da88f02011-12-17 16:09:16 +00003589static int unixSectorSize(sqlite3_file *pFile){
drh8942d412012-01-02 18:20:14 +00003590 (void)pFile;
3591 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003592}
3593
danielk197790949c22007-08-17 16:50:38 +00003594/*
drhf12b3f62011-12-21 14:42:29 +00003595** Return the device characteristics for the file.
3596**
drhcb15f352011-12-23 01:04:17 +00003597** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3598** However, that choice is contraversial since technically the underlying
3599** file system does not always provide powersafe overwrites. (In other
3600** words, after a power-loss event, parts of the file that were never
3601** written might end up being altered.) However, non-PSOW behavior is very,
3602** very rare. And asserting PSOW makes a large reduction in the amount
3603** of required I/O for journaling, since a lot of padding is eliminated.
3604** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3605** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003606*/
drhf12b3f62011-12-21 14:42:29 +00003607static int unixDeviceCharacteristics(sqlite3_file *id){
3608 unixFile *p = (unixFile*)id;
drhcb15f352011-12-23 01:04:17 +00003609 if( p->ctrlFlags & UNIXFILE_PSOW ){
3610 return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3611 }else{
3612 return 0;
3613 }
danielk197762079062007-08-15 17:08:46 +00003614}
3615
drhd9e5c4f2010-05-12 18:01:39 +00003616#ifndef SQLITE_OMIT_WAL
3617
3618
3619/*
drhd91c68f2010-05-14 14:52:25 +00003620** Object used to represent an shared memory buffer.
3621**
3622** When multiple threads all reference the same wal-index, each thread
3623** has its own unixShm object, but they all point to a single instance
3624** of this unixShmNode object. In other words, each wal-index is opened
3625** only once per process.
3626**
3627** Each unixShmNode object is connected to a single unixInodeInfo object.
3628** We could coalesce this object into unixInodeInfo, but that would mean
3629** every open file that does not use shared memory (in other words, most
3630** open files) would have to carry around this extra information. So
3631** the unixInodeInfo object contains a pointer to this unixShmNode object
3632** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003633**
3634** unixMutexHeld() must be true when creating or destroying
3635** this object or while reading or writing the following fields:
3636**
3637** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003638**
3639** The following fields are read-only after the object is created:
3640**
3641** fid
3642** zFilename
3643**
drhd91c68f2010-05-14 14:52:25 +00003644** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003645** unixMutexHeld() is true when reading or writing any other field
3646** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003647*/
drhd91c68f2010-05-14 14:52:25 +00003648struct unixShmNode {
3649 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003650 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003651 char *zFilename; /* Name of the mmapped file */
3652 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003653 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003654 u16 nRegion; /* Size of array apRegion */
3655 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003656 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003657 int nRef; /* Number of unixShm objects pointing to this */
3658 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003659#ifdef SQLITE_DEBUG
3660 u8 exclMask; /* Mask of exclusive locks held */
3661 u8 sharedMask; /* Mask of shared locks held */
3662 u8 nextShmId; /* Next available unixShm.id value */
3663#endif
3664};
3665
3666/*
drhd9e5c4f2010-05-12 18:01:39 +00003667** Structure used internally by this VFS to record the state of an
3668** open shared memory connection.
3669**
drhd91c68f2010-05-14 14:52:25 +00003670** The following fields are initialized when this object is created and
3671** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003672**
drhd91c68f2010-05-14 14:52:25 +00003673** unixShm.pFile
3674** unixShm.id
3675**
3676** All other fields are read/write. The unixShm.pFile->mutex must be held
3677** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003678*/
3679struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003680 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3681 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003682 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003683 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003684 u16 sharedMask; /* Mask of shared locks held */
3685 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003686};
3687
3688/*
drhd9e5c4f2010-05-12 18:01:39 +00003689** Constants used for locking
3690*/
drhbd9676c2010-06-23 17:58:38 +00003691#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003692#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003693
drhd9e5c4f2010-05-12 18:01:39 +00003694/*
drh73b64e42010-05-30 19:55:15 +00003695** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003696**
3697** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3698** otherwise.
3699*/
3700static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003701 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3702 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003703 int ofst, /* First byte of the locking range */
3704 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003705){
3706 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003707 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003708
drhd91c68f2010-05-14 14:52:25 +00003709 /* Access to the unixShmNode object is serialized by the caller */
3710 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003711
drh73b64e42010-05-30 19:55:15 +00003712 /* Shared locks never span more than one byte */
3713 assert( n==1 || lockType!=F_RDLCK );
3714
3715 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003716 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003717
drh3cb93392011-03-12 18:10:44 +00003718 if( pShmNode->h>=0 ){
3719 /* Initialize the locking parameters */
3720 memset(&f, 0, sizeof(f));
3721 f.l_type = lockType;
3722 f.l_whence = SEEK_SET;
3723 f.l_start = ofst;
3724 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003725
drh3cb93392011-03-12 18:10:44 +00003726 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3727 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3728 }
drhd9e5c4f2010-05-12 18:01:39 +00003729
3730 /* Update the global lock state and do debug tracing */
3731#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003732 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003733 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003734 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003735 if( rc==SQLITE_OK ){
3736 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003737 OSTRACE(("unlock %d ok", ofst));
3738 pShmNode->exclMask &= ~mask;
3739 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003740 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003741 OSTRACE(("read-lock %d ok", ofst));
3742 pShmNode->exclMask &= ~mask;
3743 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003744 }else{
3745 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003746 OSTRACE(("write-lock %d ok", ofst));
3747 pShmNode->exclMask |= mask;
3748 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003749 }
3750 }else{
3751 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003752 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003753 }else if( lockType==F_RDLCK ){
3754 OSTRACE(("read-lock failed"));
3755 }else{
3756 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003757 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003758 }
3759 }
drh20e1f082010-05-31 16:10:12 +00003760 OSTRACE((" - afterwards %03x,%03x\n",
3761 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003762 }
drhd9e5c4f2010-05-12 18:01:39 +00003763#endif
3764
3765 return rc;
3766}
3767
drhd9e5c4f2010-05-12 18:01:39 +00003768
3769/*
drhd91c68f2010-05-14 14:52:25 +00003770** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003771**
3772** This is not a VFS shared-memory method; it is a utility function called
3773** by VFS shared-memory methods.
3774*/
drhd91c68f2010-05-14 14:52:25 +00003775static void unixShmPurge(unixFile *pFd){
3776 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003777 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003778 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003779 int i;
drhd91c68f2010-05-14 14:52:25 +00003780 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003781 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003782 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003783 if( p->h>=0 ){
3784 munmap(p->apRegion[i], p->szRegion);
3785 }else{
3786 sqlite3_free(p->apRegion[i]);
3787 }
dan13a3cb82010-06-11 19:04:21 +00003788 }
dan18801912010-06-14 14:07:50 +00003789 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003790 if( p->h>=0 ){
3791 robust_close(pFd, p->h, __LINE__);
3792 p->h = -1;
3793 }
drhd91c68f2010-05-14 14:52:25 +00003794 p->pInode->pShmNode = 0;
3795 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003796 }
3797}
3798
3799/*
danda9fe0c2010-07-13 18:44:03 +00003800** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003801** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003802**
drh7234c6d2010-06-19 15:10:09 +00003803** The file used to implement shared-memory is in the same directory
3804** as the open database file and has the same name as the open database
3805** file with the "-shm" suffix added. For example, if the database file
3806** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003807** for shared memory will be called "/home/user1/config.db-shm".
3808**
3809** Another approach to is to use files in /dev/shm or /dev/tmp or an
3810** some other tmpfs mount. But if a file in a different directory
3811** from the database file is used, then differing access permissions
3812** or a chroot() might cause two different processes on the same
3813** database to end up using different files for shared memory -
3814** meaning that their memory would not really be shared - resulting
3815** in database corruption. Nevertheless, this tmpfs file usage
3816** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3817** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3818** option results in an incompatible build of SQLite; builds of SQLite
3819** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3820** same database file at the same time, database corruption will likely
3821** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3822** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003823**
3824** When opening a new shared-memory file, if no other instances of that
3825** file are currently open, in this process or in other processes, then
3826** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003827**
3828** If the original database file (pDbFd) is using the "unix-excl" VFS
3829** that means that an exclusive lock is held on the database file and
3830** that no other processes are able to read or write the database. In
3831** that case, we do not really need shared memory. No shared memory
3832** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003833*/
danda9fe0c2010-07-13 18:44:03 +00003834static int unixOpenSharedMemory(unixFile *pDbFd){
3835 struct unixShm *p = 0; /* The connection to be opened */
3836 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3837 int rc; /* Result code */
3838 unixInodeInfo *pInode; /* The inode of fd */
3839 char *zShmFilename; /* Name of the file used for SHM */
3840 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003841
danda9fe0c2010-07-13 18:44:03 +00003842 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003843 p = sqlite3_malloc( sizeof(*p) );
3844 if( p==0 ) return SQLITE_NOMEM;
3845 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003846 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003847
danda9fe0c2010-07-13 18:44:03 +00003848 /* Check to see if a unixShmNode object already exists. Reuse an existing
3849 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003850 */
3851 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003852 pInode = pDbFd->pInode;
3853 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003854 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003855 struct stat sStat; /* fstat() info for database file */
3856
3857 /* Call fstat() to figure out the permissions on the database file. If
3858 ** a new *-shm file is created, an attempt will be made to create it
3859 ** with the same permissions. The actual permissions the file is created
3860 ** with are subject to the current umask setting.
3861 */
drh3cb93392011-03-12 18:10:44 +00003862 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003863 rc = SQLITE_IOERR_FSTAT;
3864 goto shm_open_err;
3865 }
3866
drha4ced192010-07-15 18:32:40 +00003867#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00003868 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00003869#else
drh52bcde02012-01-03 14:50:45 +00003870 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003871#endif
drh7234c6d2010-06-19 15:10:09 +00003872 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003873 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003874 rc = SQLITE_NOMEM;
3875 goto shm_open_err;
3876 }
drh9cb5a0d2012-01-05 21:19:54 +00003877 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00003878 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003879#ifdef SQLITE_SHM_DIRECTORY
3880 sqlite3_snprintf(nShmFilename, zShmFilename,
3881 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3882 (u32)sStat.st_ino, (u32)sStat.st_dev);
3883#else
drh7234c6d2010-06-19 15:10:09 +00003884 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003885 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003886#endif
drhd91c68f2010-05-14 14:52:25 +00003887 pShmNode->h = -1;
3888 pDbFd->pInode->pShmNode = pShmNode;
3889 pShmNode->pInode = pDbFd->pInode;
3890 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3891 if( pShmNode->mutex==0 ){
3892 rc = SQLITE_NOMEM;
3893 goto shm_open_err;
3894 }
drhd9e5c4f2010-05-12 18:01:39 +00003895
drh3cb93392011-03-12 18:10:44 +00003896 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003897 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003898 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003899 openFlags = O_RDONLY;
3900 pShmNode->isReadonly = 1;
3901 }
3902 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003903 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00003904 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3905 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003906 }
drh3cb93392011-03-12 18:10:44 +00003907
3908 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003909 ** If not, truncate the file to zero length.
3910 */
3911 rc = SQLITE_OK;
3912 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3913 if( robust_ftruncate(pShmNode->h, 0) ){
3914 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003915 }
3916 }
drh66dfec8b2011-06-01 20:01:49 +00003917 if( rc==SQLITE_OK ){
3918 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3919 }
3920 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003921 }
drhd9e5c4f2010-05-12 18:01:39 +00003922 }
3923
drhd91c68f2010-05-14 14:52:25 +00003924 /* Make the new connection a child of the unixShmNode */
3925 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003926#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003927 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003928#endif
drhd91c68f2010-05-14 14:52:25 +00003929 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003930 pDbFd->pShm = p;
3931 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003932
3933 /* The reference count on pShmNode has already been incremented under
3934 ** the cover of the unixEnterMutex() mutex and the pointer from the
3935 ** new (struct unixShm) object to the pShmNode has been set. All that is
3936 ** left to do is to link the new object into the linked list starting
3937 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3938 ** mutex.
3939 */
3940 sqlite3_mutex_enter(pShmNode->mutex);
3941 p->pNext = pShmNode->pFirst;
3942 pShmNode->pFirst = p;
3943 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003944 return SQLITE_OK;
3945
3946 /* Jump here on any error */
3947shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003948 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003949 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003950 unixLeaveMutex();
3951 return rc;
3952}
3953
3954/*
danda9fe0c2010-07-13 18:44:03 +00003955** This function is called to obtain a pointer to region iRegion of the
3956** shared-memory associated with the database file fd. Shared-memory regions
3957** are numbered starting from zero. Each shared-memory region is szRegion
3958** bytes in size.
3959**
3960** If an error occurs, an error code is returned and *pp is set to NULL.
3961**
3962** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3963** region has not been allocated (by any client, including one running in a
3964** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3965** bExtend is non-zero and the requested shared-memory region has not yet
3966** been allocated, it is allocated by this function.
3967**
3968** If the shared-memory region has already been allocated or is allocated by
3969** this call as described above, then it is mapped into this processes
3970** address space (if it is not already), *pp is set to point to the mapped
3971** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003972*/
danda9fe0c2010-07-13 18:44:03 +00003973static int unixShmMap(
3974 sqlite3_file *fd, /* Handle open on database file */
3975 int iRegion, /* Region to retrieve */
3976 int szRegion, /* Size of regions */
3977 int bExtend, /* True to extend file if necessary */
3978 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003979){
danda9fe0c2010-07-13 18:44:03 +00003980 unixFile *pDbFd = (unixFile*)fd;
3981 unixShm *p;
3982 unixShmNode *pShmNode;
3983 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003984
danda9fe0c2010-07-13 18:44:03 +00003985 /* If the shared-memory file has not yet been opened, open it now. */
3986 if( pDbFd->pShm==0 ){
3987 rc = unixOpenSharedMemory(pDbFd);
3988 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003989 }
drhd9e5c4f2010-05-12 18:01:39 +00003990
danda9fe0c2010-07-13 18:44:03 +00003991 p = pDbFd->pShm;
3992 pShmNode = p->pShmNode;
3993 sqlite3_mutex_enter(pShmNode->mutex);
3994 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003995 assert( pShmNode->pInode==pDbFd->pInode );
3996 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3997 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003998
3999 if( pShmNode->nRegion<=iRegion ){
4000 char **apNew; /* New apRegion[] array */
4001 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4002 struct stat sStat; /* Used by fstat() */
4003
4004 pShmNode->szRegion = szRegion;
4005
drh3cb93392011-03-12 18:10:44 +00004006 if( pShmNode->h>=0 ){
4007 /* The requested region is not mapped into this processes address space.
4008 ** Check to see if it has been allocated (i.e. if the wal-index file is
4009 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004010 */
drh3cb93392011-03-12 18:10:44 +00004011 if( osFstat(pShmNode->h, &sStat) ){
4012 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004013 goto shmpage_out;
4014 }
drh3cb93392011-03-12 18:10:44 +00004015
4016 if( sStat.st_size<nByte ){
4017 /* The requested memory region does not exist. If bExtend is set to
4018 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4019 **
4020 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4021 ** the requested memory region.
4022 */
4023 if( !bExtend ) goto shmpage_out;
4024 if( robust_ftruncate(pShmNode->h, nByte) ){
4025 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4026 pShmNode->zFilename);
4027 goto shmpage_out;
4028 }
4029 }
danda9fe0c2010-07-13 18:44:03 +00004030 }
4031
4032 /* Map the requested memory region into this processes address space. */
4033 apNew = (char **)sqlite3_realloc(
4034 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4035 );
4036 if( !apNew ){
4037 rc = SQLITE_IOERR_NOMEM;
4038 goto shmpage_out;
4039 }
4040 pShmNode->apRegion = apNew;
4041 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004042 void *pMem;
4043 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004044 pMem = mmap(0, szRegion,
4045 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004046 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4047 );
4048 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004049 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004050 goto shmpage_out;
4051 }
4052 }else{
4053 pMem = sqlite3_malloc(szRegion);
4054 if( pMem==0 ){
4055 rc = SQLITE_NOMEM;
4056 goto shmpage_out;
4057 }
4058 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004059 }
4060 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4061 pShmNode->nRegion++;
4062 }
4063 }
4064
4065shmpage_out:
4066 if( pShmNode->nRegion>iRegion ){
4067 *pp = pShmNode->apRegion[iRegion];
4068 }else{
4069 *pp = 0;
4070 }
drh66dfec8b2011-06-01 20:01:49 +00004071 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004072 sqlite3_mutex_leave(pShmNode->mutex);
4073 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004074}
4075
4076/*
drhd9e5c4f2010-05-12 18:01:39 +00004077** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004078**
4079** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4080** different here than in posix. In xShmLock(), one can go from unlocked
4081** to shared and back or from unlocked to exclusive and back. But one may
4082** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004083*/
4084static int unixShmLock(
4085 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004086 int ofst, /* First lock to acquire or release */
4087 int n, /* Number of locks to acquire or release */
4088 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004089){
drh73b64e42010-05-30 19:55:15 +00004090 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4091 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4092 unixShm *pX; /* For looping over all siblings */
4093 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4094 int rc = SQLITE_OK; /* Result code */
4095 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004096
drhd91c68f2010-05-14 14:52:25 +00004097 assert( pShmNode==pDbFd->pInode->pShmNode );
4098 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004099 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004100 assert( n>=1 );
4101 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4102 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4103 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4104 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4105 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004106 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4107 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004108
drhc99597c2010-05-31 01:41:15 +00004109 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004110 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004111 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004112 if( flags & SQLITE_SHM_UNLOCK ){
4113 u16 allMask = 0; /* Mask of locks held by siblings */
4114
4115 /* See if any siblings hold this same lock */
4116 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4117 if( pX==p ) continue;
4118 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4119 allMask |= pX->sharedMask;
4120 }
4121
4122 /* Unlock the system-level locks */
4123 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004124 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004125 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004126 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004127 }
drh73b64e42010-05-30 19:55:15 +00004128
4129 /* Undo the local locks */
4130 if( rc==SQLITE_OK ){
4131 p->exclMask &= ~mask;
4132 p->sharedMask &= ~mask;
4133 }
4134 }else if( flags & SQLITE_SHM_SHARED ){
4135 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4136
4137 /* Find out which shared locks are already held by sibling connections.
4138 ** If any sibling already holds an exclusive lock, go ahead and return
4139 ** SQLITE_BUSY.
4140 */
4141 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004142 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004143 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004144 break;
4145 }
4146 allShared |= pX->sharedMask;
4147 }
4148
4149 /* Get shared locks at the system level, if necessary */
4150 if( rc==SQLITE_OK ){
4151 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004152 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004153 }else{
drh73b64e42010-05-30 19:55:15 +00004154 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004155 }
drhd9e5c4f2010-05-12 18:01:39 +00004156 }
drh73b64e42010-05-30 19:55:15 +00004157
4158 /* Get the local shared locks */
4159 if( rc==SQLITE_OK ){
4160 p->sharedMask |= mask;
4161 }
4162 }else{
4163 /* Make sure no sibling connections hold locks that will block this
4164 ** lock. If any do, return SQLITE_BUSY right away.
4165 */
4166 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004167 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4168 rc = SQLITE_BUSY;
4169 break;
4170 }
4171 }
4172
4173 /* Get the exclusive locks at the system level. Then if successful
4174 ** also mark the local connection as being locked.
4175 */
4176 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004177 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004178 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004179 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004180 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004181 }
drhd9e5c4f2010-05-12 18:01:39 +00004182 }
4183 }
drhd91c68f2010-05-14 14:52:25 +00004184 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004185 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4186 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004187 return rc;
4188}
4189
drh286a2882010-05-20 23:51:06 +00004190/*
4191** Implement a memory barrier or memory fence on shared memory.
4192**
4193** All loads and stores begun before the barrier must complete before
4194** any load or store begun after the barrier.
4195*/
4196static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004197 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004198){
drhff828942010-06-26 21:34:06 +00004199 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004200 unixEnterMutex();
4201 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004202}
4203
dan18801912010-06-14 14:07:50 +00004204/*
danda9fe0c2010-07-13 18:44:03 +00004205** Close a connection to shared-memory. Delete the underlying
4206** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004207**
4208** If there is no shared memory associated with the connection then this
4209** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004210*/
danda9fe0c2010-07-13 18:44:03 +00004211static int unixShmUnmap(
4212 sqlite3_file *fd, /* The underlying database file */
4213 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004214){
danda9fe0c2010-07-13 18:44:03 +00004215 unixShm *p; /* The connection to be closed */
4216 unixShmNode *pShmNode; /* The underlying shared-memory file */
4217 unixShm **pp; /* For looping over sibling connections */
4218 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004219
danda9fe0c2010-07-13 18:44:03 +00004220 pDbFd = (unixFile*)fd;
4221 p = pDbFd->pShm;
4222 if( p==0 ) return SQLITE_OK;
4223 pShmNode = p->pShmNode;
4224
4225 assert( pShmNode==pDbFd->pInode->pShmNode );
4226 assert( pShmNode->pInode==pDbFd->pInode );
4227
4228 /* Remove connection p from the set of connections associated
4229 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004230 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004231 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4232 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004233
danda9fe0c2010-07-13 18:44:03 +00004234 /* Free the connection p */
4235 sqlite3_free(p);
4236 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004237 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004238
4239 /* If pShmNode->nRef has reached 0, then close the underlying
4240 ** shared-memory file, too */
4241 unixEnterMutex();
4242 assert( pShmNode->nRef>0 );
4243 pShmNode->nRef--;
4244 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004245 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004246 unixShmPurge(pDbFd);
4247 }
4248 unixLeaveMutex();
4249
4250 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004251}
drh286a2882010-05-20 23:51:06 +00004252
danda9fe0c2010-07-13 18:44:03 +00004253
drhd9e5c4f2010-05-12 18:01:39 +00004254#else
drh6b017cc2010-06-14 18:01:46 +00004255# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004256# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004257# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004258# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004259#endif /* #ifndef SQLITE_OMIT_WAL */
4260
drh734c9862008-11-28 15:37:20 +00004261/*
4262** Here ends the implementation of all sqlite3_file methods.
4263**
4264********************** End sqlite3_file Methods *******************************
4265******************************************************************************/
4266
4267/*
drh6b9d6dd2008-12-03 19:34:47 +00004268** This division contains definitions of sqlite3_io_methods objects that
4269** implement various file locking strategies. It also contains definitions
4270** of "finder" functions. A finder-function is used to locate the appropriate
4271** sqlite3_io_methods object for a particular database file. The pAppData
4272** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4273** the correct finder-function for that VFS.
4274**
4275** Most finder functions return a pointer to a fixed sqlite3_io_methods
4276** object. The only interesting finder-function is autolockIoFinder, which
4277** looks at the filesystem type and tries to guess the best locking
4278** strategy from that.
4279**
drh1875f7a2008-12-08 18:19:17 +00004280** For finder-funtion F, two objects are created:
4281**
4282** (1) The real finder-function named "FImpt()".
4283**
dane946c392009-08-22 11:39:46 +00004284** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004285**
4286**
4287** A pointer to the F pointer is used as the pAppData value for VFS
4288** objects. We have to do this instead of letting pAppData point
4289** directly at the finder-function since C90 rules prevent a void*
4290** from be cast into a function pointer.
4291**
drh6b9d6dd2008-12-03 19:34:47 +00004292**
drh7708e972008-11-29 00:56:52 +00004293** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004294**
drh7708e972008-11-29 00:56:52 +00004295** * A constant sqlite3_io_methods object call METHOD that has locking
4296** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4297**
4298** * An I/O method finder function called FINDER that returns a pointer
4299** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004300*/
drhd9e5c4f2010-05-12 18:01:39 +00004301#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004302static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004303 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004304 CLOSE, /* xClose */ \
4305 unixRead, /* xRead */ \
4306 unixWrite, /* xWrite */ \
4307 unixTruncate, /* xTruncate */ \
4308 unixSync, /* xSync */ \
4309 unixFileSize, /* xFileSize */ \
4310 LOCK, /* xLock */ \
4311 UNLOCK, /* xUnlock */ \
4312 CKLOCK, /* xCheckReservedLock */ \
4313 unixFileControl, /* xFileControl */ \
4314 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004315 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004316 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004317 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004318 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004319 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004320}; \
drh0c2694b2009-09-03 16:23:44 +00004321static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4322 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004323 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004324} \
drh0c2694b2009-09-03 16:23:44 +00004325static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004326 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004327
4328/*
4329** Here are all of the sqlite3_io_methods objects for each of the
4330** locking strategies. Functions that return pointers to these methods
4331** are also created.
4332*/
4333IOMETHODS(
4334 posixIoFinder, /* Finder function name */
4335 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004336 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004337 unixClose, /* xClose method */
4338 unixLock, /* xLock method */
4339 unixUnlock, /* xUnlock method */
4340 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004341)
drh7708e972008-11-29 00:56:52 +00004342IOMETHODS(
4343 nolockIoFinder, /* Finder function name */
4344 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004345 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004346 nolockClose, /* xClose method */
4347 nolockLock, /* xLock method */
4348 nolockUnlock, /* xUnlock method */
4349 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004350)
drh7708e972008-11-29 00:56:52 +00004351IOMETHODS(
4352 dotlockIoFinder, /* Finder function name */
4353 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004354 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004355 dotlockClose, /* xClose method */
4356 dotlockLock, /* xLock method */
4357 dotlockUnlock, /* xUnlock method */
4358 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004359)
drh7708e972008-11-29 00:56:52 +00004360
chw78a13182009-04-07 05:35:03 +00004361#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004362IOMETHODS(
4363 flockIoFinder, /* Finder function name */
4364 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004365 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004366 flockClose, /* xClose method */
4367 flockLock, /* xLock method */
4368 flockUnlock, /* xUnlock method */
4369 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004370)
drh7708e972008-11-29 00:56:52 +00004371#endif
4372
drh6c7d5c52008-11-21 20:32:33 +00004373#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004374IOMETHODS(
4375 semIoFinder, /* Finder function name */
4376 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004377 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004378 semClose, /* xClose method */
4379 semLock, /* xLock method */
4380 semUnlock, /* xUnlock method */
4381 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004382)
aswiftaebf4132008-11-21 00:10:35 +00004383#endif
drh7708e972008-11-29 00:56:52 +00004384
drhd2cb50b2009-01-09 21:41:17 +00004385#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004386IOMETHODS(
4387 afpIoFinder, /* Finder function name */
4388 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004389 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004390 afpClose, /* xClose method */
4391 afpLock, /* xLock method */
4392 afpUnlock, /* xUnlock method */
4393 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004394)
drh715ff302008-12-03 22:32:44 +00004395#endif
4396
4397/*
4398** The proxy locking method is a "super-method" in the sense that it
4399** opens secondary file descriptors for the conch and lock files and
4400** it uses proxy, dot-file, AFP, and flock() locking methods on those
4401** secondary files. For this reason, the division that implements
4402** proxy locking is located much further down in the file. But we need
4403** to go ahead and define the sqlite3_io_methods and finder function
4404** for proxy locking here. So we forward declare the I/O methods.
4405*/
drhd2cb50b2009-01-09 21:41:17 +00004406#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004407static int proxyClose(sqlite3_file*);
4408static int proxyLock(sqlite3_file*, int);
4409static int proxyUnlock(sqlite3_file*, int);
4410static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004411IOMETHODS(
4412 proxyIoFinder, /* Finder function name */
4413 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004414 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004415 proxyClose, /* xClose method */
4416 proxyLock, /* xLock method */
4417 proxyUnlock, /* xUnlock method */
4418 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004419)
aswiftaebf4132008-11-21 00:10:35 +00004420#endif
drh7708e972008-11-29 00:56:52 +00004421
drh7ed97b92010-01-20 13:07:21 +00004422/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4423#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4424IOMETHODS(
4425 nfsIoFinder, /* Finder function name */
4426 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004427 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004428 unixClose, /* xClose method */
4429 unixLock, /* xLock method */
4430 nfsUnlock, /* xUnlock method */
4431 unixCheckReservedLock /* xCheckReservedLock method */
4432)
4433#endif
drh7708e972008-11-29 00:56:52 +00004434
drhd2cb50b2009-01-09 21:41:17 +00004435#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004436/*
drh6b9d6dd2008-12-03 19:34:47 +00004437** This "finder" function attempts to determine the best locking strategy
4438** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004439** object that implements that strategy.
4440**
4441** This is for MacOSX only.
4442*/
drh1875f7a2008-12-08 18:19:17 +00004443static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004444 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004445 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004446){
4447 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004448 const char *zFilesystem; /* Filesystem type name */
4449 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004450 } aMap[] = {
4451 { "hfs", &posixIoMethods },
4452 { "ufs", &posixIoMethods },
4453 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004454 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004455 { "webdav", &nolockIoMethods },
4456 { 0, 0 }
4457 };
4458 int i;
4459 struct statfs fsInfo;
4460 struct flock lockInfo;
4461
4462 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004463 /* If filePath==NULL that means we are dealing with a transient file
4464 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004465 return &nolockIoMethods;
4466 }
4467 if( statfs(filePath, &fsInfo) != -1 ){
4468 if( fsInfo.f_flags & MNT_RDONLY ){
4469 return &nolockIoMethods;
4470 }
4471 for(i=0; aMap[i].zFilesystem; i++){
4472 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4473 return aMap[i].pMethods;
4474 }
4475 }
4476 }
4477
4478 /* Default case. Handles, amongst others, "nfs".
4479 ** Test byte-range lock using fcntl(). If the call succeeds,
4480 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004481 */
drh7708e972008-11-29 00:56:52 +00004482 lockInfo.l_len = 1;
4483 lockInfo.l_start = 0;
4484 lockInfo.l_whence = SEEK_SET;
4485 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004486 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004487 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4488 return &nfsIoMethods;
4489 } else {
4490 return &posixIoMethods;
4491 }
drh7708e972008-11-29 00:56:52 +00004492 }else{
4493 return &dotlockIoMethods;
4494 }
4495}
drh0c2694b2009-09-03 16:23:44 +00004496static const sqlite3_io_methods
4497 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004498
drhd2cb50b2009-01-09 21:41:17 +00004499#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004500
chw78a13182009-04-07 05:35:03 +00004501#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4502/*
4503** This "finder" function attempts to determine the best locking strategy
4504** for the database file "filePath". It then returns the sqlite3_io_methods
4505** object that implements that strategy.
4506**
4507** This is for VXWorks only.
4508*/
4509static const sqlite3_io_methods *autolockIoFinderImpl(
4510 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004511 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004512){
4513 struct flock lockInfo;
4514
4515 if( !filePath ){
4516 /* If filePath==NULL that means we are dealing with a transient file
4517 ** that does not need to be locked. */
4518 return &nolockIoMethods;
4519 }
4520
4521 /* Test if fcntl() is supported and use POSIX style locks.
4522 ** Otherwise fall back to the named semaphore method.
4523 */
4524 lockInfo.l_len = 1;
4525 lockInfo.l_start = 0;
4526 lockInfo.l_whence = SEEK_SET;
4527 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004528 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004529 return &posixIoMethods;
4530 }else{
4531 return &semIoMethods;
4532 }
4533}
drh0c2694b2009-09-03 16:23:44 +00004534static const sqlite3_io_methods
4535 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004536
4537#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4538
drh7708e972008-11-29 00:56:52 +00004539/*
4540** An abstract type for a pointer to a IO method finder function:
4541*/
drh0c2694b2009-09-03 16:23:44 +00004542typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004543
aswiftaebf4132008-11-21 00:10:35 +00004544
drh734c9862008-11-28 15:37:20 +00004545/****************************************************************************
4546**************************** sqlite3_vfs methods ****************************
4547**
4548** This division contains the implementation of methods on the
4549** sqlite3_vfs object.
4550*/
4551
danielk1977a3d4c882007-03-23 10:08:38 +00004552/*
danielk1977e339d652008-06-28 11:23:00 +00004553** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004554*/
4555static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004556 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004557 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004558 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004559 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004560 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004561){
drh7708e972008-11-29 00:56:52 +00004562 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004563 unixFile *pNew = (unixFile *)pId;
4564 int rc = SQLITE_OK;
4565
drh8af6c222010-05-14 12:43:01 +00004566 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004567
dan00157392010-10-05 11:33:15 +00004568 /* Usually the path zFilename should not be a relative pathname. The
4569 ** exception is when opening the proxy "conch" file in builds that
4570 ** include the special Apple locking styles.
4571 */
dan00157392010-10-05 11:33:15 +00004572#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004573 assert( zFilename==0 || zFilename[0]=='/'
4574 || pVfs->pAppData==(void*)&autolockIoFinder );
4575#else
4576 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004577#endif
dan00157392010-10-05 11:33:15 +00004578
drhb07028f2011-10-14 21:49:18 +00004579 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004580 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004581
drh308c2a52010-05-14 11:30:18 +00004582 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004583 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004584 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004585 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004586 pNew->ctrlFlags = (u8)ctrlFlags;
4587 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4588 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004589 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004590 }
drha7e61d82011-03-12 17:02:57 +00004591 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004592 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004593 }
drh339eb0b2008-03-07 15:34:11 +00004594
drh6c7d5c52008-11-21 20:32:33 +00004595#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004596 pNew->pId = vxworksFindFileId(zFilename);
4597 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004598 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004599 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004600 }
4601#endif
4602
drhc02a43a2012-01-10 23:18:38 +00004603 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004604 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004605 }else{
drh0c2694b2009-09-03 16:23:44 +00004606 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004607#if SQLITE_ENABLE_LOCKING_STYLE
4608 /* Cache zFilename in the locking context (AFP and dotlock override) for
4609 ** proxyLock activation is possible (remote proxy is based on db name)
4610 ** zFilename remains valid until file is closed, to support */
4611 pNew->lockingContext = (void*)zFilename;
4612#endif
drhda0e7682008-07-30 15:27:54 +00004613 }
danielk1977e339d652008-06-28 11:23:00 +00004614
drh7ed97b92010-01-20 13:07:21 +00004615 if( pLockingStyle == &posixIoMethods
4616#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4617 || pLockingStyle == &nfsIoMethods
4618#endif
4619 ){
drh7708e972008-11-29 00:56:52 +00004620 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004621 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004622 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004623 /* If an error occured in findInodeInfo(), close the file descriptor
4624 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004625 ** in two scenarios:
4626 **
4627 ** (a) A call to fstat() failed.
4628 ** (b) A malloc failed.
4629 **
4630 ** Scenario (b) may only occur if the process is holding no other
4631 ** file descriptors open on the same file. If there were other file
4632 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004633 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004634 ** handle h - as it is guaranteed that no posix locks will be released
4635 ** by doing so.
4636 **
4637 ** If scenario (a) caused the error then things are not so safe. The
4638 ** implicit assumption here is that if fstat() fails, things are in
4639 ** such bad shape that dropping a lock or two doesn't matter much.
4640 */
drh0e9365c2011-03-02 02:08:13 +00004641 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004642 h = -1;
4643 }
drh7708e972008-11-29 00:56:52 +00004644 unixLeaveMutex();
4645 }
danielk1977e339d652008-06-28 11:23:00 +00004646
drhd2cb50b2009-01-09 21:41:17 +00004647#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004648 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004649 /* AFP locking uses the file path so it needs to be included in
4650 ** the afpLockingContext.
4651 */
4652 afpLockingContext *pCtx;
4653 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4654 if( pCtx==0 ){
4655 rc = SQLITE_NOMEM;
4656 }else{
4657 /* NB: zFilename exists and remains valid until the file is closed
4658 ** according to requirement F11141. So we do not need to make a
4659 ** copy of the filename. */
4660 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004661 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004662 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004663 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004664 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004665 if( rc!=SQLITE_OK ){
4666 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004667 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004668 h = -1;
4669 }
drh7708e972008-11-29 00:56:52 +00004670 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004671 }
drh7708e972008-11-29 00:56:52 +00004672 }
4673#endif
danielk1977e339d652008-06-28 11:23:00 +00004674
drh7708e972008-11-29 00:56:52 +00004675 else if( pLockingStyle == &dotlockIoMethods ){
4676 /* Dotfile locking uses the file path so it needs to be included in
4677 ** the dotlockLockingContext
4678 */
4679 char *zLockFile;
4680 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004681 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004682 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004683 zLockFile = (char *)sqlite3_malloc(nFilename);
4684 if( zLockFile==0 ){
4685 rc = SQLITE_NOMEM;
4686 }else{
4687 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004688 }
drh7708e972008-11-29 00:56:52 +00004689 pNew->lockingContext = zLockFile;
4690 }
danielk1977e339d652008-06-28 11:23:00 +00004691
drh6c7d5c52008-11-21 20:32:33 +00004692#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004693 else if( pLockingStyle == &semIoMethods ){
4694 /* Named semaphore locking uses the file path so it needs to be
4695 ** included in the semLockingContext
4696 */
4697 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004698 rc = findInodeInfo(pNew, &pNew->pInode);
4699 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4700 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004701 int n;
drh2238dcc2009-08-27 17:56:20 +00004702 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004703 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004704 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004705 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004706 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4707 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004708 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004709 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004710 }
chw97185482008-11-17 08:05:31 +00004711 }
drh7708e972008-11-29 00:56:52 +00004712 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004713 }
drh7708e972008-11-29 00:56:52 +00004714#endif
aswift5b1a2562008-08-22 00:22:35 +00004715
4716 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004717#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004718 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004719 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004720 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004721 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004722 isDelete = 0;
4723 }
drhc02a43a2012-01-10 23:18:38 +00004724 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004725#endif
danielk1977e339d652008-06-28 11:23:00 +00004726 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004727 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004728 }else{
drh7708e972008-11-29 00:56:52 +00004729 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004730 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004731 }
danielk1977e339d652008-06-28 11:23:00 +00004732 return rc;
drh054889e2005-11-30 03:20:31 +00004733}
drh9c06c952005-11-26 00:25:00 +00004734
danielk1977ad94b582007-08-20 06:44:22 +00004735/*
drh8b3cf822010-06-01 21:02:51 +00004736** Return the name of a directory in which to put temporary files.
4737** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004738*/
drh7234c6d2010-06-19 15:10:09 +00004739static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004740 static const char *azDirs[] = {
4741 0,
aswiftaebf4132008-11-21 00:10:35 +00004742 0,
danielk197717b90b52008-06-06 11:11:25 +00004743 "/var/tmp",
4744 "/usr/tmp",
4745 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004746 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004747 };
drh8b3cf822010-06-01 21:02:51 +00004748 unsigned int i;
4749 struct stat buf;
4750 const char *zDir = 0;
4751
4752 azDirs[0] = sqlite3_temp_directory;
4753 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004754 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004755 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004756 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004757 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004758 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004759 break;
4760 }
4761 return zDir;
4762}
4763
4764/*
4765** Create a temporary file name in zBuf. zBuf must be allocated
4766** by the calling process and must be big enough to hold at least
4767** pVfs->mxPathname bytes.
4768*/
4769static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004770 static const unsigned char zChars[] =
4771 "abcdefghijklmnopqrstuvwxyz"
4772 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4773 "0123456789";
drh41022642008-11-21 00:24:42 +00004774 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004775 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004776
4777 /* It's odd to simulate an io-error here, but really this is just
4778 ** using the io-error infrastructure to test that SQLite handles this
4779 ** function failing.
4780 */
4781 SimulateIOError( return SQLITE_IOERR );
4782
drh7234c6d2010-06-19 15:10:09 +00004783 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004784 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004785
4786 /* Check that the output buffer is large enough for the temporary file
4787 ** name. If it is not, return SQLITE_ERROR.
4788 */
drhc02a43a2012-01-10 23:18:38 +00004789 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004790 return SQLITE_ERROR;
4791 }
4792
4793 do{
drhc02a43a2012-01-10 23:18:38 +00004794 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004795 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004796 sqlite3_randomness(15, &zBuf[j]);
4797 for(i=0; i<15; i++, j++){
4798 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4799 }
4800 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00004801 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00004802 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004803 return SQLITE_OK;
4804}
4805
drhd2cb50b2009-01-09 21:41:17 +00004806#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004807/*
4808** Routine to transform a unixFile into a proxy-locking unixFile.
4809** Implementation in the proxy-lock division, but used by unixOpen()
4810** if SQLITE_PREFER_PROXY_LOCKING is defined.
4811*/
4812static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004813#endif
drhc66d5b62008-12-03 22:48:32 +00004814
dan08da86a2009-08-21 17:18:03 +00004815/*
4816** Search for an unused file descriptor that was opened on the database
4817** file (not a journal or master-journal file) identified by pathname
4818** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4819** argument to this function.
4820**
4821** Such a file descriptor may exist if a database connection was closed
4822** but the associated file descriptor could not be closed because some
4823** other file descriptor open on the same file is holding a file-lock.
4824** Refer to comments in the unixClose() function and the lengthy comment
4825** describing "Posix Advisory Locking" at the start of this file for
4826** further details. Also, ticket #4018.
4827**
4828** If a suitable file descriptor is found, then it is returned. If no
4829** such file descriptor is located, -1 is returned.
4830*/
dane946c392009-08-22 11:39:46 +00004831static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4832 UnixUnusedFd *pUnused = 0;
4833
4834 /* Do not search for an unused file descriptor on vxworks. Not because
4835 ** vxworks would not benefit from the change (it might, we're not sure),
4836 ** but because no way to test it is currently available. It is better
4837 ** not to risk breaking vxworks support for the sake of such an obscure
4838 ** feature. */
4839#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004840 struct stat sStat; /* Results of stat() call */
4841
4842 /* A stat() call may fail for various reasons. If this happens, it is
4843 ** almost certain that an open() call on the same path will also fail.
4844 ** For this reason, if an error occurs in the stat() call here, it is
4845 ** ignored and -1 is returned. The caller will try to open a new file
4846 ** descriptor on the same path, fail, and return an error to SQLite.
4847 **
4848 ** Even if a subsequent open() call does succeed, the consequences of
4849 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004850 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004851 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004852
4853 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004854 pInode = inodeList;
4855 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4856 || pInode->fileId.ino!=sStat.st_ino) ){
4857 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004858 }
drh8af6c222010-05-14 12:43:01 +00004859 if( pInode ){
dane946c392009-08-22 11:39:46 +00004860 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004861 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004862 pUnused = *pp;
4863 if( pUnused ){
4864 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004865 }
4866 }
4867 unixLeaveMutex();
4868 }
dane946c392009-08-22 11:39:46 +00004869#endif /* if !OS_VXWORKS */
4870 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004871}
danielk197717b90b52008-06-06 11:11:25 +00004872
4873/*
danddb0ac42010-07-14 14:48:58 +00004874** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004875** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004876** and a value suitable for passing as the third argument to open(2) is
4877** written to *pMode. If an IO error occurs, an SQLite error code is
4878** returned and the value of *pMode is not modified.
4879**
4880** If the file being opened is a temporary file, it is always created with
4881** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004882** is a database or master journal file, it is created with the permissions
4883** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004884**
drh8ab58662010-07-15 18:38:39 +00004885** Finally, if the file being opened is a WAL or regular journal file, then
4886** this function queries the file-system for the permissions on the
4887** corresponding database file and sets *pMode to this value. Whenever
4888** possible, WAL and journal files are created using the same permissions
4889** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004890**
4891** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4892** original filename is unavailable. But 8_3_NAMES is only used for
4893** FAT filesystems and permissions do not matter there, so just use
4894** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004895*/
4896static int findCreateFileMode(
4897 const char *zPath, /* Path of file (possibly) being created */
4898 int flags, /* Flags passed as 4th argument to xOpen() */
4899 mode_t *pMode /* OUT: Permissions to open file with */
4900){
4901 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004902 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004903 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004904 char zDb[MAX_PATHNAME+1]; /* Database file path */
4905 int nDb; /* Number of valid bytes in zDb */
4906 struct stat sStat; /* Output of stat() on database file */
4907
dana0c989d2010-11-05 18:07:37 +00004908 /* zPath is a path to a WAL or journal file. The following block derives
4909 ** the path to the associated database file from zPath. This block handles
4910 ** the following naming conventions:
4911 **
4912 ** "<path to db>-journal"
4913 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004914 ** "<path to db>-journalNN"
4915 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004916 **
drhd337c5b2011-10-20 18:23:35 +00004917 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004918 ** used by the test_multiplex.c module.
4919 */
4920 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004921#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004922 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004923 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004924#else
4925 while( zPath[nDb]!='-' ){
4926 assert( nDb>0 );
4927 assert( zPath[nDb]!='\n' );
4928 nDb--;
4929 }
4930#endif
danddb0ac42010-07-14 14:48:58 +00004931 memcpy(zDb, zPath, nDb);
4932 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004933
drh58384f12011-07-28 00:14:45 +00004934 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004935 *pMode = sStat.st_mode & 0777;
4936 }else{
4937 rc = SQLITE_IOERR_FSTAT;
4938 }
4939 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4940 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004941 }
4942 return rc;
4943}
4944
4945/*
danielk1977ad94b582007-08-20 06:44:22 +00004946** Open the file zPath.
4947**
danielk1977b4b47412007-08-17 15:53:36 +00004948** Previously, the SQLite OS layer used three functions in place of this
4949** one:
4950**
4951** sqlite3OsOpenReadWrite();
4952** sqlite3OsOpenReadOnly();
4953** sqlite3OsOpenExclusive();
4954**
4955** These calls correspond to the following combinations of flags:
4956**
4957** ReadWrite() -> (READWRITE | CREATE)
4958** ReadOnly() -> (READONLY)
4959** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4960**
4961** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4962** true, the file was configured to be automatically deleted when the
4963** file handle closed. To achieve the same effect using this new
4964** interface, add the DELETEONCLOSE flag to those specified above for
4965** OpenExclusive().
4966*/
4967static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004968 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4969 const char *zPath, /* Pathname of file to be opened */
4970 sqlite3_file *pFile, /* The file descriptor to be filled in */
4971 int flags, /* Input flags to control the opening */
4972 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004973){
dan08da86a2009-08-21 17:18:03 +00004974 unixFile *p = (unixFile *)pFile;
4975 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004976 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004977 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004978 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004979 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00004980 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00004981
4982 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4983 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4984 int isCreate = (flags & SQLITE_OPEN_CREATE);
4985 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4986 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004987#if SQLITE_ENABLE_LOCKING_STYLE
4988 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4989#endif
drh3d4435b2011-08-26 20:55:50 +00004990#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4991 struct statfs fsInfo;
4992#endif
danielk1977b4b47412007-08-17 15:53:36 +00004993
danielk1977fee2d252007-08-18 10:59:19 +00004994 /* If creating a master or main-file journal, this function will open
4995 ** a file-descriptor on the directory too. The first time unixSync()
4996 ** is called the directory file descriptor will be fsync()ed and close()d.
4997 */
drh0059eae2011-08-08 23:48:40 +00004998 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00004999 eType==SQLITE_OPEN_MASTER_JOURNAL
5000 || eType==SQLITE_OPEN_MAIN_JOURNAL
5001 || eType==SQLITE_OPEN_WAL
5002 ));
danielk1977fee2d252007-08-18 10:59:19 +00005003
danielk197717b90b52008-06-06 11:11:25 +00005004 /* If argument zPath is a NULL pointer, this function is required to open
5005 ** a temporary file. Use this buffer to store the file name in.
5006 */
drhc02a43a2012-01-10 23:18:38 +00005007 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005008 const char *zName = zPath;
5009
danielk1977fee2d252007-08-18 10:59:19 +00005010 /* Check the following statements are true:
5011 **
5012 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5013 ** (b) if CREATE is set, then READWRITE must also be set, and
5014 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005015 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005016 */
danielk1977b4b47412007-08-17 15:53:36 +00005017 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005018 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005019 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005020 assert(isDelete==0 || isCreate);
5021
danddb0ac42010-07-14 14:48:58 +00005022 /* The main DB, main journal, WAL file and master journal are never
5023 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005024 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5025 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5026 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005027 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005028
danielk1977fee2d252007-08-18 10:59:19 +00005029 /* Assert that the upper layer has set one of the "file-type" flags. */
5030 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5031 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5032 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005033 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005034 );
5035
dan08da86a2009-08-21 17:18:03 +00005036 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005037
dan08da86a2009-08-21 17:18:03 +00005038 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005039 UnixUnusedFd *pUnused;
5040 pUnused = findReusableFd(zName, flags);
5041 if( pUnused ){
5042 fd = pUnused->fd;
5043 }else{
dan6aa657f2009-08-24 18:57:58 +00005044 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005045 if( !pUnused ){
5046 return SQLITE_NOMEM;
5047 }
5048 }
5049 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005050
5051 /* Database filenames are double-zero terminated if they are not
5052 ** URIs with parameters. Hence, they can always be passed into
5053 ** sqlite3_uri_parameter(). */
5054 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5055
dan08da86a2009-08-21 17:18:03 +00005056 }else if( !zName ){
5057 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005058 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005059 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005060 if( rc!=SQLITE_OK ){
5061 return rc;
5062 }
5063 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005064
5065 /* Generated temporary filenames are always double-zero terminated
5066 ** for use by sqlite3_uri_parameter(). */
5067 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005068 }
5069
dan08da86a2009-08-21 17:18:03 +00005070 /* Determine the value of the flags parameter passed to POSIX function
5071 ** open(). These must be calculated even if open() is not called, as
5072 ** they may be stored as part of the file handle and used by the
5073 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005074 if( isReadonly ) openFlags |= O_RDONLY;
5075 if( isReadWrite ) openFlags |= O_RDWR;
5076 if( isCreate ) openFlags |= O_CREAT;
5077 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5078 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005079
danielk1977b4b47412007-08-17 15:53:36 +00005080 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005081 mode_t openMode; /* Permissions to create file with */
5082 rc = findCreateFileMode(zName, flags, &openMode);
5083 if( rc!=SQLITE_OK ){
5084 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005085 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005086 return rc;
5087 }
drhad4f1e52011-03-04 15:43:57 +00005088 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005089 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005090 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5091 /* Failed to open the file for read/write access. Try read-only. */
5092 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005093 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005094 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005095 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005096 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005097 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005098 }
5099 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005100 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005101 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005102 }
danielk1977b4b47412007-08-17 15:53:36 +00005103 }
dan08da86a2009-08-21 17:18:03 +00005104 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005105 if( pOutFlags ){
5106 *pOutFlags = flags;
5107 }
5108
dane946c392009-08-22 11:39:46 +00005109 if( p->pUnused ){
5110 p->pUnused->fd = fd;
5111 p->pUnused->flags = flags;
5112 }
5113
danielk1977b4b47412007-08-17 15:53:36 +00005114 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005115#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005116 zPath = zName;
5117#else
drh036ac7f2011-08-08 23:18:05 +00005118 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005119#endif
danielk1977b4b47412007-08-17 15:53:36 +00005120 }
drh41022642008-11-21 00:24:42 +00005121#if SQLITE_ENABLE_LOCKING_STYLE
5122 else{
dan08da86a2009-08-21 17:18:03 +00005123 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005124 }
5125#endif
5126
danielk1977e339d652008-06-28 11:23:00 +00005127#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005128 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005129#endif
5130
drhda0e7682008-07-30 15:27:54 +00005131 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005132
drh7ed97b92010-01-20 13:07:21 +00005133
5134#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005135 if( fstatfs(fd, &fsInfo) == -1 ){
5136 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005137 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005138 return SQLITE_IOERR_ACCESS;
5139 }
5140 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5141 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5142 }
5143#endif
drhc02a43a2012-01-10 23:18:38 +00005144
5145 /* Set up appropriate ctrlFlags */
5146 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5147 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5148 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5149 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5150 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5151
drh7ed97b92010-01-20 13:07:21 +00005152#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005153#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005154 isAutoProxy = 1;
5155#endif
5156 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005157 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5158 int useProxy = 0;
5159
dan08da86a2009-08-21 17:18:03 +00005160 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5161 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005162 if( envforce!=NULL ){
5163 useProxy = atoi(envforce)>0;
5164 }else{
aswiftaebf4132008-11-21 00:10:35 +00005165 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005166 /* In theory, the close(fd) call is sub-optimal. If the file opened
5167 ** with fd is a database file, and there are other connections open
5168 ** on that file that are currently holding advisory locks on it,
5169 ** then the call to close() will cancel those locks. In practice,
5170 ** we're assuming that statfs() doesn't fail very often. At least
5171 ** not while other file descriptors opened by the same process on
5172 ** the same file are working. */
5173 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005174 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005175 rc = SQLITE_IOERR_ACCESS;
5176 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005177 }
5178 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5179 }
5180 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005181 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005182 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005183 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005184 if( rc!=SQLITE_OK ){
5185 /* Use unixClose to clean up the resources added in fillInUnixFile
5186 ** and clear all the structure's references. Specifically,
5187 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5188 */
5189 unixClose(pFile);
5190 return rc;
5191 }
aswiftaebf4132008-11-21 00:10:35 +00005192 }
dane946c392009-08-22 11:39:46 +00005193 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005194 }
5195 }
5196#endif
5197
drhc02a43a2012-01-10 23:18:38 +00005198 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5199
dane946c392009-08-22 11:39:46 +00005200open_finished:
5201 if( rc!=SQLITE_OK ){
5202 sqlite3_free(p->pUnused);
5203 }
5204 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005205}
5206
dane946c392009-08-22 11:39:46 +00005207
danielk1977b4b47412007-08-17 15:53:36 +00005208/*
danielk1977fee2d252007-08-18 10:59:19 +00005209** Delete the file at zPath. If the dirSync argument is true, fsync()
5210** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005211*/
drh6b9d6dd2008-12-03 19:34:47 +00005212static int unixDelete(
5213 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5214 const char *zPath, /* Name of file to be deleted */
5215 int dirSync /* If true, fsync() directory after deleting file */
5216){
danielk1977fee2d252007-08-18 10:59:19 +00005217 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005218 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005219 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005220 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005221 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005222 }
danielk1977d39fa702008-10-16 13:27:40 +00005223#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005224 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005225 int fd;
drh90315a22011-08-10 01:52:12 +00005226 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005227 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005228#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005229 if( fsync(fd)==-1 )
5230#else
5231 if( fsync(fd) )
5232#endif
5233 {
dane18d4952011-02-21 11:46:24 +00005234 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005235 }
drh0e9365c2011-03-02 02:08:13 +00005236 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005237 }else if( rc==SQLITE_CANTOPEN ){
5238 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005239 }
5240 }
danielk1977d138dd82008-10-15 16:02:48 +00005241#endif
danielk1977fee2d252007-08-18 10:59:19 +00005242 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005243}
5244
danielk197790949c22007-08-17 16:50:38 +00005245/*
5246** Test the existance of or access permissions of file zPath. The
5247** test performed depends on the value of flags:
5248**
5249** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5250** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5251** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5252**
5253** Otherwise return 0.
5254*/
danielk1977861f7452008-06-05 11:39:11 +00005255static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005256 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5257 const char *zPath, /* Path of the file to examine */
5258 int flags, /* What do we want to learn about the zPath file? */
5259 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005260){
rse25c0d1a2007-09-20 08:38:14 +00005261 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005262 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005263 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005264 switch( flags ){
5265 case SQLITE_ACCESS_EXISTS:
5266 amode = F_OK;
5267 break;
5268 case SQLITE_ACCESS_READWRITE:
5269 amode = W_OK|R_OK;
5270 break;
drh50d3f902007-08-27 21:10:36 +00005271 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005272 amode = R_OK;
5273 break;
5274
5275 default:
5276 assert(!"Invalid flags argument");
5277 }
drh99ab3b12011-03-02 15:09:07 +00005278 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005279 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5280 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005281 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005282 *pResOut = 0;
5283 }
5284 }
danielk1977861f7452008-06-05 11:39:11 +00005285 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005286}
5287
danielk1977b4b47412007-08-17 15:53:36 +00005288
5289/*
5290** Turn a relative pathname into a full pathname. The relative path
5291** is stored as a nul-terminated string in the buffer pointed to by
5292** zPath.
5293**
5294** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5295** (in this case, MAX_PATHNAME bytes). The full-path is written to
5296** this buffer before returning.
5297*/
danielk1977adfb9b02007-09-17 07:02:56 +00005298static int unixFullPathname(
5299 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5300 const char *zPath, /* Possibly relative input path */
5301 int nOut, /* Size of output buffer in bytes */
5302 char *zOut /* Output buffer */
5303){
danielk1977843e65f2007-09-01 16:16:15 +00005304
5305 /* It's odd to simulate an io-error here, but really this is just
5306 ** using the io-error infrastructure to test that SQLite handles this
5307 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005308 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005309 */
5310 SimulateIOError( return SQLITE_ERROR );
5311
drh153c62c2007-08-24 03:51:33 +00005312 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005313 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005314
drh3c7f2dc2007-12-06 13:26:20 +00005315 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005316 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005317 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005318 }else{
5319 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005320 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005321 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005322 }
drhea678832008-12-10 19:26:22 +00005323 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005324 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005325 }
5326 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005327}
5328
drh0ccebe72005-06-07 22:22:50 +00005329
drh761df872006-12-21 01:29:22 +00005330#ifndef SQLITE_OMIT_LOAD_EXTENSION
5331/*
5332** Interfaces for opening a shared library, finding entry points
5333** within the shared library, and closing the shared library.
5334*/
5335#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005336static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5337 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005338 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5339}
danielk197795c8a542007-09-01 06:51:27 +00005340
5341/*
5342** SQLite calls this function immediately after a call to unixDlSym() or
5343** unixDlOpen() fails (returns a null pointer). If a more detailed error
5344** message is available, it is written to zBufOut. If no error message
5345** is available, zBufOut is left unmodified and SQLite uses a default
5346** error message.
5347*/
danielk1977397d65f2008-11-19 11:35:39 +00005348static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005349 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005350 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005351 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005352 zErr = dlerror();
5353 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005354 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005355 }
drh6c7d5c52008-11-21 20:32:33 +00005356 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005357}
drh1875f7a2008-12-08 18:19:17 +00005358static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5359 /*
5360 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5361 ** cast into a pointer to a function. And yet the library dlsym() routine
5362 ** returns a void* which is really a pointer to a function. So how do we
5363 ** use dlsym() with -pedantic-errors?
5364 **
5365 ** Variable x below is defined to be a pointer to a function taking
5366 ** parameters void* and const char* and returning a pointer to a function.
5367 ** We initialize x by assigning it a pointer to the dlsym() function.
5368 ** (That assignment requires a cast.) Then we call the function that
5369 ** x points to.
5370 **
5371 ** This work-around is unlikely to work correctly on any system where
5372 ** you really cannot cast a function pointer into void*. But then, on the
5373 ** other hand, dlsym() will not work on such a system either, so we have
5374 ** not really lost anything.
5375 */
5376 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005377 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005378 x = (void(*(*)(void*,const char*))(void))dlsym;
5379 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005380}
danielk1977397d65f2008-11-19 11:35:39 +00005381static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5382 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005383 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005384}
danielk1977b4b47412007-08-17 15:53:36 +00005385#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5386 #define unixDlOpen 0
5387 #define unixDlError 0
5388 #define unixDlSym 0
5389 #define unixDlClose 0
5390#endif
5391
5392/*
danielk197790949c22007-08-17 16:50:38 +00005393** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005394*/
danielk1977397d65f2008-11-19 11:35:39 +00005395static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5396 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005397 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005398
drhbbd42a62004-05-22 17:41:58 +00005399 /* We have to initialize zBuf to prevent valgrind from reporting
5400 ** errors. The reports issued by valgrind are incorrect - we would
5401 ** prefer that the randomness be increased by making use of the
5402 ** uninitialized space in zBuf - but valgrind errors tend to worry
5403 ** some users. Rather than argue, it seems easier just to initialize
5404 ** the whole array and silence valgrind, even if that means less randomness
5405 ** in the random seed.
5406 **
5407 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005408 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005409 ** tests repeatable.
5410 */
danielk1977b4b47412007-08-17 15:53:36 +00005411 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005412#if !defined(SQLITE_TEST)
5413 {
drhc18b4042012-02-10 03:10:27 +00005414 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005415 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005416 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005417 time_t t;
5418 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005419 memcpy(zBuf, &t, sizeof(t));
5420 pid = getpid();
5421 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005422 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005423 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005424 }else{
drhc18b4042012-02-10 03:10:27 +00005425 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005426 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005427 }
drhbbd42a62004-05-22 17:41:58 +00005428 }
5429#endif
drh72cbd072008-10-14 17:58:38 +00005430 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005431}
5432
danielk1977b4b47412007-08-17 15:53:36 +00005433
drhbbd42a62004-05-22 17:41:58 +00005434/*
5435** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005436** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005437** The return value is the number of microseconds of sleep actually
5438** requested from the underlying operating system, a number which
5439** might be greater than or equal to the argument, but not less
5440** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005441*/
danielk1977397d65f2008-11-19 11:35:39 +00005442static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005443#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005444 struct timespec sp;
5445
5446 sp.tv_sec = microseconds / 1000000;
5447 sp.tv_nsec = (microseconds % 1000000) * 1000;
5448 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005449 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005450 return microseconds;
5451#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005452 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005453 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005454 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005455#else
danielk1977b4b47412007-08-17 15:53:36 +00005456 int seconds = (microseconds+999999)/1000000;
5457 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005458 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005459 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005460#endif
drh88f474a2006-01-02 20:00:12 +00005461}
5462
5463/*
drh6b9d6dd2008-12-03 19:34:47 +00005464** The following variable, if set to a non-zero value, is interpreted as
5465** the number of seconds since 1970 and is used to set the result of
5466** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005467*/
5468#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005469int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005470#endif
5471
5472/*
drhb7e8ea22010-05-03 14:32:30 +00005473** Find the current time (in Universal Coordinated Time). Write into *piNow
5474** the current time and date as a Julian Day number times 86_400_000. In
5475** other words, write into *piNow the number of milliseconds since the Julian
5476** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5477** proleptic Gregorian calendar.
5478**
drh31702252011-10-12 23:13:43 +00005479** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5480** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005481*/
5482static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5483 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005484 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005485#if defined(NO_GETTOD)
5486 time_t t;
5487 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005488 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005489#elif OS_VXWORKS
5490 struct timespec sNow;
5491 clock_gettime(CLOCK_REALTIME, &sNow);
5492 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5493#else
5494 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005495 if( gettimeofday(&sNow, 0)==0 ){
5496 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5497 }else{
5498 rc = SQLITE_ERROR;
5499 }
drhb7e8ea22010-05-03 14:32:30 +00005500#endif
5501
5502#ifdef SQLITE_TEST
5503 if( sqlite3_current_time ){
5504 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5505 }
5506#endif
5507 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005508 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005509}
5510
5511/*
drhbbd42a62004-05-22 17:41:58 +00005512** Find the current time (in Universal Coordinated Time). Write the
5513** current time and date as a Julian Day number into *prNow and
5514** return 0. Return 1 if the time and date cannot be found.
5515*/
danielk1977397d65f2008-11-19 11:35:39 +00005516static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005517 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005518 int rc;
drhff828942010-06-26 21:34:06 +00005519 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005520 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005521 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005522 return rc;
drhbbd42a62004-05-22 17:41:58 +00005523}
danielk1977b4b47412007-08-17 15:53:36 +00005524
drh6b9d6dd2008-12-03 19:34:47 +00005525/*
5526** We added the xGetLastError() method with the intention of providing
5527** better low-level error messages when operating-system problems come up
5528** during SQLite operation. But so far, none of that has been implemented
5529** in the core. So this routine is never called. For now, it is merely
5530** a place-holder.
5531*/
danielk1977397d65f2008-11-19 11:35:39 +00005532static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5533 UNUSED_PARAMETER(NotUsed);
5534 UNUSED_PARAMETER(NotUsed2);
5535 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005536 return 0;
5537}
5538
drhf2424c52010-04-26 00:04:55 +00005539
5540/*
drh734c9862008-11-28 15:37:20 +00005541************************ End of sqlite3_vfs methods ***************************
5542******************************************************************************/
5543
drh715ff302008-12-03 22:32:44 +00005544/******************************************************************************
5545************************** Begin Proxy Locking ********************************
5546**
5547** Proxy locking is a "uber-locking-method" in this sense: It uses the
5548** other locking methods on secondary lock files. Proxy locking is a
5549** meta-layer over top of the primitive locking implemented above. For
5550** this reason, the division that implements of proxy locking is deferred
5551** until late in the file (here) after all of the other I/O methods have
5552** been defined - so that the primitive locking methods are available
5553** as services to help with the implementation of proxy locking.
5554**
5555****
5556**
5557** The default locking schemes in SQLite use byte-range locks on the
5558** database file to coordinate safe, concurrent access by multiple readers
5559** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5560** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5561** as POSIX read & write locks over fixed set of locations (via fsctl),
5562** on AFP and SMB only exclusive byte-range locks are available via fsctl
5563** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5564** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5565** address in the shared range is taken for a SHARED lock, the entire
5566** shared range is taken for an EXCLUSIVE lock):
5567**
5568** PENDING_BYTE 0x40000000
5569** RESERVED_BYTE 0x40000001
5570** SHARED_RANGE 0x40000002 -> 0x40000200
5571**
5572** This works well on the local file system, but shows a nearly 100x
5573** slowdown in read performance on AFP because the AFP client disables
5574** the read cache when byte-range locks are present. Enabling the read
5575** cache exposes a cache coherency problem that is present on all OS X
5576** supported network file systems. NFS and AFP both observe the
5577** close-to-open semantics for ensuring cache coherency
5578** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5579** address the requirements for concurrent database access by multiple
5580** readers and writers
5581** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5582**
5583** To address the performance and cache coherency issues, proxy file locking
5584** changes the way database access is controlled by limiting access to a
5585** single host at a time and moving file locks off of the database file
5586** and onto a proxy file on the local file system.
5587**
5588**
5589** Using proxy locks
5590** -----------------
5591**
5592** C APIs
5593**
5594** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5595** <proxy_path> | ":auto:");
5596** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5597**
5598**
5599** SQL pragmas
5600**
5601** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5602** PRAGMA [database.]lock_proxy_file
5603**
5604** Specifying ":auto:" means that if there is a conch file with a matching
5605** host ID in it, the proxy path in the conch file will be used, otherwise
5606** a proxy path based on the user's temp dir
5607** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5608** actual proxy file name is generated from the name and path of the
5609** database file. For example:
5610**
5611** For database path "/Users/me/foo.db"
5612** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5613**
5614** Once a lock proxy is configured for a database connection, it can not
5615** be removed, however it may be switched to a different proxy path via
5616** the above APIs (assuming the conch file is not being held by another
5617** connection or process).
5618**
5619**
5620** How proxy locking works
5621** -----------------------
5622**
5623** Proxy file locking relies primarily on two new supporting files:
5624**
5625** * conch file to limit access to the database file to a single host
5626** at a time
5627**
5628** * proxy file to act as a proxy for the advisory locks normally
5629** taken on the database
5630**
5631** The conch file - to use a proxy file, sqlite must first "hold the conch"
5632** by taking an sqlite-style shared lock on the conch file, reading the
5633** contents and comparing the host's unique host ID (see below) and lock
5634** proxy path against the values stored in the conch. The conch file is
5635** stored in the same directory as the database file and the file name
5636** is patterned after the database file name as ".<databasename>-conch".
5637** If the conch file does not exist, or it's contents do not match the
5638** host ID and/or proxy path, then the lock is escalated to an exclusive
5639** lock and the conch file contents is updated with the host ID and proxy
5640** path and the lock is downgraded to a shared lock again. If the conch
5641** is held by another process (with a shared lock), the exclusive lock
5642** will fail and SQLITE_BUSY is returned.
5643**
5644** The proxy file - a single-byte file used for all advisory file locks
5645** normally taken on the database file. This allows for safe sharing
5646** of the database file for multiple readers and writers on the same
5647** host (the conch ensures that they all use the same local lock file).
5648**
drh715ff302008-12-03 22:32:44 +00005649** Requesting the lock proxy does not immediately take the conch, it is
5650** only taken when the first request to lock database file is made.
5651** This matches the semantics of the traditional locking behavior, where
5652** opening a connection to a database file does not take a lock on it.
5653** The shared lock and an open file descriptor are maintained until
5654** the connection to the database is closed.
5655**
5656** The proxy file and the lock file are never deleted so they only need
5657** to be created the first time they are used.
5658**
5659** Configuration options
5660** ---------------------
5661**
5662** SQLITE_PREFER_PROXY_LOCKING
5663**
5664** Database files accessed on non-local file systems are
5665** automatically configured for proxy locking, lock files are
5666** named automatically using the same logic as
5667** PRAGMA lock_proxy_file=":auto:"
5668**
5669** SQLITE_PROXY_DEBUG
5670**
5671** Enables the logging of error messages during host id file
5672** retrieval and creation
5673**
drh715ff302008-12-03 22:32:44 +00005674** LOCKPROXYDIR
5675**
5676** Overrides the default directory used for lock proxy files that
5677** are named automatically via the ":auto:" setting
5678**
5679** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5680**
5681** Permissions to use when creating a directory for storing the
5682** lock proxy files, only used when LOCKPROXYDIR is not set.
5683**
5684**
5685** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5686** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5687** force proxy locking to be used for every database file opened, and 0
5688** will force automatic proxy locking to be disabled for all database
5689** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5690** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5691*/
5692
5693/*
5694** Proxy locking is only available on MacOSX
5695*/
drhd2cb50b2009-01-09 21:41:17 +00005696#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005697
drh715ff302008-12-03 22:32:44 +00005698/*
5699** The proxyLockingContext has the path and file structures for the remote
5700** and local proxy files in it
5701*/
5702typedef struct proxyLockingContext proxyLockingContext;
5703struct proxyLockingContext {
5704 unixFile *conchFile; /* Open conch file */
5705 char *conchFilePath; /* Name of the conch file */
5706 unixFile *lockProxy; /* Open proxy lock file */
5707 char *lockProxyPath; /* Name of the proxy lock file */
5708 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005709 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005710 void *oldLockingContext; /* Original lockingcontext to restore on close */
5711 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5712};
5713
drh7ed97b92010-01-20 13:07:21 +00005714/*
5715** The proxy lock file path for the database at dbPath is written into lPath,
5716** which must point to valid, writable memory large enough for a maxLen length
5717** file path.
drh715ff302008-12-03 22:32:44 +00005718*/
drh715ff302008-12-03 22:32:44 +00005719static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5720 int len;
5721 int dbLen;
5722 int i;
5723
5724#ifdef LOCKPROXYDIR
5725 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5726#else
5727# ifdef _CS_DARWIN_USER_TEMP_DIR
5728 {
drh7ed97b92010-01-20 13:07:21 +00005729 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005730 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5731 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005732 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005733 }
drh7ed97b92010-01-20 13:07:21 +00005734 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005735 }
5736# else
5737 len = strlcpy(lPath, "/tmp/", maxLen);
5738# endif
5739#endif
5740
5741 if( lPath[len-1]!='/' ){
5742 len = strlcat(lPath, "/", maxLen);
5743 }
5744
5745 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005746 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005747 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005748 char c = dbPath[i];
5749 lPath[i+len] = (c=='/')?'_':c;
5750 }
5751 lPath[i+len]='\0';
5752 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005753 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005754 return SQLITE_OK;
5755}
5756
drh7ed97b92010-01-20 13:07:21 +00005757/*
5758 ** Creates the lock file and any missing directories in lockPath
5759 */
5760static int proxyCreateLockPath(const char *lockPath){
5761 int i, len;
5762 char buf[MAXPATHLEN];
5763 int start = 0;
5764
5765 assert(lockPath!=NULL);
5766 /* try to create all the intermediate directories */
5767 len = (int)strlen(lockPath);
5768 buf[0] = lockPath[0];
5769 for( i=1; i<len; i++ ){
5770 if( lockPath[i] == '/' && (i - start > 0) ){
5771 /* only mkdir if leaf dir != "." or "/" or ".." */
5772 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5773 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5774 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005775 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005776 int err=errno;
5777 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005778 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005779 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005780 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005781 return err;
5782 }
5783 }
5784 }
5785 start=i+1;
5786 }
5787 buf[i] = lockPath[i];
5788 }
drh308c2a52010-05-14 11:30:18 +00005789 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005790 return 0;
5791}
5792
drh715ff302008-12-03 22:32:44 +00005793/*
5794** Create a new VFS file descriptor (stored in memory obtained from
5795** sqlite3_malloc) and open the file named "path" in the file descriptor.
5796**
5797** The caller is responsible not only for closing the file descriptor
5798** but also for freeing the memory associated with the file descriptor.
5799*/
drh7ed97b92010-01-20 13:07:21 +00005800static int proxyCreateUnixFile(
5801 const char *path, /* path for the new unixFile */
5802 unixFile **ppFile, /* unixFile created and returned by ref */
5803 int islockfile /* if non zero missing dirs will be created */
5804) {
5805 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005806 unixFile *pNew;
5807 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005808 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005809 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005810 int terrno = 0;
5811 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005812
drh7ed97b92010-01-20 13:07:21 +00005813 /* 1. first try to open/create the file
5814 ** 2. if that fails, and this is a lock file (not-conch), try creating
5815 ** the parent directories and then try again.
5816 ** 3. if that fails, try to open the file read-only
5817 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5818 */
5819 pUnused = findReusableFd(path, openFlags);
5820 if( pUnused ){
5821 fd = pUnused->fd;
5822 }else{
5823 pUnused = sqlite3_malloc(sizeof(*pUnused));
5824 if( !pUnused ){
5825 return SQLITE_NOMEM;
5826 }
5827 }
5828 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005829 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005830 terrno = errno;
5831 if( fd<0 && errno==ENOENT && islockfile ){
5832 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005833 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005834 }
5835 }
5836 }
5837 if( fd<0 ){
5838 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005839 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005840 terrno = errno;
5841 }
5842 if( fd<0 ){
5843 if( islockfile ){
5844 return SQLITE_BUSY;
5845 }
5846 switch (terrno) {
5847 case EACCES:
5848 return SQLITE_PERM;
5849 case EIO:
5850 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5851 default:
drh9978c972010-02-23 17:36:32 +00005852 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005853 }
5854 }
5855
5856 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5857 if( pNew==NULL ){
5858 rc = SQLITE_NOMEM;
5859 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005860 }
5861 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005862 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005863 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005864 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005865 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005866 pUnused->fd = fd;
5867 pUnused->flags = openFlags;
5868 pNew->pUnused = pUnused;
5869
drhc02a43a2012-01-10 23:18:38 +00005870 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00005871 if( rc==SQLITE_OK ){
5872 *ppFile = pNew;
5873 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005874 }
drh7ed97b92010-01-20 13:07:21 +00005875end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005876 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005877 sqlite3_free(pNew);
5878 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005879 return rc;
5880}
5881
drh7ed97b92010-01-20 13:07:21 +00005882#ifdef SQLITE_TEST
5883/* simulate multiple hosts by creating unique hostid file paths */
5884int sqlite3_hostid_num = 0;
5885#endif
5886
5887#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5888
drh0ab216a2010-07-02 17:10:40 +00005889/* Not always defined in the headers as it ought to be */
5890extern int gethostuuid(uuid_t id, const struct timespec *wait);
5891
drh7ed97b92010-01-20 13:07:21 +00005892/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5893** bytes of writable memory.
5894*/
5895static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005896 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5897 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005898#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5899 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005900 {
5901 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5902 if( gethostuuid(pHostID, &timeout) ){
5903 int err = errno;
5904 if( pError ){
5905 *pError = err;
5906 }
5907 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005908 }
drh7ed97b92010-01-20 13:07:21 +00005909 }
drh3d4435b2011-08-26 20:55:50 +00005910#else
5911 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005912#endif
drh7ed97b92010-01-20 13:07:21 +00005913#ifdef SQLITE_TEST
5914 /* simulate multiple hosts by creating unique hostid file paths */
5915 if( sqlite3_hostid_num != 0){
5916 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5917 }
5918#endif
5919
5920 return SQLITE_OK;
5921}
5922
5923/* The conch file contains the header, host id and lock file path
5924 */
5925#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5926#define PROXY_HEADERLEN 1 /* conch file header length */
5927#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5928#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5929
5930/*
5931** Takes an open conch file, copies the contents to a new path and then moves
5932** it back. The newly created file's file descriptor is assigned to the
5933** conch file structure and finally the original conch file descriptor is
5934** closed. Returns zero if successful.
5935*/
5936static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5937 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5938 unixFile *conchFile = pCtx->conchFile;
5939 char tPath[MAXPATHLEN];
5940 char buf[PROXY_MAXCONCHLEN];
5941 char *cPath = pCtx->conchFilePath;
5942 size_t readLen = 0;
5943 size_t pathLen = 0;
5944 char errmsg[64] = "";
5945 int fd = -1;
5946 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005947 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005948
5949 /* create a new path by replace the trailing '-conch' with '-break' */
5950 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5951 if( pathLen>MAXPATHLEN || pathLen<6 ||
5952 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005953 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005954 goto end_breaklock;
5955 }
5956 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005957 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005958 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005959 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005960 goto end_breaklock;
5961 }
5962 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005963 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5964 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005965 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005966 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005967 goto end_breaklock;
5968 }
drhe562be52011-03-02 18:01:10 +00005969 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005970 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005971 goto end_breaklock;
5972 }
5973 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005974 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005975 goto end_breaklock;
5976 }
5977 rc = 0;
5978 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005979 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005980 conchFile->h = fd;
5981 conchFile->openFlags = O_RDWR | O_CREAT;
5982
5983end_breaklock:
5984 if( rc ){
5985 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005986 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005987 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005988 }
5989 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5990 }
5991 return rc;
5992}
5993
5994/* Take the requested lock on the conch file and break a stale lock if the
5995** host id matches.
5996*/
5997static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5998 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5999 unixFile *conchFile = pCtx->conchFile;
6000 int rc = SQLITE_OK;
6001 int nTries = 0;
6002 struct timespec conchModTime;
6003
drh3d4435b2011-08-26 20:55:50 +00006004 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006005 do {
6006 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6007 nTries ++;
6008 if( rc==SQLITE_BUSY ){
6009 /* If the lock failed (busy):
6010 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6011 * 2nd try: fail if the mod time changed or host id is different, wait
6012 * 10 sec and try again
6013 * 3rd try: break the lock unless the mod time has changed.
6014 */
6015 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006016 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006017 pFile->lastErrno = errno;
6018 return SQLITE_IOERR_LOCK;
6019 }
6020
6021 if( nTries==1 ){
6022 conchModTime = buf.st_mtimespec;
6023 usleep(500000); /* wait 0.5 sec and try the lock again*/
6024 continue;
6025 }
6026
6027 assert( nTries>1 );
6028 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6029 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6030 return SQLITE_BUSY;
6031 }
6032
6033 if( nTries==2 ){
6034 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006035 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006036 if( len<0 ){
6037 pFile->lastErrno = errno;
6038 return SQLITE_IOERR_LOCK;
6039 }
6040 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6041 /* don't break the lock if the host id doesn't match */
6042 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6043 return SQLITE_BUSY;
6044 }
6045 }else{
6046 /* don't break the lock on short read or a version mismatch */
6047 return SQLITE_BUSY;
6048 }
6049 usleep(10000000); /* wait 10 sec and try the lock again */
6050 continue;
6051 }
6052
6053 assert( nTries==3 );
6054 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6055 rc = SQLITE_OK;
6056 if( lockType==EXCLUSIVE_LOCK ){
6057 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6058 }
6059 if( !rc ){
6060 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6061 }
6062 }
6063 }
6064 } while( rc==SQLITE_BUSY && nTries<3 );
6065
6066 return rc;
6067}
6068
6069/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006070** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6071** lockPath means that the lockPath in the conch file will be used if the
6072** host IDs match, or a new lock path will be generated automatically
6073** and written to the conch file.
6074*/
6075static int proxyTakeConch(unixFile *pFile){
6076 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6077
drh7ed97b92010-01-20 13:07:21 +00006078 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006079 return SQLITE_OK;
6080 }else{
6081 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006082 uuid_t myHostID;
6083 int pError = 0;
6084 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006085 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006086 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006087 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006088 int createConch = 0;
6089 int hostIdMatch = 0;
6090 int readLen = 0;
6091 int tryOldLockPath = 0;
6092 int forceNewLockPath = 0;
6093
drh308c2a52010-05-14 11:30:18 +00006094 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6095 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006096
drh7ed97b92010-01-20 13:07:21 +00006097 rc = proxyGetHostID(myHostID, &pError);
6098 if( (rc&0xff)==SQLITE_IOERR ){
6099 pFile->lastErrno = pError;
6100 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006101 }
drh7ed97b92010-01-20 13:07:21 +00006102 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006103 if( rc!=SQLITE_OK ){
6104 goto end_takeconch;
6105 }
drh7ed97b92010-01-20 13:07:21 +00006106 /* read the existing conch file */
6107 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6108 if( readLen<0 ){
6109 /* I/O error: lastErrno set by seekAndRead */
6110 pFile->lastErrno = conchFile->lastErrno;
6111 rc = SQLITE_IOERR_READ;
6112 goto end_takeconch;
6113 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6114 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6115 /* a short read or version format mismatch means we need to create a new
6116 ** conch file.
6117 */
6118 createConch = 1;
6119 }
6120 /* if the host id matches and the lock path already exists in the conch
6121 ** we'll try to use the path there, if we can't open that path, we'll
6122 ** retry with a new auto-generated path
6123 */
6124 do { /* in case we need to try again for an :auto: named lock file */
6125
6126 if( !createConch && !forceNewLockPath ){
6127 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6128 PROXY_HOSTIDLEN);
6129 /* if the conch has data compare the contents */
6130 if( !pCtx->lockProxyPath ){
6131 /* for auto-named local lock file, just check the host ID and we'll
6132 ** use the local lock file path that's already in there
6133 */
6134 if( hostIdMatch ){
6135 size_t pathLen = (readLen - PROXY_PATHINDEX);
6136
6137 if( pathLen>=MAXPATHLEN ){
6138 pathLen=MAXPATHLEN-1;
6139 }
6140 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6141 lockPath[pathLen] = 0;
6142 tempLockPath = lockPath;
6143 tryOldLockPath = 1;
6144 /* create a copy of the lock path if the conch is taken */
6145 goto end_takeconch;
6146 }
6147 }else if( hostIdMatch
6148 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6149 readLen-PROXY_PATHINDEX)
6150 ){
6151 /* conch host and lock path match */
6152 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006153 }
drh7ed97b92010-01-20 13:07:21 +00006154 }
6155
6156 /* if the conch isn't writable and doesn't match, we can't take it */
6157 if( (conchFile->openFlags&O_RDWR) == 0 ){
6158 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006159 goto end_takeconch;
6160 }
drh7ed97b92010-01-20 13:07:21 +00006161
6162 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006163 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006164 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6165 tempLockPath = lockPath;
6166 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006167 }
drh7ed97b92010-01-20 13:07:21 +00006168
6169 /* update conch with host and path (this will fail if other process
6170 ** has a shared lock already), if the host id matches, use the big
6171 ** stick.
drh715ff302008-12-03 22:32:44 +00006172 */
drh7ed97b92010-01-20 13:07:21 +00006173 futimes(conchFile->h, NULL);
6174 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006175 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006176 /* We are trying for an exclusive lock but another thread in this
6177 ** same process is still holding a shared lock. */
6178 rc = SQLITE_BUSY;
6179 } else {
6180 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006181 }
drh715ff302008-12-03 22:32:44 +00006182 }else{
drh7ed97b92010-01-20 13:07:21 +00006183 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006184 }
drh7ed97b92010-01-20 13:07:21 +00006185 if( rc==SQLITE_OK ){
6186 char writeBuffer[PROXY_MAXCONCHLEN];
6187 int writeSize = 0;
6188
6189 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6190 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6191 if( pCtx->lockProxyPath!=NULL ){
6192 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6193 }else{
6194 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6195 }
6196 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006197 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006198 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6199 fsync(conchFile->h);
6200 /* If we created a new conch file (not just updated the contents of a
6201 ** valid conch file), try to match the permissions of the database
6202 */
6203 if( rc==SQLITE_OK && createConch ){
6204 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006205 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006206 if( err==0 ){
6207 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6208 S_IROTH|S_IWOTH);
6209 /* try to match the database file R/W permissions, ignore failure */
6210#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006211 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006212#else
drhff812312011-02-23 13:33:46 +00006213 do{
drhe562be52011-03-02 18:01:10 +00006214 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006215 }while( rc==(-1) && errno==EINTR );
6216 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006217 int code = errno;
6218 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6219 cmode, code, strerror(code));
6220 } else {
6221 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6222 }
6223 }else{
6224 int code = errno;
6225 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6226 err, code, strerror(code));
6227#endif
6228 }
drh715ff302008-12-03 22:32:44 +00006229 }
6230 }
drh7ed97b92010-01-20 13:07:21 +00006231 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6232
6233 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006234 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006235 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006236 int fd;
drh7ed97b92010-01-20 13:07:21 +00006237 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006238 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006239 }
6240 pFile->h = -1;
drh3d4435b2011-08-26 20:55:50 +00006241 fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006242 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006243 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006244 if( fd>=0 ){
6245 pFile->h = fd;
6246 }else{
drh9978c972010-02-23 17:36:32 +00006247 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006248 during locking */
6249 }
6250 }
6251 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6252 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6253 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6254 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6255 /* we couldn't create the proxy lock file with the old lock file path
6256 ** so try again via auto-naming
6257 */
6258 forceNewLockPath = 1;
6259 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006260 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006261 }
6262 }
6263 if( rc==SQLITE_OK ){
6264 /* Need to make a copy of path if we extracted the value
6265 ** from the conch file or the path was allocated on the stack
6266 */
6267 if( tempLockPath ){
6268 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6269 if( !pCtx->lockProxyPath ){
6270 rc = SQLITE_NOMEM;
6271 }
6272 }
6273 }
6274 if( rc==SQLITE_OK ){
6275 pCtx->conchHeld = 1;
6276
6277 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6278 afpLockingContext *afpCtx;
6279 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6280 afpCtx->dbPath = pCtx->lockProxyPath;
6281 }
6282 } else {
6283 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6284 }
drh308c2a52010-05-14 11:30:18 +00006285 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6286 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006287 return rc;
drh308c2a52010-05-14 11:30:18 +00006288 } while (1); /* in case we need to retry the :auto: lock file -
6289 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006290 }
6291}
6292
6293/*
6294** If pFile holds a lock on a conch file, then release that lock.
6295*/
6296static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006297 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006298 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6299 unixFile *conchFile; /* Name of the conch file */
6300
6301 pCtx = (proxyLockingContext *)pFile->lockingContext;
6302 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006303 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006304 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006305 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006306 if( pCtx->conchHeld>0 ){
6307 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6308 }
drh715ff302008-12-03 22:32:44 +00006309 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006310 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6311 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006312 return rc;
6313}
6314
6315/*
6316** Given the name of a database file, compute the name of its conch file.
6317** Store the conch filename in memory obtained from sqlite3_malloc().
6318** Make *pConchPath point to the new name. Return SQLITE_OK on success
6319** or SQLITE_NOMEM if unable to obtain memory.
6320**
6321** The caller is responsible for ensuring that the allocated memory
6322** space is eventually freed.
6323**
6324** *pConchPath is set to NULL if a memory allocation error occurs.
6325*/
6326static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6327 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006328 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006329 char *conchPath; /* buffer in which to construct conch name */
6330
6331 /* Allocate space for the conch filename and initialize the name to
6332 ** the name of the original database file. */
6333 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6334 if( conchPath==0 ){
6335 return SQLITE_NOMEM;
6336 }
6337 memcpy(conchPath, dbPath, len+1);
6338
6339 /* now insert a "." before the last / character */
6340 for( i=(len-1); i>=0; i-- ){
6341 if( conchPath[i]=='/' ){
6342 i++;
6343 break;
6344 }
6345 }
6346 conchPath[i]='.';
6347 while ( i<len ){
6348 conchPath[i+1]=dbPath[i];
6349 i++;
6350 }
6351
6352 /* append the "-conch" suffix to the file */
6353 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006354 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006355
6356 return SQLITE_OK;
6357}
6358
6359
6360/* Takes a fully configured proxy locking-style unix file and switches
6361** the local lock file path
6362*/
6363static int switchLockProxyPath(unixFile *pFile, const char *path) {
6364 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6365 char *oldPath = pCtx->lockProxyPath;
6366 int rc = SQLITE_OK;
6367
drh308c2a52010-05-14 11:30:18 +00006368 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006369 return SQLITE_BUSY;
6370 }
6371
6372 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6373 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6374 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6375 return SQLITE_OK;
6376 }else{
6377 unixFile *lockProxy = pCtx->lockProxy;
6378 pCtx->lockProxy=NULL;
6379 pCtx->conchHeld = 0;
6380 if( lockProxy!=NULL ){
6381 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6382 if( rc ) return rc;
6383 sqlite3_free(lockProxy);
6384 }
6385 sqlite3_free(oldPath);
6386 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6387 }
6388
6389 return rc;
6390}
6391
6392/*
6393** pFile is a file that has been opened by a prior xOpen call. dbPath
6394** is a string buffer at least MAXPATHLEN+1 characters in size.
6395**
6396** This routine find the filename associated with pFile and writes it
6397** int dbPath.
6398*/
6399static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006400#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006401 if( pFile->pMethod == &afpIoMethods ){
6402 /* afp style keeps a reference to the db path in the filePath field
6403 ** of the struct */
drhea678832008-12-10 19:26:22 +00006404 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006405 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6406 } else
drh715ff302008-12-03 22:32:44 +00006407#endif
6408 if( pFile->pMethod == &dotlockIoMethods ){
6409 /* dot lock style uses the locking context to store the dot lock
6410 ** file path */
6411 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6412 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6413 }else{
6414 /* all other styles use the locking context to store the db file path */
6415 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006416 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006417 }
6418 return SQLITE_OK;
6419}
6420
6421/*
6422** Takes an already filled in unix file and alters it so all file locking
6423** will be performed on the local proxy lock file. The following fields
6424** are preserved in the locking context so that they can be restored and
6425** the unix structure properly cleaned up at close time:
6426** ->lockingContext
6427** ->pMethod
6428*/
6429static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6430 proxyLockingContext *pCtx;
6431 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6432 char *lockPath=NULL;
6433 int rc = SQLITE_OK;
6434
drh308c2a52010-05-14 11:30:18 +00006435 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006436 return SQLITE_BUSY;
6437 }
6438 proxyGetDbPathForUnixFile(pFile, dbPath);
6439 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6440 lockPath=NULL;
6441 }else{
6442 lockPath=(char *)path;
6443 }
6444
drh308c2a52010-05-14 11:30:18 +00006445 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6446 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006447
6448 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6449 if( pCtx==0 ){
6450 return SQLITE_NOMEM;
6451 }
6452 memset(pCtx, 0, sizeof(*pCtx));
6453
6454 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6455 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006456 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6457 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6458 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6459 ** (c) the file system is read-only, then enable no-locking access.
6460 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6461 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6462 */
6463 struct statfs fsInfo;
6464 struct stat conchInfo;
6465 int goLockless = 0;
6466
drh99ab3b12011-03-02 15:09:07 +00006467 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006468 int err = errno;
6469 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6470 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6471 }
6472 }
6473 if( goLockless ){
6474 pCtx->conchHeld = -1; /* read only FS/ lockless */
6475 rc = SQLITE_OK;
6476 }
6477 }
drh715ff302008-12-03 22:32:44 +00006478 }
6479 if( rc==SQLITE_OK && lockPath ){
6480 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6481 }
6482
6483 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006484 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6485 if( pCtx->dbPath==NULL ){
6486 rc = SQLITE_NOMEM;
6487 }
6488 }
6489 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006490 /* all memory is allocated, proxys are created and assigned,
6491 ** switch the locking context and pMethod then return.
6492 */
drh715ff302008-12-03 22:32:44 +00006493 pCtx->oldLockingContext = pFile->lockingContext;
6494 pFile->lockingContext = pCtx;
6495 pCtx->pOldMethod = pFile->pMethod;
6496 pFile->pMethod = &proxyIoMethods;
6497 }else{
6498 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006499 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006500 sqlite3_free(pCtx->conchFile);
6501 }
drhd56b1212010-08-11 06:14:15 +00006502 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006503 sqlite3_free(pCtx->conchFilePath);
6504 sqlite3_free(pCtx);
6505 }
drh308c2a52010-05-14 11:30:18 +00006506 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6507 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006508 return rc;
6509}
6510
6511
6512/*
6513** This routine handles sqlite3_file_control() calls that are specific
6514** to proxy locking.
6515*/
6516static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6517 switch( op ){
6518 case SQLITE_GET_LOCKPROXYFILE: {
6519 unixFile *pFile = (unixFile*)id;
6520 if( pFile->pMethod == &proxyIoMethods ){
6521 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6522 proxyTakeConch(pFile);
6523 if( pCtx->lockProxyPath ){
6524 *(const char **)pArg = pCtx->lockProxyPath;
6525 }else{
6526 *(const char **)pArg = ":auto: (not held)";
6527 }
6528 } else {
6529 *(const char **)pArg = NULL;
6530 }
6531 return SQLITE_OK;
6532 }
6533 case SQLITE_SET_LOCKPROXYFILE: {
6534 unixFile *pFile = (unixFile*)id;
6535 int rc = SQLITE_OK;
6536 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6537 if( pArg==NULL || (const char *)pArg==0 ){
6538 if( isProxyStyle ){
6539 /* turn off proxy locking - not supported */
6540 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6541 }else{
6542 /* turn off proxy locking - already off - NOOP */
6543 rc = SQLITE_OK;
6544 }
6545 }else{
6546 const char *proxyPath = (const char *)pArg;
6547 if( isProxyStyle ){
6548 proxyLockingContext *pCtx =
6549 (proxyLockingContext*)pFile->lockingContext;
6550 if( !strcmp(pArg, ":auto:")
6551 || (pCtx->lockProxyPath &&
6552 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6553 ){
6554 rc = SQLITE_OK;
6555 }else{
6556 rc = switchLockProxyPath(pFile, proxyPath);
6557 }
6558 }else{
6559 /* turn on proxy file locking */
6560 rc = proxyTransformUnixFile(pFile, proxyPath);
6561 }
6562 }
6563 return rc;
6564 }
6565 default: {
6566 assert( 0 ); /* The call assures that only valid opcodes are sent */
6567 }
6568 }
6569 /*NOTREACHED*/
6570 return SQLITE_ERROR;
6571}
6572
6573/*
6574** Within this division (the proxying locking implementation) the procedures
6575** above this point are all utilities. The lock-related methods of the
6576** proxy-locking sqlite3_io_method object follow.
6577*/
6578
6579
6580/*
6581** This routine checks if there is a RESERVED lock held on the specified
6582** file by this or any other process. If such a lock is held, set *pResOut
6583** to a non-zero value otherwise *pResOut is set to zero. The return value
6584** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6585*/
6586static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6587 unixFile *pFile = (unixFile*)id;
6588 int rc = proxyTakeConch(pFile);
6589 if( rc==SQLITE_OK ){
6590 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006591 if( pCtx->conchHeld>0 ){
6592 unixFile *proxy = pCtx->lockProxy;
6593 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6594 }else{ /* conchHeld < 0 is lockless */
6595 pResOut=0;
6596 }
drh715ff302008-12-03 22:32:44 +00006597 }
6598 return rc;
6599}
6600
6601/*
drh308c2a52010-05-14 11:30:18 +00006602** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006603** of the following:
6604**
6605** (1) SHARED_LOCK
6606** (2) RESERVED_LOCK
6607** (3) PENDING_LOCK
6608** (4) EXCLUSIVE_LOCK
6609**
6610** Sometimes when requesting one lock state, additional lock states
6611** are inserted in between. The locking might fail on one of the later
6612** transitions leaving the lock state different from what it started but
6613** still short of its goal. The following chart shows the allowed
6614** transitions and the inserted intermediate states:
6615**
6616** UNLOCKED -> SHARED
6617** SHARED -> RESERVED
6618** SHARED -> (PENDING) -> EXCLUSIVE
6619** RESERVED -> (PENDING) -> EXCLUSIVE
6620** PENDING -> EXCLUSIVE
6621**
6622** This routine will only increase a lock. Use the sqlite3OsUnlock()
6623** routine to lower a locking level.
6624*/
drh308c2a52010-05-14 11:30:18 +00006625static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006626 unixFile *pFile = (unixFile*)id;
6627 int rc = proxyTakeConch(pFile);
6628 if( rc==SQLITE_OK ){
6629 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006630 if( pCtx->conchHeld>0 ){
6631 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006632 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6633 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006634 }else{
6635 /* conchHeld < 0 is lockless */
6636 }
drh715ff302008-12-03 22:32:44 +00006637 }
6638 return rc;
6639}
6640
6641
6642/*
drh308c2a52010-05-14 11:30:18 +00006643** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006644** must be either NO_LOCK or SHARED_LOCK.
6645**
6646** If the locking level of the file descriptor is already at or below
6647** the requested locking level, this routine is a no-op.
6648*/
drh308c2a52010-05-14 11:30:18 +00006649static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006650 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;
drh308c2a52010-05-14 11:30:18 +00006656 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6657 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006658 }else{
6659 /* conchHeld < 0 is lockless */
6660 }
drh715ff302008-12-03 22:32:44 +00006661 }
6662 return rc;
6663}
6664
6665/*
6666** Close a file that uses proxy locks.
6667*/
6668static int proxyClose(sqlite3_file *id) {
6669 if( id ){
6670 unixFile *pFile = (unixFile*)id;
6671 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6672 unixFile *lockProxy = pCtx->lockProxy;
6673 unixFile *conchFile = pCtx->conchFile;
6674 int rc = SQLITE_OK;
6675
6676 if( lockProxy ){
6677 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6678 if( rc ) return rc;
6679 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6680 if( rc ) return rc;
6681 sqlite3_free(lockProxy);
6682 pCtx->lockProxy = 0;
6683 }
6684 if( conchFile ){
6685 if( pCtx->conchHeld ){
6686 rc = proxyReleaseConch(pFile);
6687 if( rc ) return rc;
6688 }
6689 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6690 if( rc ) return rc;
6691 sqlite3_free(conchFile);
6692 }
drhd56b1212010-08-11 06:14:15 +00006693 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006694 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006695 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006696 /* restore the original locking context and pMethod then close it */
6697 pFile->lockingContext = pCtx->oldLockingContext;
6698 pFile->pMethod = pCtx->pOldMethod;
6699 sqlite3_free(pCtx);
6700 return pFile->pMethod->xClose(id);
6701 }
6702 return SQLITE_OK;
6703}
6704
6705
6706
drhd2cb50b2009-01-09 21:41:17 +00006707#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006708/*
6709** The proxy locking style is intended for use with AFP filesystems.
6710** And since AFP is only supported on MacOSX, the proxy locking is also
6711** restricted to MacOSX.
6712**
6713**
6714******************* End of the proxy lock implementation **********************
6715******************************************************************************/
6716
drh734c9862008-11-28 15:37:20 +00006717/*
danielk1977e339d652008-06-28 11:23:00 +00006718** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006719**
6720** This routine registers all VFS implementations for unix-like operating
6721** systems. This routine, and the sqlite3_os_end() routine that follows,
6722** should be the only routines in this file that are visible from other
6723** files.
drh6b9d6dd2008-12-03 19:34:47 +00006724**
6725** This routine is called once during SQLite initialization and by a
6726** single thread. The memory allocation and mutex subsystems have not
6727** necessarily been initialized when this routine is called, and so they
6728** should not be used.
drh153c62c2007-08-24 03:51:33 +00006729*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006730int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006731 /*
6732 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006733 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6734 ** to the "finder" function. (pAppData is a pointer to a pointer because
6735 ** silly C90 rules prohibit a void* from being cast to a function pointer
6736 ** and so we have to go through the intermediate pointer to avoid problems
6737 ** when compiling with -pedantic-errors on GCC.)
6738 **
6739 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006740 ** finder-function. The finder-function returns a pointer to the
6741 ** sqlite_io_methods object that implements the desired locking
6742 ** behaviors. See the division above that contains the IOMETHODS
6743 ** macro for addition information on finder-functions.
6744 **
6745 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6746 ** object. But the "autolockIoFinder" available on MacOSX does a little
6747 ** more than that; it looks at the filesystem type that hosts the
6748 ** database file and tries to choose an locking method appropriate for
6749 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006750 */
drh7708e972008-11-29 00:56:52 +00006751 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006752 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006753 sizeof(unixFile), /* szOsFile */ \
6754 MAX_PATHNAME, /* mxPathname */ \
6755 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006756 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006757 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006758 unixOpen, /* xOpen */ \
6759 unixDelete, /* xDelete */ \
6760 unixAccess, /* xAccess */ \
6761 unixFullPathname, /* xFullPathname */ \
6762 unixDlOpen, /* xDlOpen */ \
6763 unixDlError, /* xDlError */ \
6764 unixDlSym, /* xDlSym */ \
6765 unixDlClose, /* xDlClose */ \
6766 unixRandomness, /* xRandomness */ \
6767 unixSleep, /* xSleep */ \
6768 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006769 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006770 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006771 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006772 unixGetSystemCall, /* xGetSystemCall */ \
6773 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006774 }
6775
drh6b9d6dd2008-12-03 19:34:47 +00006776 /*
6777 ** All default VFSes for unix are contained in the following array.
6778 **
6779 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6780 ** by the SQLite core when the VFS is registered. So the following
6781 ** array cannot be const.
6782 */
danielk1977e339d652008-06-28 11:23:00 +00006783 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006784#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006785 UNIXVFS("unix", autolockIoFinder ),
6786#else
6787 UNIXVFS("unix", posixIoFinder ),
6788#endif
6789 UNIXVFS("unix-none", nolockIoFinder ),
6790 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006791 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006792#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006793 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006794#endif
6795#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006796 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006797#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006798 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006799#endif
chw78a13182009-04-07 05:35:03 +00006800#endif
drhd2cb50b2009-01-09 21:41:17 +00006801#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006802 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006803 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006804 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006805#endif
drh153c62c2007-08-24 03:51:33 +00006806 };
drh6b9d6dd2008-12-03 19:34:47 +00006807 unsigned int i; /* Loop counter */
6808
drh2aa5a002011-04-13 13:42:25 +00006809 /* Double-check that the aSyscall[] array has been constructed
6810 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh8942d412012-01-02 18:20:14 +00006811 assert( ArraySize(aSyscall)==20 );
drh2aa5a002011-04-13 13:42:25 +00006812
drh6b9d6dd2008-12-03 19:34:47 +00006813 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006814 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006815 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006816 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006817 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006818}
danielk1977e339d652008-06-28 11:23:00 +00006819
6820/*
drh6b9d6dd2008-12-03 19:34:47 +00006821** Shutdown the operating system interface.
6822**
6823** Some operating systems might need to do some cleanup in this routine,
6824** to release dynamically allocated objects. But not on unix.
6825** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006826*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006827int sqlite3_os_end(void){
6828 return SQLITE_OK;
6829}
drhdce8bdb2007-08-16 13:01:44 +00006830
danielk197729bafea2008-06-26 10:41:19 +00006831#endif /* SQLITE_OS_UNIX */