blob: 5ca3415a5300350101cc820955ac30cee1cd8e88 [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
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drhdbe4b882011-06-20 18:00:17 +0000141#ifdef HAVE_UTIME
142# include <utime.h>
143#endif
144
drh9cbe6352005-11-29 03:13:21 +0000145/*
drh7ed97b92010-01-20 13:07:21 +0000146** Allowed values of unixFile.fsFlags
147*/
148#define SQLITE_FSFLAGS_IS_MSDOS 0x1
149
150/*
drhf1a221e2006-01-15 17:27:17 +0000151** If we are to be thread-safe, include the pthreads header and define
152** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000153*/
drhd677b3d2007-08-20 22:48:41 +0000154#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000155# include <pthread.h>
156# define SQLITE_UNIX_THREADS 1
157#endif
158
159/*
160** Default permissions when creating a new file
161*/
162#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
163# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
164#endif
165
danielk1977b4b47412007-08-17 15:53:36 +0000166/*
aswiftaebf4132008-11-21 00:10:35 +0000167 ** Default permissions when creating auto proxy dir
168 */
169#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
170# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
171#endif
172
173/*
danielk1977b4b47412007-08-17 15:53:36 +0000174** Maximum supported path-length.
175*/
176#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000177
drh734c9862008-11-28 15:37:20 +0000178/*
drh734c9862008-11-28 15:37:20 +0000179** Only set the lastErrno if the error code is a real error and not
180** a normal expected return code of SQLITE_BUSY or SQLITE_OK
181*/
182#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
183
drhd91c68f2010-05-14 14:52:25 +0000184/* Forward references */
185typedef struct unixShm unixShm; /* Connection shared memory */
186typedef struct unixShmNode unixShmNode; /* Shared memory instance */
187typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
188typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000189
190/*
dane946c392009-08-22 11:39:46 +0000191** Sometimes, after a file handle is closed by SQLite, the file descriptor
192** cannot be closed immediately. In these cases, instances of the following
193** structure are used to store the file descriptor while waiting for an
194** opportunity to either close or reuse it.
195*/
dane946c392009-08-22 11:39:46 +0000196struct UnixUnusedFd {
197 int fd; /* File descriptor to close */
198 int flags; /* Flags this file descriptor was opened with */
199 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
200};
201
202/*
drh9b35ea62008-11-29 02:20:26 +0000203** The unixFile structure is subclass of sqlite3_file specific to the unix
204** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000205*/
drh054889e2005-11-30 03:20:31 +0000206typedef struct unixFile unixFile;
207struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000208 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000209 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000210 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000211 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000212 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000213 int lastErrno; /* The unix errno from last I/O error */
214 void *lockingContext; /* Locking style specific state */
215 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000216 const char *zPath; /* Name of the file */
217 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000218 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000219#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000220 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000221#endif
drh7ed97b92010-01-20 13:07:21 +0000222#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000223 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000224#endif
225#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000226 int isDelete; /* Delete on close if true */
227 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000228#endif
drh8f941bc2009-01-14 23:03:40 +0000229#ifndef NDEBUG
230 /* The next group of variables are used to track whether or not the
231 ** transaction counter in bytes 24-27 of database files are updated
232 ** whenever any part of the database changes. An assertion fault will
233 ** occur if a file is updated without also updating the transaction
234 ** counter. This test is made to avoid new problems similar to the
235 ** one described by ticket #3584.
236 */
237 unsigned char transCntrChng; /* True if the transaction counter changed */
238 unsigned char dbUpdate; /* True if any part of database file changed */
239 unsigned char inNormalWrite; /* True if in a normal write operation */
240#endif
danielk1977967a4a12007-08-20 14:23:44 +0000241#ifdef SQLITE_TEST
242 /* In test mode, increase the size of this structure a bit so that
243 ** it is larger than the struct CrashFile defined in test6.c.
244 */
245 char aPadding[32];
246#endif
drh9cbe6352005-11-29 03:13:21 +0000247};
248
drh0ccebe72005-06-07 22:22:50 +0000249/*
drha7e61d82011-03-12 17:02:57 +0000250** Allowed values for the unixFile.ctrlFlags bitmask:
251*/
drhf0b190d2011-07-26 16:03:07 +0000252#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
253#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
254#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000255#ifndef SQLITE_DISABLE_DIRSYNC
256# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
257#else
258# define UNIXFILE_DIRSYNC 0x00
259#endif
drha7e61d82011-03-12 17:02:57 +0000260
261/*
drh198bf392006-01-06 21:52:49 +0000262** Include code that is common to all os_*.c files
263*/
264#include "os_common.h"
265
266/*
drh0ccebe72005-06-07 22:22:50 +0000267** Define various macros that are missing from some systems.
268*/
drhbbd42a62004-05-22 17:41:58 +0000269#ifndef O_LARGEFILE
270# define O_LARGEFILE 0
271#endif
272#ifdef SQLITE_DISABLE_LFS
273# undef O_LARGEFILE
274# define O_LARGEFILE 0
275#endif
276#ifndef O_NOFOLLOW
277# define O_NOFOLLOW 0
278#endif
279#ifndef O_BINARY
280# define O_BINARY 0
281#endif
282
283/*
drh2b4b5962005-06-15 17:47:55 +0000284** The threadid macro resolves to the thread-id or to 0. Used for
285** testing and debugging only.
286*/
drhd677b3d2007-08-20 22:48:41 +0000287#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000288#define threadid pthread_self()
289#else
290#define threadid 0
291#endif
292
drh99ab3b12011-03-02 15:09:07 +0000293/*
drh9a3baf12011-04-25 18:01:27 +0000294** Different Unix systems declare open() in different ways. Same use
295** open(const char*,int,mode_t). Others use open(const char*,int,...).
296** The difference is important when using a pointer to the function.
297**
298** The safest way to deal with the problem is to always use this wrapper
299** which always has the same well-defined interface.
300*/
301static int posixOpen(const char *zFile, int flags, int mode){
302 return open(zFile, flags, mode);
303}
304
drh90315a22011-08-10 01:52:12 +0000305/* Forward reference */
306static int openDirectory(const char*, int*);
307
drh9a3baf12011-04-25 18:01:27 +0000308/*
drh99ab3b12011-03-02 15:09:07 +0000309** Many system calls are accessed through pointer-to-functions so that
310** they may be overridden at runtime to facilitate fault injection during
311** testing and sandboxing. The following array holds the names and pointers
312** to all overrideable system calls.
313*/
314static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000315 const char *zName; /* Name of the sytem call */
316 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
317 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000318} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000319 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
320#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000321
drh58ad5802011-03-23 22:02:23 +0000322 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000323#define osClose ((int(*)(int))aSyscall[1].pCurrent)
324
drh58ad5802011-03-23 22:02:23 +0000325 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000326#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
327
drh58ad5802011-03-23 22:02:23 +0000328 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000329#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
330
drh58ad5802011-03-23 22:02:23 +0000331 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000332#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
333
334/*
335** The DJGPP compiler environment looks mostly like Unix, but it
336** lacks the fcntl() system call. So redefine fcntl() to be something
337** that always succeeds. This means that locking does not occur under
338** DJGPP. But it is DOS - what did you expect?
339*/
340#ifdef __DJGPP__
341 { "fstat", 0, 0 },
342#define osFstat(a,b,c) 0
343#else
drh58ad5802011-03-23 22:02:23 +0000344 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
346#endif
347
drh58ad5802011-03-23 22:02:23 +0000348 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000349#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
350
drh58ad5802011-03-23 22:02:23 +0000351 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000352#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000353
drh58ad5802011-03-23 22:02:23 +0000354 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000355#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
356
drhd4a80312011-04-15 14:33:20 +0000357#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000358 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000359#else
drh58ad5802011-03-23 22:02:23 +0000360 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000361#endif
362#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
363
364#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000365 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000366#else
drh58ad5802011-03-23 22:02:23 +0000367 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000368#endif
369#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
370
drh58ad5802011-03-23 22:02:23 +0000371 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000372#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
373
drhd4a80312011-04-15 14:33:20 +0000374#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000375 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000376#else
drh58ad5802011-03-23 22:02:23 +0000377 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000378#endif
379#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
380 aSyscall[12].pCurrent)
381
382#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000383 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000384#else
drh58ad5802011-03-23 22:02:23 +0000385 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000386#endif
387#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
388 aSyscall[13].pCurrent)
389
drha6c47492011-04-11 18:35:09 +0000390#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000391 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000392#else
393 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000394#endif
drh2aa5a002011-04-13 13:42:25 +0000395#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000396
397#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000398 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000399#else
drh58ad5802011-03-23 22:02:23 +0000400 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000401#endif
dan0fd7d862011-03-29 10:04:23 +0000402#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000403
drh036ac7f2011-08-08 23:18:05 +0000404 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
405#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
406
drh90315a22011-08-10 01:52:12 +0000407 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
408#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
409
drh9ef6bc42011-11-04 02:24:02 +0000410 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
411#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
412
413 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
414#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
415
drhe562be52011-03-02 18:01:10 +0000416}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000417
418/*
419** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000420** "unix" VFSes. Return SQLITE_OK opon successfully updating the
421** system call pointer, or SQLITE_NOTFOUND if there is no configurable
422** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000423*/
424static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000425 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
426 const char *zName, /* Name of system call to override */
427 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000428){
drh58ad5802011-03-23 22:02:23 +0000429 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000430 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000431
432 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000433 if( zName==0 ){
434 /* If no zName is given, restore all system calls to their default
435 ** settings and return NULL
436 */
dan51438a72011-04-02 17:00:47 +0000437 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000438 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
439 if( aSyscall[i].pDefault ){
440 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000441 }
442 }
443 }else{
444 /* If zName is specified, operate on only the one system call
445 ** specified.
446 */
447 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
448 if( strcmp(zName, aSyscall[i].zName)==0 ){
449 if( aSyscall[i].pDefault==0 ){
450 aSyscall[i].pDefault = aSyscall[i].pCurrent;
451 }
drh1df30962011-03-02 19:06:42 +0000452 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000453 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
454 aSyscall[i].pCurrent = pNewFunc;
455 break;
456 }
457 }
458 }
459 return rc;
460}
461
drh1df30962011-03-02 19:06:42 +0000462/*
463** Return the value of a system call. Return NULL if zName is not a
464** recognized system call name. NULL is also returned if the system call
465** is currently undefined.
466*/
drh58ad5802011-03-23 22:02:23 +0000467static sqlite3_syscall_ptr unixGetSystemCall(
468 sqlite3_vfs *pNotUsed,
469 const char *zName
470){
471 unsigned int i;
472
473 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000474 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
475 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
476 }
477 return 0;
478}
479
480/*
481** Return the name of the first system call after zName. If zName==NULL
482** then return the name of the first system call. Return NULL if zName
483** is the last system call or if zName is not the name of a valid
484** system call.
485*/
486static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000487 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000488
489 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000490 if( zName ){
491 for(i=0; i<ArraySize(aSyscall)-1; i++){
492 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000493 }
494 }
dan0fd7d862011-03-29 10:04:23 +0000495 for(i++; i<ArraySize(aSyscall); i++){
496 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000497 }
498 return 0;
499}
500
drhad4f1e52011-03-04 15:43:57 +0000501/*
502** Retry open() calls that fail due to EINTR
503*/
504static int robust_open(const char *z, int f, int m){
505 int rc;
506 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
507 return rc;
508}
danielk197713adf8a2004-06-03 16:08:41 +0000509
drh107886a2008-11-21 22:21:50 +0000510/*
dan9359c7b2009-08-21 08:29:10 +0000511** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000512** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000513** vxworksFileId objects used by this file, all of which may be
514** shared by multiple threads.
515**
516** Function unixMutexHeld() is used to assert() that the global mutex
517** is held when required. This function is only used as part of assert()
518** statements. e.g.
519**
520** unixEnterMutex()
521** assert( unixMutexHeld() );
522** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000523*/
524static void unixEnterMutex(void){
525 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
526}
527static void unixLeaveMutex(void){
528 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
529}
dan9359c7b2009-08-21 08:29:10 +0000530#ifdef SQLITE_DEBUG
531static int unixMutexHeld(void) {
532 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
533}
534#endif
drh107886a2008-11-21 22:21:50 +0000535
drh734c9862008-11-28 15:37:20 +0000536
drh30ddce62011-10-15 00:16:30 +0000537#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000538/*
539** Helper function for printing out trace information from debugging
540** binaries. This returns the string represetation of the supplied
541** integer lock-type.
542*/
drh308c2a52010-05-14 11:30:18 +0000543static const char *azFileLock(int eFileLock){
544 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000545 case NO_LOCK: return "NONE";
546 case SHARED_LOCK: return "SHARED";
547 case RESERVED_LOCK: return "RESERVED";
548 case PENDING_LOCK: return "PENDING";
549 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000550 }
551 return "ERROR";
552}
553#endif
554
555#ifdef SQLITE_LOCK_TRACE
556/*
557** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000558**
drh734c9862008-11-28 15:37:20 +0000559** This routine is used for troubleshooting locks on multithreaded
560** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
561** command-line option on the compiler. This code is normally
562** turned off.
563*/
564static int lockTrace(int fd, int op, struct flock *p){
565 char *zOpName, *zType;
566 int s;
567 int savedErrno;
568 if( op==F_GETLK ){
569 zOpName = "GETLK";
570 }else if( op==F_SETLK ){
571 zOpName = "SETLK";
572 }else{
drh99ab3b12011-03-02 15:09:07 +0000573 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000574 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
575 return s;
576 }
577 if( p->l_type==F_RDLCK ){
578 zType = "RDLCK";
579 }else if( p->l_type==F_WRLCK ){
580 zType = "WRLCK";
581 }else if( p->l_type==F_UNLCK ){
582 zType = "UNLCK";
583 }else{
584 assert( 0 );
585 }
586 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000587 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000588 savedErrno = errno;
589 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
590 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
591 (int)p->l_pid, s);
592 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
593 struct flock l2;
594 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000595 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000596 if( l2.l_type==F_RDLCK ){
597 zType = "RDLCK";
598 }else if( l2.l_type==F_WRLCK ){
599 zType = "WRLCK";
600 }else if( l2.l_type==F_UNLCK ){
601 zType = "UNLCK";
602 }else{
603 assert( 0 );
604 }
605 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
606 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
607 }
608 errno = savedErrno;
609 return s;
610}
drh99ab3b12011-03-02 15:09:07 +0000611#undef osFcntl
612#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000613#endif /* SQLITE_LOCK_TRACE */
614
drhff812312011-02-23 13:33:46 +0000615/*
616** Retry ftruncate() calls that fail due to EINTR
617*/
drhff812312011-02-23 13:33:46 +0000618static int robust_ftruncate(int h, sqlite3_int64 sz){
619 int rc;
drh99ab3b12011-03-02 15:09:07 +0000620 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000621 return rc;
622}
drh734c9862008-11-28 15:37:20 +0000623
624/*
625** This routine translates a standard POSIX errno code into something
626** useful to the clients of the sqlite3 functions. Specifically, it is
627** intended to translate a variety of "try again" errors into SQLITE_BUSY
628** and a variety of "please close the file descriptor NOW" errors into
629** SQLITE_IOERR
630**
631** Errors during initialization of locks, or file system support for locks,
632** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
633*/
634static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
635 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000636#if 0
637 /* At one point this code was not commented out. In theory, this branch
638 ** should never be hit, as this function should only be called after
639 ** a locking-related function (i.e. fcntl()) has returned non-zero with
640 ** the value of errno as the first argument. Since a system call has failed,
641 ** errno should be non-zero.
642 **
643 ** Despite this, if errno really is zero, we still don't want to return
644 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
645 ** propagated back to the caller. Commenting this branch out means errno==0
646 ** will be handled by the "default:" case below.
647 */
drh734c9862008-11-28 15:37:20 +0000648 case 0:
649 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000650#endif
651
drh734c9862008-11-28 15:37:20 +0000652 case EAGAIN:
653 case ETIMEDOUT:
654 case EBUSY:
655 case EINTR:
656 case ENOLCK:
657 /* random NFS retry error, unless during file system support
658 * introspection, in which it actually means what it says */
659 return SQLITE_BUSY;
660
661 case EACCES:
662 /* EACCES is like EAGAIN during locking operations, but not any other time*/
663 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
664 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
665 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
666 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
667 return SQLITE_BUSY;
668 }
669 /* else fall through */
670 case EPERM:
671 return SQLITE_PERM;
672
danea83bc62011-04-01 11:56:32 +0000673 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
674 ** this module never makes such a call. And the code in SQLite itself
675 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
676 ** this case is also commented out. If the system does set errno to EDEADLK,
677 ** the default SQLITE_IOERR_XXX code will be returned. */
678#if 0
drh734c9862008-11-28 15:37:20 +0000679 case EDEADLK:
680 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000681#endif
drh734c9862008-11-28 15:37:20 +0000682
683#if EOPNOTSUPP!=ENOTSUP
684 case EOPNOTSUPP:
685 /* something went terribly awry, unless during file system support
686 * introspection, in which it actually means what it says */
687#endif
688#ifdef ENOTSUP
689 case ENOTSUP:
690 /* invalid fd, unless during file system support introspection, in which
691 * it actually means what it says */
692#endif
693 case EIO:
694 case EBADF:
695 case EINVAL:
696 case ENOTCONN:
697 case ENODEV:
698 case ENXIO:
699 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000700#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000701 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000702#endif
drh734c9862008-11-28 15:37:20 +0000703 case ENOSYS:
704 /* these should force the client to close the file and reconnect */
705
706 default:
707 return sqliteIOErr;
708 }
709}
710
711
712
713/******************************************************************************
714****************** Begin Unique File ID Utility Used By VxWorks ***************
715**
716** On most versions of unix, we can get a unique ID for a file by concatenating
717** the device number and the inode number. But this does not work on VxWorks.
718** On VxWorks, a unique file id must be based on the canonical filename.
719**
720** A pointer to an instance of the following structure can be used as a
721** unique file ID in VxWorks. Each instance of this structure contains
722** a copy of the canonical filename. There is also a reference count.
723** The structure is reclaimed when the number of pointers to it drops to
724** zero.
725**
726** There are never very many files open at one time and lookups are not
727** a performance-critical path, so it is sufficient to put these
728** structures on a linked list.
729*/
730struct vxworksFileId {
731 struct vxworksFileId *pNext; /* Next in a list of them all */
732 int nRef; /* Number of references to this one */
733 int nName; /* Length of the zCanonicalName[] string */
734 char *zCanonicalName; /* Canonical filename */
735};
736
737#if OS_VXWORKS
738/*
drh9b35ea62008-11-29 02:20:26 +0000739** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000740** variable:
741*/
742static struct vxworksFileId *vxworksFileList = 0;
743
744/*
745** Simplify a filename into its canonical form
746** by making the following changes:
747**
748** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000749** * convert /./ into just /
750** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000751**
752** Changes are made in-place. Return the new name length.
753**
754** The original filename is in z[0..n-1]. Return the number of
755** characters in the simplified name.
756*/
757static int vxworksSimplifyName(char *z, int n){
758 int i, j;
759 while( n>1 && z[n-1]=='/' ){ n--; }
760 for(i=j=0; i<n; i++){
761 if( z[i]=='/' ){
762 if( z[i+1]=='/' ) continue;
763 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
764 i += 1;
765 continue;
766 }
767 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
768 while( j>0 && z[j-1]!='/' ){ j--; }
769 if( j>0 ){ j--; }
770 i += 2;
771 continue;
772 }
773 }
774 z[j++] = z[i];
775 }
776 z[j] = 0;
777 return j;
778}
779
780/*
781** Find a unique file ID for the given absolute pathname. Return
782** a pointer to the vxworksFileId object. This pointer is the unique
783** file ID.
784**
785** The nRef field of the vxworksFileId object is incremented before
786** the object is returned. A new vxworksFileId object is created
787** and added to the global list if necessary.
788**
789** If a memory allocation error occurs, return NULL.
790*/
791static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
792 struct vxworksFileId *pNew; /* search key and new file ID */
793 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
794 int n; /* Length of zAbsoluteName string */
795
796 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000797 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000798 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
799 if( pNew==0 ) return 0;
800 pNew->zCanonicalName = (char*)&pNew[1];
801 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
802 n = vxworksSimplifyName(pNew->zCanonicalName, n);
803
804 /* Search for an existing entry that matching the canonical name.
805 ** If found, increment the reference count and return a pointer to
806 ** the existing file ID.
807 */
808 unixEnterMutex();
809 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
810 if( pCandidate->nName==n
811 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
812 ){
813 sqlite3_free(pNew);
814 pCandidate->nRef++;
815 unixLeaveMutex();
816 return pCandidate;
817 }
818 }
819
820 /* No match was found. We will make a new file ID */
821 pNew->nRef = 1;
822 pNew->nName = n;
823 pNew->pNext = vxworksFileList;
824 vxworksFileList = pNew;
825 unixLeaveMutex();
826 return pNew;
827}
828
829/*
830** Decrement the reference count on a vxworksFileId object. Free
831** the object when the reference count reaches zero.
832*/
833static void vxworksReleaseFileId(struct vxworksFileId *pId){
834 unixEnterMutex();
835 assert( pId->nRef>0 );
836 pId->nRef--;
837 if( pId->nRef==0 ){
838 struct vxworksFileId **pp;
839 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
840 assert( *pp==pId );
841 *pp = pId->pNext;
842 sqlite3_free(pId);
843 }
844 unixLeaveMutex();
845}
846#endif /* OS_VXWORKS */
847/*************** End of Unique File ID Utility Used By VxWorks ****************
848******************************************************************************/
849
850
851/******************************************************************************
852*************************** Posix Advisory Locking ****************************
853**
drh9b35ea62008-11-29 02:20:26 +0000854** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000855** section 6.5.2.2 lines 483 through 490 specify that when a process
856** sets or clears a lock, that operation overrides any prior locks set
857** by the same process. It does not explicitly say so, but this implies
858** that it overrides locks set by the same process using a different
859** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000860**
861** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000862** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
863**
864** Suppose ./file1 and ./file2 are really the same file (because
865** one is a hard or symbolic link to the other) then if you set
866** an exclusive lock on fd1, then try to get an exclusive lock
867** on fd2, it works. I would have expected the second lock to
868** fail since there was already a lock on the file due to fd1.
869** But not so. Since both locks came from the same process, the
870** second overrides the first, even though they were on different
871** file descriptors opened on different file names.
872**
drh734c9862008-11-28 15:37:20 +0000873** This means that we cannot use POSIX locks to synchronize file access
874** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000875** to synchronize access for threads in separate processes, but not
876** threads within the same process.
877**
878** To work around the problem, SQLite has to manage file locks internally
879** on its own. Whenever a new database is opened, we have to find the
880** specific inode of the database file (the inode is determined by the
881** st_dev and st_ino fields of the stat structure that fstat() fills in)
882** and check for locks already existing on that inode. When locks are
883** created or removed, we have to look at our own internal record of the
884** locks to see if another thread has previously set a lock on that same
885** inode.
886**
drh9b35ea62008-11-29 02:20:26 +0000887** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
888** For VxWorks, we have to use the alternative unique ID system based on
889** canonical filename and implemented in the previous division.)
890**
danielk1977ad94b582007-08-20 06:44:22 +0000891** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000892** descriptor. It is now a structure that holds the integer file
893** descriptor and a pointer to a structure that describes the internal
894** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000895** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000896** point to the same locking structure. The locking structure keeps
897** a reference count (so we will know when to delete it) and a "cnt"
898** field that tells us its internal lock status. cnt==0 means the
899** file is unlocked. cnt==-1 means the file has an exclusive lock.
900** cnt>0 means there are cnt shared locks on the file.
901**
902** Any attempt to lock or unlock a file first checks the locking
903** structure. The fcntl() system call is only invoked to set a
904** POSIX lock if the internal lock structure transitions between
905** a locked and an unlocked state.
906**
drh734c9862008-11-28 15:37:20 +0000907** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000908**
909** If you close a file descriptor that points to a file that has locks,
910** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000911** released. To work around this problem, each unixInodeInfo object
912** maintains a count of the number of pending locks on tha inode.
913** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000914** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000915** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000916** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000917** be closed and that list is walked (and cleared) when the last lock
918** clears.
919**
drh9b35ea62008-11-29 02:20:26 +0000920** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000921**
drh9b35ea62008-11-29 02:20:26 +0000922** Many older versions of linux use the LinuxThreads library which is
923** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000924** A cannot be modified or overridden by a different thread B.
925** Only thread A can modify the lock. Locking behavior is correct
926** if the appliation uses the newer Native Posix Thread Library (NPTL)
927** on linux - with NPTL a lock created by thread A can override locks
928** in thread B. But there is no way to know at compile-time which
929** threading library is being used. So there is no way to know at
930** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000931** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000932** current process.
drh5fdae772004-06-29 03:29:00 +0000933**
drh8af6c222010-05-14 12:43:01 +0000934** SQLite used to support LinuxThreads. But support for LinuxThreads
935** was dropped beginning with version 3.7.0. SQLite will still work with
936** LinuxThreads provided that (1) there is no more than one connection
937** per database file in the same process and (2) database connections
938** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000939*/
940
941/*
942** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000943** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000944*/
945struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000946 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000947#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000948 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000949#else
drh107886a2008-11-21 22:21:50 +0000950 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000951#endif
952};
953
954/*
drhbbd42a62004-05-22 17:41:58 +0000955** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000956** inode. Or, on LinuxThreads, there is one of these structures for
957** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000958**
danielk1977ad94b582007-08-20 06:44:22 +0000959** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000960** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000961** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000962*/
drh8af6c222010-05-14 12:43:01 +0000963struct unixInodeInfo {
964 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000965 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000966 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
967 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000968 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000969 unixShmNode *pShmNode; /* Shared memory associated with this inode */
970 int nLock; /* Number of outstanding file locks */
971 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
972 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
973 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000974#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000975 unsigned long long sharedByte; /* for AFP simulated shared lock */
976#endif
drh6c7d5c52008-11-21 20:32:33 +0000977#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000978 sem_t *pSem; /* Named POSIX semaphore */
979 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000980#endif
drhbbd42a62004-05-22 17:41:58 +0000981};
982
drhda0e7682008-07-30 15:27:54 +0000983/*
drh8af6c222010-05-14 12:43:01 +0000984** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000985*/
drhd91c68f2010-05-14 14:52:25 +0000986static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000987
drh5fdae772004-06-29 03:29:00 +0000988/*
dane18d4952011-02-21 11:46:24 +0000989**
990** This function - unixLogError_x(), is only ever called via the macro
991** unixLogError().
992**
993** It is invoked after an error occurs in an OS function and errno has been
994** set. It logs a message using sqlite3_log() containing the current value of
995** errno and, if possible, the human-readable equivalent from strerror() or
996** strerror_r().
997**
998** The first argument passed to the macro should be the error code that
999** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1000** The two subsequent arguments should be the name of the OS function that
1001** failed (e.g. "unlink", "open") and the the associated file-system path,
1002** if any.
1003*/
drh0e9365c2011-03-02 02:08:13 +00001004#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1005static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001006 int errcode, /* SQLite error code */
1007 const char *zFunc, /* Name of OS function that failed */
1008 const char *zPath, /* File path associated with error */
1009 int iLine /* Source line number where error occurred */
1010){
1011 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001012 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001013
1014 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1015 ** the strerror() function to obtain the human-readable error message
1016 ** equivalent to errno. Otherwise, use strerror_r().
1017 */
1018#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1019 char aErr[80];
1020 memset(aErr, 0, sizeof(aErr));
1021 zErr = aErr;
1022
1023 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1024 ** assume that the system provides the the GNU version of strerror_r() that
1025 ** returns a pointer to a buffer containing the error message. That pointer
1026 ** may point to aErr[], or it may point to some static storage somewhere.
1027 ** Otherwise, assume that the system provides the POSIX version of
1028 ** strerror_r(), which always writes an error message into aErr[].
1029 **
1030 ** If the code incorrectly assumes that it is the POSIX version that is
1031 ** available, the error message will often be an empty string. Not a
1032 ** huge problem. Incorrectly concluding that the GNU version is available
1033 ** could lead to a segfault though.
1034 */
1035#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1036 zErr =
1037# endif
drh0e9365c2011-03-02 02:08:13 +00001038 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001039
1040#elif SQLITE_THREADSAFE
1041 /* This is a threadsafe build, but strerror_r() is not available. */
1042 zErr = "";
1043#else
1044 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001045 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001046#endif
1047
1048 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001049 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001050 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001051 "os_unix.c:%d: (%d) %s(%s) - %s",
1052 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001053 );
1054
1055 return errcode;
1056}
1057
drh0e9365c2011-03-02 02:08:13 +00001058/*
1059** Close a file descriptor.
1060**
1061** We assume that close() almost always works, since it is only in a
1062** very sick application or on a very sick platform that it might fail.
1063** If it does fail, simply leak the file descriptor, but do log the
1064** error.
1065**
1066** Note that it is not safe to retry close() after EINTR since the
1067** file descriptor might have already been reused by another thread.
1068** So we don't even try to recover from an EINTR. Just log the error
1069** and move on.
1070*/
1071static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001072 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001073 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1074 pFile ? pFile->zPath : 0, lineno);
1075 }
1076}
dane18d4952011-02-21 11:46:24 +00001077
1078/*
danb0ac3e32010-06-16 10:55:42 +00001079** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001080*/
drh0e9365c2011-03-02 02:08:13 +00001081static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001082 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001083 UnixUnusedFd *p;
1084 UnixUnusedFd *pNext;
1085 for(p=pInode->pUnused; p; p=pNext){
1086 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001087 robust_close(pFile, p->fd, __LINE__);
1088 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001089 }
drh0e9365c2011-03-02 02:08:13 +00001090 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001091}
1092
1093/*
drh8af6c222010-05-14 12:43:01 +00001094** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001095**
1096** The mutex entered using the unixEnterMutex() function must be held
1097** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001098*/
danb0ac3e32010-06-16 10:55:42 +00001099static void releaseInodeInfo(unixFile *pFile){
1100 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001101 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001102 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001103 pInode->nRef--;
1104 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001105 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001106 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001107 if( pInode->pPrev ){
1108 assert( pInode->pPrev->pNext==pInode );
1109 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001110 }else{
drh8af6c222010-05-14 12:43:01 +00001111 assert( inodeList==pInode );
1112 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001113 }
drh8af6c222010-05-14 12:43:01 +00001114 if( pInode->pNext ){
1115 assert( pInode->pNext->pPrev==pInode );
1116 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001117 }
drh8af6c222010-05-14 12:43:01 +00001118 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001119 }
drhbbd42a62004-05-22 17:41:58 +00001120 }
1121}
1122
1123/*
drh8af6c222010-05-14 12:43:01 +00001124** Given a file descriptor, locate the unixInodeInfo object that
1125** describes that file descriptor. Create a new one if necessary. The
1126** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001127**
dan9359c7b2009-08-21 08:29:10 +00001128** The mutex entered using the unixEnterMutex() function must be held
1129** when this function is called.
1130**
drh6c7d5c52008-11-21 20:32:33 +00001131** Return an appropriate error code.
1132*/
drh8af6c222010-05-14 12:43:01 +00001133static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001134 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001135 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001136){
1137 int rc; /* System call return code */
1138 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001139 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1140 struct stat statbuf; /* Low-level file information */
1141 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001142
dan9359c7b2009-08-21 08:29:10 +00001143 assert( unixMutexHeld() );
1144
drh6c7d5c52008-11-21 20:32:33 +00001145 /* Get low-level information about the file that we can used to
1146 ** create a unique name for the file.
1147 */
1148 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001149 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001150 if( rc!=0 ){
1151 pFile->lastErrno = errno;
1152#ifdef EOVERFLOW
1153 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1154#endif
1155 return SQLITE_IOERR;
1156 }
1157
drheb0d74f2009-02-03 15:27:02 +00001158#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001159 /* On OS X on an msdos filesystem, the inode number is reported
1160 ** incorrectly for zero-size files. See ticket #3260. To work
1161 ** around this problem (we consider it a bug in OS X, not SQLite)
1162 ** we always increase the file size to 1 by writing a single byte
1163 ** prior to accessing the inode number. The one byte written is
1164 ** an ASCII 'S' character which also happens to be the first byte
1165 ** in the header of every SQLite database. In this way, if there
1166 ** is a race condition such that another thread has already populated
1167 ** the first page of the database, no damage is done.
1168 */
drh7ed97b92010-01-20 13:07:21 +00001169 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001170 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001171 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001172 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001173 return SQLITE_IOERR;
1174 }
drh99ab3b12011-03-02 15:09:07 +00001175 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001176 if( rc!=0 ){
1177 pFile->lastErrno = errno;
1178 return SQLITE_IOERR;
1179 }
1180 }
drheb0d74f2009-02-03 15:27:02 +00001181#endif
drh6c7d5c52008-11-21 20:32:33 +00001182
drh8af6c222010-05-14 12:43:01 +00001183 memset(&fileId, 0, sizeof(fileId));
1184 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001185#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001186 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001187#else
drh8af6c222010-05-14 12:43:01 +00001188 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001189#endif
drh8af6c222010-05-14 12:43:01 +00001190 pInode = inodeList;
1191 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1192 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001193 }
drh8af6c222010-05-14 12:43:01 +00001194 if( pInode==0 ){
1195 pInode = sqlite3_malloc( sizeof(*pInode) );
1196 if( pInode==0 ){
1197 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001198 }
drh8af6c222010-05-14 12:43:01 +00001199 memset(pInode, 0, sizeof(*pInode));
1200 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1201 pInode->nRef = 1;
1202 pInode->pNext = inodeList;
1203 pInode->pPrev = 0;
1204 if( inodeList ) inodeList->pPrev = pInode;
1205 inodeList = pInode;
1206 }else{
1207 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001208 }
drh8af6c222010-05-14 12:43:01 +00001209 *ppInode = pInode;
1210 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001211}
drh6c7d5c52008-11-21 20:32:33 +00001212
aswift5b1a2562008-08-22 00:22:35 +00001213
1214/*
danielk197713adf8a2004-06-03 16:08:41 +00001215** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001216** file by this or any other process. If such a lock is held, set *pResOut
1217** to a non-zero value otherwise *pResOut is set to zero. The return value
1218** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001219*/
danielk1977861f7452008-06-05 11:39:11 +00001220static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001221 int rc = SQLITE_OK;
1222 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001223 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001224
danielk1977861f7452008-06-05 11:39:11 +00001225 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1226
drh054889e2005-11-30 03:20:31 +00001227 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001228 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001229
1230 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001231 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001232 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001233 }
1234
drh2ac3ee92004-06-07 16:27:46 +00001235 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001236 */
danielk197709480a92009-02-09 05:32:32 +00001237#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001238 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001239 struct flock lock;
1240 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001241 lock.l_start = RESERVED_BYTE;
1242 lock.l_len = 1;
1243 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001244 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1245 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1246 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001247 } else if( lock.l_type!=F_UNLCK ){
1248 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001249 }
1250 }
danielk197709480a92009-02-09 05:32:32 +00001251#endif
danielk197713adf8a2004-06-03 16:08:41 +00001252
drh6c7d5c52008-11-21 20:32:33 +00001253 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001254 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001255
aswift5b1a2562008-08-22 00:22:35 +00001256 *pResOut = reserved;
1257 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001258}
1259
1260/*
drha7e61d82011-03-12 17:02:57 +00001261** Attempt to set a system-lock on the file pFile. The lock is
1262** described by pLock.
1263**
drh77197112011-03-15 19:08:48 +00001264** If the pFile was opened read/write from unix-excl, then the only lock
1265** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001266** the first time any lock is attempted. All subsequent system locking
1267** operations become no-ops. Locking operations still happen internally,
1268** in order to coordinate access between separate database connections
1269** within this process, but all of that is handled in memory and the
1270** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001271**
1272** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1273** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1274** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001275**
1276** Zero is returned if the call completes successfully, or -1 if a call
1277** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001278*/
1279static int unixFileLock(unixFile *pFile, struct flock *pLock){
1280 int rc;
drh3cb93392011-03-12 18:10:44 +00001281 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001282 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001283 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001284 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1285 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1286 ){
drh3cb93392011-03-12 18:10:44 +00001287 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001288 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001289 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001290 lock.l_whence = SEEK_SET;
1291 lock.l_start = SHARED_FIRST;
1292 lock.l_len = SHARED_SIZE;
1293 lock.l_type = F_WRLCK;
1294 rc = osFcntl(pFile->h, F_SETLK, &lock);
1295 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001296 pInode->bProcessLock = 1;
1297 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001298 }else{
1299 rc = 0;
1300 }
1301 }else{
1302 rc = osFcntl(pFile->h, F_SETLK, pLock);
1303 }
1304 return rc;
1305}
1306
1307/*
drh308c2a52010-05-14 11:30:18 +00001308** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001309** of the following:
1310**
drh2ac3ee92004-06-07 16:27:46 +00001311** (1) SHARED_LOCK
1312** (2) RESERVED_LOCK
1313** (3) PENDING_LOCK
1314** (4) EXCLUSIVE_LOCK
1315**
drhb3e04342004-06-08 00:47:47 +00001316** Sometimes when requesting one lock state, additional lock states
1317** are inserted in between. The locking might fail on one of the later
1318** transitions leaving the lock state different from what it started but
1319** still short of its goal. The following chart shows the allowed
1320** transitions and the inserted intermediate states:
1321**
1322** UNLOCKED -> SHARED
1323** SHARED -> RESERVED
1324** SHARED -> (PENDING) -> EXCLUSIVE
1325** RESERVED -> (PENDING) -> EXCLUSIVE
1326** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001327**
drha6abd042004-06-09 17:37:22 +00001328** This routine will only increase a lock. Use the sqlite3OsUnlock()
1329** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001330*/
drh308c2a52010-05-14 11:30:18 +00001331static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001332 /* The following describes the implementation of the various locks and
1333 ** lock transitions in terms of the POSIX advisory shared and exclusive
1334 ** lock primitives (called read-locks and write-locks below, to avoid
1335 ** confusion with SQLite lock names). The algorithms are complicated
1336 ** slightly in order to be compatible with windows systems simultaneously
1337 ** accessing the same database file, in case that is ever required.
1338 **
1339 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1340 ** byte', each single bytes at well known offsets, and the 'shared byte
1341 ** range', a range of 510 bytes at a well known offset.
1342 **
1343 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1344 ** byte'. If this is successful, a random byte from the 'shared byte
1345 ** range' is read-locked and the lock on the 'pending byte' released.
1346 **
danielk197790ba3bd2004-06-25 08:32:25 +00001347 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1348 ** A RESERVED lock is implemented by grabbing a write-lock on the
1349 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001350 **
1351 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001352 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1353 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1354 ** obtained, but existing SHARED locks are allowed to persist. A process
1355 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1356 ** This property is used by the algorithm for rolling back a journal file
1357 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001358 **
danielk197790ba3bd2004-06-25 08:32:25 +00001359 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1360 ** implemented by obtaining a write-lock on the entire 'shared byte
1361 ** range'. Since all other locks require a read-lock on one of the bytes
1362 ** within this range, this ensures that no other locks are held on the
1363 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001364 **
1365 ** The reason a single byte cannot be used instead of the 'shared byte
1366 ** range' is that some versions of windows do not support read-locks. By
1367 ** locking a random byte from a range, concurrent SHARED locks may exist
1368 ** even if the locking primitive used is always a write-lock.
1369 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001370 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001371 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001372 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001373 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001374 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001375
drh054889e2005-11-30 03:20:31 +00001376 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001377 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1378 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001379 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001380
1381 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001382 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001383 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001384 */
drh308c2a52010-05-14 11:30:18 +00001385 if( pFile->eFileLock>=eFileLock ){
1386 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1387 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001388 return SQLITE_OK;
1389 }
1390
drh0c2694b2009-09-03 16:23:44 +00001391 /* Make sure the locking sequence is correct.
1392 ** (1) We never move from unlocked to anything higher than shared lock.
1393 ** (2) SQLite never explicitly requests a pendig lock.
1394 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001395 */
drh308c2a52010-05-14 11:30:18 +00001396 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1397 assert( eFileLock!=PENDING_LOCK );
1398 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001399
drh8af6c222010-05-14 12:43:01 +00001400 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001401 */
drh6c7d5c52008-11-21 20:32:33 +00001402 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001403 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001404
danielk1977ad94b582007-08-20 06:44:22 +00001405 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001406 ** handle that precludes the requested lock, return BUSY.
1407 */
drh8af6c222010-05-14 12:43:01 +00001408 if( (pFile->eFileLock!=pInode->eFileLock &&
1409 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001410 ){
1411 rc = SQLITE_BUSY;
1412 goto end_lock;
1413 }
1414
1415 /* If a SHARED lock is requested, and some thread using this PID already
1416 ** has a SHARED or RESERVED lock, then increment reference counts and
1417 ** return SQLITE_OK.
1418 */
drh308c2a52010-05-14 11:30:18 +00001419 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001420 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001421 assert( eFileLock==SHARED_LOCK );
1422 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001423 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001424 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001425 pInode->nShared++;
1426 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001427 goto end_lock;
1428 }
1429
danielk19779a1d0ab2004-06-01 14:09:28 +00001430
drh3cde3bb2004-06-12 02:17:14 +00001431 /* A PENDING lock is needed before acquiring a SHARED lock and before
1432 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1433 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001434 */
drh0c2694b2009-09-03 16:23:44 +00001435 lock.l_len = 1L;
1436 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001437 if( eFileLock==SHARED_LOCK
1438 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001439 ){
drh308c2a52010-05-14 11:30:18 +00001440 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001441 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001442 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001443 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001444 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001445 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001446 pFile->lastErrno = tErrno;
1447 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001448 goto end_lock;
1449 }
drh3cde3bb2004-06-12 02:17:14 +00001450 }
1451
1452
1453 /* If control gets to this point, then actually go ahead and make
1454 ** operating system calls for the specified lock.
1455 */
drh308c2a52010-05-14 11:30:18 +00001456 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001457 assert( pInode->nShared==0 );
1458 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001459 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001460
drh2ac3ee92004-06-07 16:27:46 +00001461 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001462 lock.l_start = SHARED_FIRST;
1463 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001464 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001465 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001466 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001467 }
dan661d71a2011-03-30 19:08:03 +00001468
drh2ac3ee92004-06-07 16:27:46 +00001469 /* Drop the temporary PENDING lock */
1470 lock.l_start = PENDING_BYTE;
1471 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001472 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001473 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1474 /* This could happen with a network mount */
1475 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001476 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001477 }
dan661d71a2011-03-30 19:08:03 +00001478
1479 if( rc ){
1480 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001481 pFile->lastErrno = tErrno;
1482 }
dan661d71a2011-03-30 19:08:03 +00001483 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001484 }else{
drh308c2a52010-05-14 11:30:18 +00001485 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001486 pInode->nLock++;
1487 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001488 }
drh8af6c222010-05-14 12:43:01 +00001489 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001490 /* We are trying for an exclusive lock but another thread in this
1491 ** same process is still holding a shared lock. */
1492 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001493 }else{
drh3cde3bb2004-06-12 02:17:14 +00001494 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001495 ** assumed that there is a SHARED or greater lock on the file
1496 ** already.
1497 */
drh308c2a52010-05-14 11:30:18 +00001498 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001499 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001500
1501 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1502 if( eFileLock==RESERVED_LOCK ){
1503 lock.l_start = RESERVED_BYTE;
1504 lock.l_len = 1L;
1505 }else{
1506 lock.l_start = SHARED_FIRST;
1507 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001508 }
dan661d71a2011-03-30 19:08:03 +00001509
1510 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001511 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001512 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001513 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001514 pFile->lastErrno = tErrno;
1515 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001516 }
drhbbd42a62004-05-22 17:41:58 +00001517 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001518
drh8f941bc2009-01-14 23:03:40 +00001519
1520#ifndef NDEBUG
1521 /* Set up the transaction-counter change checking flags when
1522 ** transitioning from a SHARED to a RESERVED lock. The change
1523 ** from SHARED to RESERVED marks the beginning of a normal
1524 ** write operation (not a hot journal rollback).
1525 */
1526 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001527 && pFile->eFileLock<=SHARED_LOCK
1528 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001529 ){
1530 pFile->transCntrChng = 0;
1531 pFile->dbUpdate = 0;
1532 pFile->inNormalWrite = 1;
1533 }
1534#endif
1535
1536
danielk1977ecb2a962004-06-02 06:30:16 +00001537 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001538 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001539 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001540 }else if( eFileLock==EXCLUSIVE_LOCK ){
1541 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001542 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001543 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001544
1545end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001546 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001547 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1548 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001549 return rc;
1550}
1551
1552/*
dan08da86a2009-08-21 17:18:03 +00001553** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001554** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001555*/
1556static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001557 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001558 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001559 p->pNext = pInode->pUnused;
1560 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001561 pFile->h = -1;
1562 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001563}
1564
1565/*
drh308c2a52010-05-14 11:30:18 +00001566** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001567** must be either NO_LOCK or SHARED_LOCK.
1568**
1569** If the locking level of the file descriptor is already at or below
1570** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001571**
1572** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1573** the byte range is divided into 2 parts and the first part is unlocked then
1574** set to a read lock, then the other part is simply unlocked. This works
1575** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1576** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001577*/
drha7e61d82011-03-12 17:02:57 +00001578static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001579 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001580 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001581 struct flock lock;
1582 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001583
drh054889e2005-11-30 03:20:31 +00001584 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001585 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001586 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001587 getpid()));
drha6abd042004-06-09 17:37:22 +00001588
drh308c2a52010-05-14 11:30:18 +00001589 assert( eFileLock<=SHARED_LOCK );
1590 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001591 return SQLITE_OK;
1592 }
drh6c7d5c52008-11-21 20:32:33 +00001593 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001594 pInode = pFile->pInode;
1595 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001596 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001597 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001598
1599#ifndef NDEBUG
1600 /* When reducing a lock such that other processes can start
1601 ** reading the database file again, make sure that the
1602 ** transaction counter was updated if any part of the database
1603 ** file changed. If the transaction counter is not updated,
1604 ** other connections to the same file might not realize that
1605 ** the file has changed and hence might not know to flush their
1606 ** cache. The use of a stale cache can lead to database corruption.
1607 */
drh8f941bc2009-01-14 23:03:40 +00001608 pFile->inNormalWrite = 0;
1609#endif
1610
drh7ed97b92010-01-20 13:07:21 +00001611 /* downgrading to a shared lock on NFS involves clearing the write lock
1612 ** before establishing the readlock - to avoid a race condition we downgrade
1613 ** the lock in 2 blocks, so that part of the range will be covered by a
1614 ** write lock until the rest is covered by a read lock:
1615 ** 1: [WWWWW]
1616 ** 2: [....W]
1617 ** 3: [RRRRW]
1618 ** 4: [RRRR.]
1619 */
drh308c2a52010-05-14 11:30:18 +00001620 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001621
1622#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001623 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001624 assert( handleNFSUnlock==0 );
1625#endif
1626#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001627 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001628 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001629 off_t divSize = SHARED_SIZE - 1;
1630
1631 lock.l_type = F_UNLCK;
1632 lock.l_whence = SEEK_SET;
1633 lock.l_start = SHARED_FIRST;
1634 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001635 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001636 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001637 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001638 if( IS_LOCK_ERROR(rc) ){
1639 pFile->lastErrno = tErrno;
1640 }
1641 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001642 }
drh7ed97b92010-01-20 13:07:21 +00001643 lock.l_type = F_RDLCK;
1644 lock.l_whence = SEEK_SET;
1645 lock.l_start = SHARED_FIRST;
1646 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001647 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001648 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001649 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1650 if( IS_LOCK_ERROR(rc) ){
1651 pFile->lastErrno = tErrno;
1652 }
1653 goto end_unlock;
1654 }
1655 lock.l_type = F_UNLCK;
1656 lock.l_whence = SEEK_SET;
1657 lock.l_start = SHARED_FIRST+divSize;
1658 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001659 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001660 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001661 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001662 if( IS_LOCK_ERROR(rc) ){
1663 pFile->lastErrno = tErrno;
1664 }
1665 goto end_unlock;
1666 }
drh30f776f2011-02-25 03:25:07 +00001667 }else
1668#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1669 {
drh7ed97b92010-01-20 13:07:21 +00001670 lock.l_type = F_RDLCK;
1671 lock.l_whence = SEEK_SET;
1672 lock.l_start = SHARED_FIRST;
1673 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001674 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001675 /* In theory, the call to unixFileLock() cannot fail because another
1676 ** process is holding an incompatible lock. If it does, this
1677 ** indicates that the other process is not following the locking
1678 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1679 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1680 ** an assert to fail). */
1681 rc = SQLITE_IOERR_RDLOCK;
1682 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001683 goto end_unlock;
1684 }
drh9c105bb2004-10-02 20:38:28 +00001685 }
1686 }
drhbbd42a62004-05-22 17:41:58 +00001687 lock.l_type = F_UNLCK;
1688 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001689 lock.l_start = PENDING_BYTE;
1690 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001691 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001692 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001693 }else{
danea83bc62011-04-01 11:56:32 +00001694 rc = SQLITE_IOERR_UNLOCK;
1695 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001696 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001697 }
drhbbd42a62004-05-22 17:41:58 +00001698 }
drh308c2a52010-05-14 11:30:18 +00001699 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001700 /* Decrement the shared lock counter. Release the lock using an
1701 ** OS call only when all threads in this same process have released
1702 ** the lock.
1703 */
drh8af6c222010-05-14 12:43:01 +00001704 pInode->nShared--;
1705 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001706 lock.l_type = F_UNLCK;
1707 lock.l_whence = SEEK_SET;
1708 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001709 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001710 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001711 }else{
danea83bc62011-04-01 11:56:32 +00001712 rc = SQLITE_IOERR_UNLOCK;
1713 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001714 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001715 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001716 }
drha6abd042004-06-09 17:37:22 +00001717 }
1718
drhbbd42a62004-05-22 17:41:58 +00001719 /* Decrement the count of locks against this same file. When the
1720 ** count reaches zero, close any other file descriptors whose close
1721 ** was deferred because of outstanding locks.
1722 */
drh8af6c222010-05-14 12:43:01 +00001723 pInode->nLock--;
1724 assert( pInode->nLock>=0 );
1725 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001726 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001727 }
1728 }
aswift5b1a2562008-08-22 00:22:35 +00001729
1730end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001731 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001732 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001733 return rc;
drhbbd42a62004-05-22 17:41:58 +00001734}
1735
1736/*
drh308c2a52010-05-14 11:30:18 +00001737** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001738** must be either NO_LOCK or SHARED_LOCK.
1739**
1740** If the locking level of the file descriptor is already at or below
1741** the requested locking level, this routine is a no-op.
1742*/
drh308c2a52010-05-14 11:30:18 +00001743static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001744 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001745}
1746
1747/*
danielk1977e339d652008-06-28 11:23:00 +00001748** This function performs the parts of the "close file" operation
1749** common to all locking schemes. It closes the directory and file
1750** handles, if they are valid, and sets all fields of the unixFile
1751** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001752**
1753** It is *not* necessary to hold the mutex when this routine is called,
1754** even on VxWorks. A mutex will be acquired on VxWorks by the
1755** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001756*/
1757static int closeUnixFile(sqlite3_file *id){
1758 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001759 if( pFile->h>=0 ){
1760 robust_close(pFile, pFile->h, __LINE__);
1761 pFile->h = -1;
1762 }
1763#if OS_VXWORKS
1764 if( pFile->pId ){
1765 if( pFile->isDelete ){
drh036ac7f2011-08-08 23:18:05 +00001766 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001767 }
1768 vxworksReleaseFileId(pFile->pId);
1769 pFile->pId = 0;
1770 }
1771#endif
1772 OSTRACE(("CLOSE %-3d\n", pFile->h));
1773 OpenCounter(-1);
1774 sqlite3_free(pFile->pUnused);
1775 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001776 return SQLITE_OK;
1777}
1778
1779/*
danielk1977e3026632004-06-22 11:29:02 +00001780** Close a file.
1781*/
danielk197762079062007-08-15 17:08:46 +00001782static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001783 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001784 unixFile *pFile = (unixFile *)id;
1785 unixUnlock(id, NO_LOCK);
1786 unixEnterMutex();
1787
1788 /* unixFile.pInode is always valid here. Otherwise, a different close
1789 ** routine (e.g. nolockClose()) would be called instead.
1790 */
1791 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1792 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1793 /* If there are outstanding locks, do not actually close the file just
1794 ** yet because that would clear those locks. Instead, add the file
1795 ** descriptor to pInode->pUnused list. It will be automatically closed
1796 ** when the last lock is cleared.
1797 */
1798 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001799 }
dan661d71a2011-03-30 19:08:03 +00001800 releaseInodeInfo(pFile);
1801 rc = closeUnixFile(id);
1802 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001803 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001804}
1805
drh734c9862008-11-28 15:37:20 +00001806/************** End of the posix advisory lock implementation *****************
1807******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001808
drh734c9862008-11-28 15:37:20 +00001809/******************************************************************************
1810****************************** No-op Locking **********************************
1811**
1812** Of the various locking implementations available, this is by far the
1813** simplest: locking is ignored. No attempt is made to lock the database
1814** file for reading or writing.
1815**
1816** This locking mode is appropriate for use on read-only databases
1817** (ex: databases that are burned into CD-ROM, for example.) It can
1818** also be used if the application employs some external mechanism to
1819** prevent simultaneous access of the same database by two or more
1820** database connections. But there is a serious risk of database
1821** corruption if this locking mode is used in situations where multiple
1822** database connections are accessing the same database file at the same
1823** time and one or more of those connections are writing.
1824*/
drhbfe66312006-10-03 17:40:40 +00001825
drh734c9862008-11-28 15:37:20 +00001826static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1827 UNUSED_PARAMETER(NotUsed);
1828 *pResOut = 0;
1829 return SQLITE_OK;
1830}
drh734c9862008-11-28 15:37:20 +00001831static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1832 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1833 return SQLITE_OK;
1834}
drh734c9862008-11-28 15:37:20 +00001835static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1836 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1837 return SQLITE_OK;
1838}
1839
1840/*
drh9b35ea62008-11-29 02:20:26 +00001841** Close the file.
drh734c9862008-11-28 15:37:20 +00001842*/
1843static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001844 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001845}
1846
1847/******************* End of the no-op lock implementation *********************
1848******************************************************************************/
1849
1850/******************************************************************************
1851************************* Begin dot-file Locking ******************************
1852**
drh0c2694b2009-09-03 16:23:44 +00001853** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001854** files (really a directory) to control access to the database. This works
1855** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001856**
1857** (1) There is zero concurrency. A single reader blocks all other
1858** connections from reading or writing the database.
1859**
1860** (2) An application crash or power loss can leave stale lock files
1861** sitting around that need to be cleared manually.
1862**
1863** Nevertheless, a dotlock is an appropriate locking mode for use if no
1864** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001865**
drh9ef6bc42011-11-04 02:24:02 +00001866** Dotfile locking works by creating a subdirectory in the same directory as
1867** the database and with the same name but with a ".lock" extension added.
1868** The existance of a lock directory implies an EXCLUSIVE lock. All other
1869** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001870*/
1871
1872/*
1873** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001874** lock directory.
drh734c9862008-11-28 15:37:20 +00001875*/
1876#define DOTLOCK_SUFFIX ".lock"
1877
drh7708e972008-11-29 00:56:52 +00001878/*
1879** This routine checks if there is a RESERVED lock held on the specified
1880** file by this or any other process. If such a lock is held, set *pResOut
1881** to a non-zero value otherwise *pResOut is set to zero. The return value
1882** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1883**
1884** In dotfile locking, either a lock exists or it does not. So in this
1885** variation of CheckReservedLock(), *pResOut is set to true if any lock
1886** is held on the file and false if the file is unlocked.
1887*/
drh734c9862008-11-28 15:37:20 +00001888static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1889 int rc = SQLITE_OK;
1890 int reserved = 0;
1891 unixFile *pFile = (unixFile*)id;
1892
1893 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1894
1895 assert( pFile );
1896
1897 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001898 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001899 /* Either this connection or some other connection in the same process
1900 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001901 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001902 }else{
1903 /* The lock is held if and only if the lockfile exists */
1904 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001905 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001906 }
drh308c2a52010-05-14 11:30:18 +00001907 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001908 *pResOut = reserved;
1909 return rc;
1910}
1911
drh7708e972008-11-29 00:56:52 +00001912/*
drh308c2a52010-05-14 11:30:18 +00001913** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001914** of the following:
1915**
1916** (1) SHARED_LOCK
1917** (2) RESERVED_LOCK
1918** (3) PENDING_LOCK
1919** (4) EXCLUSIVE_LOCK
1920**
1921** Sometimes when requesting one lock state, additional lock states
1922** are inserted in between. The locking might fail on one of the later
1923** transitions leaving the lock state different from what it started but
1924** still short of its goal. The following chart shows the allowed
1925** transitions and the inserted intermediate states:
1926**
1927** UNLOCKED -> SHARED
1928** SHARED -> RESERVED
1929** SHARED -> (PENDING) -> EXCLUSIVE
1930** RESERVED -> (PENDING) -> EXCLUSIVE
1931** PENDING -> EXCLUSIVE
1932**
1933** This routine will only increase a lock. Use the sqlite3OsUnlock()
1934** routine to lower a locking level.
1935**
1936** With dotfile locking, we really only support state (4): EXCLUSIVE.
1937** But we track the other locking levels internally.
1938*/
drh308c2a52010-05-14 11:30:18 +00001939static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001940 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001941 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001942 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001943
drh7708e972008-11-29 00:56:52 +00001944
1945 /* If we have any lock, then the lock file already exists. All we have
1946 ** to do is adjust our internal record of the lock level.
1947 */
drh308c2a52010-05-14 11:30:18 +00001948 if( pFile->eFileLock > NO_LOCK ){
1949 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001950 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001951#ifdef HAVE_UTIME
1952 utime(zLockFile, NULL);
1953#else
drh734c9862008-11-28 15:37:20 +00001954 utimes(zLockFile, NULL);
1955#endif
drh7708e972008-11-29 00:56:52 +00001956 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001957 }
1958
1959 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00001960 rc = osMkdir(zLockFile, 0777);
1961 if( rc<0 ){
1962 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00001963 int tErrno = errno;
1964 if( EEXIST == tErrno ){
1965 rc = SQLITE_BUSY;
1966 } else {
1967 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1968 if( IS_LOCK_ERROR(rc) ){
1969 pFile->lastErrno = tErrno;
1970 }
1971 }
drh7708e972008-11-29 00:56:52 +00001972 return rc;
drh734c9862008-11-28 15:37:20 +00001973 }
drh734c9862008-11-28 15:37:20 +00001974
1975 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001976 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001977 return rc;
1978}
1979
drh7708e972008-11-29 00:56:52 +00001980/*
drh308c2a52010-05-14 11:30:18 +00001981** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001982** must be either NO_LOCK or SHARED_LOCK.
1983**
1984** If the locking level of the file descriptor is already at or below
1985** the requested locking level, this routine is a no-op.
1986**
1987** When the locking level reaches NO_LOCK, delete the lock file.
1988*/
drh308c2a52010-05-14 11:30:18 +00001989static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001990 unixFile *pFile = (unixFile*)id;
1991 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00001992 int rc;
drh734c9862008-11-28 15:37:20 +00001993
1994 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001995 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1996 pFile->eFileLock, getpid()));
1997 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001998
1999 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002000 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002001 return SQLITE_OK;
2002 }
drh7708e972008-11-29 00:56:52 +00002003
2004 /* To downgrade to shared, simply update our internal notion of the
2005 ** lock state. No need to mess with the file on disk.
2006 */
drh308c2a52010-05-14 11:30:18 +00002007 if( eFileLock==SHARED_LOCK ){
2008 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002009 return SQLITE_OK;
2010 }
2011
drh7708e972008-11-29 00:56:52 +00002012 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002013 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002014 rc = osRmdir(zLockFile);
2015 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2016 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002017 int rc = 0;
2018 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002019 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002020 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002021 }
2022 if( IS_LOCK_ERROR(rc) ){
2023 pFile->lastErrno = tErrno;
2024 }
2025 return rc;
2026 }
drh308c2a52010-05-14 11:30:18 +00002027 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002028 return SQLITE_OK;
2029}
2030
2031/*
drh9b35ea62008-11-29 02:20:26 +00002032** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002033*/
2034static int dotlockClose(sqlite3_file *id) {
2035 int rc;
2036 if( id ){
2037 unixFile *pFile = (unixFile*)id;
2038 dotlockUnlock(id, NO_LOCK);
2039 sqlite3_free(pFile->lockingContext);
2040 }
drh734c9862008-11-28 15:37:20 +00002041 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002042 return rc;
2043}
2044/****************** End of the dot-file lock implementation *******************
2045******************************************************************************/
2046
2047/******************************************************************************
2048************************** Begin flock Locking ********************************
2049**
2050** Use the flock() system call to do file locking.
2051**
drh6b9d6dd2008-12-03 19:34:47 +00002052** flock() locking is like dot-file locking in that the various
2053** fine-grain locking levels supported by SQLite are collapsed into
2054** a single exclusive lock. In other words, SHARED, RESERVED, and
2055** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2056** still works when you do this, but concurrency is reduced since
2057** only a single process can be reading the database at a time.
2058**
drh734c9862008-11-28 15:37:20 +00002059** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2060** compiling for VXWORKS.
2061*/
2062#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002063
drh6b9d6dd2008-12-03 19:34:47 +00002064/*
drhff812312011-02-23 13:33:46 +00002065** Retry flock() calls that fail with EINTR
2066*/
2067#ifdef EINTR
2068static int robust_flock(int fd, int op){
2069 int rc;
2070 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2071 return rc;
2072}
2073#else
drh5c819272011-02-23 14:00:12 +00002074# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002075#endif
2076
2077
2078/*
drh6b9d6dd2008-12-03 19:34:47 +00002079** This routine checks if there is a RESERVED lock held on the specified
2080** file by this or any other process. If such a lock is held, set *pResOut
2081** to a non-zero value otherwise *pResOut is set to zero. The return value
2082** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2083*/
drh734c9862008-11-28 15:37:20 +00002084static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2085 int rc = SQLITE_OK;
2086 int reserved = 0;
2087 unixFile *pFile = (unixFile*)id;
2088
2089 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2090
2091 assert( pFile );
2092
2093 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002094 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002095 reserved = 1;
2096 }
2097
2098 /* Otherwise see if some other process holds it. */
2099 if( !reserved ){
2100 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002101 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002102 if( !lrc ){
2103 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002104 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002105 if ( lrc ) {
2106 int tErrno = errno;
2107 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002108 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002109 if( IS_LOCK_ERROR(lrc) ){
2110 pFile->lastErrno = tErrno;
2111 rc = lrc;
2112 }
2113 }
2114 } else {
2115 int tErrno = errno;
2116 reserved = 1;
2117 /* someone else might have it reserved */
2118 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2119 if( IS_LOCK_ERROR(lrc) ){
2120 pFile->lastErrno = tErrno;
2121 rc = lrc;
2122 }
2123 }
2124 }
drh308c2a52010-05-14 11:30:18 +00002125 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002126
2127#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2128 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2129 rc = SQLITE_OK;
2130 reserved=1;
2131 }
2132#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2133 *pResOut = reserved;
2134 return rc;
2135}
2136
drh6b9d6dd2008-12-03 19:34:47 +00002137/*
drh308c2a52010-05-14 11:30:18 +00002138** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002139** of the following:
2140**
2141** (1) SHARED_LOCK
2142** (2) RESERVED_LOCK
2143** (3) PENDING_LOCK
2144** (4) EXCLUSIVE_LOCK
2145**
2146** Sometimes when requesting one lock state, additional lock states
2147** are inserted in between. The locking might fail on one of the later
2148** transitions leaving the lock state different from what it started but
2149** still short of its goal. The following chart shows the allowed
2150** transitions and the inserted intermediate states:
2151**
2152** UNLOCKED -> SHARED
2153** SHARED -> RESERVED
2154** SHARED -> (PENDING) -> EXCLUSIVE
2155** RESERVED -> (PENDING) -> EXCLUSIVE
2156** PENDING -> EXCLUSIVE
2157**
2158** flock() only really support EXCLUSIVE locks. We track intermediate
2159** lock states in the sqlite3_file structure, but all locks SHARED or
2160** above are really EXCLUSIVE locks and exclude all other processes from
2161** access the file.
2162**
2163** This routine will only increase a lock. Use the sqlite3OsUnlock()
2164** routine to lower a locking level.
2165*/
drh308c2a52010-05-14 11:30:18 +00002166static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002167 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002168 unixFile *pFile = (unixFile*)id;
2169
2170 assert( pFile );
2171
2172 /* if we already have a lock, it is exclusive.
2173 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002174 if (pFile->eFileLock > NO_LOCK) {
2175 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002176 return SQLITE_OK;
2177 }
2178
2179 /* grab an exclusive lock */
2180
drhff812312011-02-23 13:33:46 +00002181 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002182 int tErrno = errno;
2183 /* didn't get, must be busy */
2184 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2185 if( IS_LOCK_ERROR(rc) ){
2186 pFile->lastErrno = tErrno;
2187 }
2188 } else {
2189 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002190 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002191 }
drh308c2a52010-05-14 11:30:18 +00002192 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2193 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002194#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2195 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2196 rc = SQLITE_BUSY;
2197 }
2198#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2199 return rc;
2200}
2201
drh6b9d6dd2008-12-03 19:34:47 +00002202
2203/*
drh308c2a52010-05-14 11:30:18 +00002204** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002205** must be either NO_LOCK or SHARED_LOCK.
2206**
2207** If the locking level of the file descriptor is already at or below
2208** the requested locking level, this routine is a no-op.
2209*/
drh308c2a52010-05-14 11:30:18 +00002210static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002211 unixFile *pFile = (unixFile*)id;
2212
2213 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002214 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2215 pFile->eFileLock, getpid()));
2216 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002217
2218 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002219 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002220 return SQLITE_OK;
2221 }
2222
2223 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002224 if (eFileLock==SHARED_LOCK) {
2225 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002226 return SQLITE_OK;
2227 }
2228
2229 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002230 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002231#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002232 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002233#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002234 return SQLITE_IOERR_UNLOCK;
2235 }else{
drh308c2a52010-05-14 11:30:18 +00002236 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002237 return SQLITE_OK;
2238 }
2239}
2240
2241/*
2242** Close a file.
2243*/
2244static int flockClose(sqlite3_file *id) {
2245 if( id ){
2246 flockUnlock(id, NO_LOCK);
2247 }
2248 return closeUnixFile(id);
2249}
2250
2251#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2252
2253/******************* End of the flock lock implementation *********************
2254******************************************************************************/
2255
2256/******************************************************************************
2257************************ Begin Named Semaphore Locking ************************
2258**
2259** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002260**
2261** Semaphore locking is like dot-lock and flock in that it really only
2262** supports EXCLUSIVE locking. Only a single process can read or write
2263** the database file at a time. This reduces potential concurrency, but
2264** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002265*/
2266#if OS_VXWORKS
2267
drh6b9d6dd2008-12-03 19:34:47 +00002268/*
2269** This routine checks if there is a RESERVED lock held on the specified
2270** file by this or any other process. If such a lock is held, set *pResOut
2271** to a non-zero value otherwise *pResOut is set to zero. The return value
2272** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2273*/
drh734c9862008-11-28 15:37:20 +00002274static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2275 int rc = SQLITE_OK;
2276 int reserved = 0;
2277 unixFile *pFile = (unixFile*)id;
2278
2279 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2280
2281 assert( pFile );
2282
2283 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002284 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002285 reserved = 1;
2286 }
2287
2288 /* Otherwise see if some other process holds it. */
2289 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002290 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002291 struct stat statBuf;
2292
2293 if( sem_trywait(pSem)==-1 ){
2294 int tErrno = errno;
2295 if( EAGAIN != tErrno ){
2296 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2297 pFile->lastErrno = tErrno;
2298 } else {
2299 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002300 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002301 }
2302 }else{
2303 /* we could have it if we want it */
2304 sem_post(pSem);
2305 }
2306 }
drh308c2a52010-05-14 11:30:18 +00002307 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002308
2309 *pResOut = reserved;
2310 return rc;
2311}
2312
drh6b9d6dd2008-12-03 19:34:47 +00002313/*
drh308c2a52010-05-14 11:30:18 +00002314** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002315** of the following:
2316**
2317** (1) SHARED_LOCK
2318** (2) RESERVED_LOCK
2319** (3) PENDING_LOCK
2320** (4) EXCLUSIVE_LOCK
2321**
2322** Sometimes when requesting one lock state, additional lock states
2323** are inserted in between. The locking might fail on one of the later
2324** transitions leaving the lock state different from what it started but
2325** still short of its goal. The following chart shows the allowed
2326** transitions and the inserted intermediate states:
2327**
2328** UNLOCKED -> SHARED
2329** SHARED -> RESERVED
2330** SHARED -> (PENDING) -> EXCLUSIVE
2331** RESERVED -> (PENDING) -> EXCLUSIVE
2332** PENDING -> EXCLUSIVE
2333**
2334** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2335** lock states in the sqlite3_file structure, but all locks SHARED or
2336** above are really EXCLUSIVE locks and exclude all other processes from
2337** access the file.
2338**
2339** This routine will only increase a lock. Use the sqlite3OsUnlock()
2340** routine to lower a locking level.
2341*/
drh308c2a52010-05-14 11:30:18 +00002342static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002343 unixFile *pFile = (unixFile*)id;
2344 int fd;
drh8af6c222010-05-14 12:43:01 +00002345 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002346 int rc = SQLITE_OK;
2347
2348 /* if we already have a lock, it is exclusive.
2349 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002350 if (pFile->eFileLock > NO_LOCK) {
2351 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002352 rc = SQLITE_OK;
2353 goto sem_end_lock;
2354 }
2355
2356 /* lock semaphore now but bail out when already locked. */
2357 if( sem_trywait(pSem)==-1 ){
2358 rc = SQLITE_BUSY;
2359 goto sem_end_lock;
2360 }
2361
2362 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002363 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002364
2365 sem_end_lock:
2366 return rc;
2367}
2368
drh6b9d6dd2008-12-03 19:34:47 +00002369/*
drh308c2a52010-05-14 11:30:18 +00002370** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002371** must be either NO_LOCK or SHARED_LOCK.
2372**
2373** If the locking level of the file descriptor is already at or below
2374** the requested locking level, this routine is a no-op.
2375*/
drh308c2a52010-05-14 11:30:18 +00002376static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002377 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002378 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002379
2380 assert( pFile );
2381 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002382 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2383 pFile->eFileLock, getpid()));
2384 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002385
2386 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002387 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002388 return SQLITE_OK;
2389 }
2390
2391 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002392 if (eFileLock==SHARED_LOCK) {
2393 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002394 return SQLITE_OK;
2395 }
2396
2397 /* no, really unlock. */
2398 if ( sem_post(pSem)==-1 ) {
2399 int rc, tErrno = errno;
2400 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2401 if( IS_LOCK_ERROR(rc) ){
2402 pFile->lastErrno = tErrno;
2403 }
2404 return rc;
2405 }
drh308c2a52010-05-14 11:30:18 +00002406 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002407 return SQLITE_OK;
2408}
2409
2410/*
2411 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002412 */
drh734c9862008-11-28 15:37:20 +00002413static int semClose(sqlite3_file *id) {
2414 if( id ){
2415 unixFile *pFile = (unixFile*)id;
2416 semUnlock(id, NO_LOCK);
2417 assert( pFile );
2418 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002419 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002420 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002421 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002422 }
2423 return SQLITE_OK;
2424}
2425
2426#endif /* OS_VXWORKS */
2427/*
2428** Named semaphore locking is only available on VxWorks.
2429**
2430*************** End of the named semaphore lock implementation ****************
2431******************************************************************************/
2432
2433
2434/******************************************************************************
2435*************************** Begin AFP Locking *********************************
2436**
2437** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2438** on Apple Macintosh computers - both OS9 and OSX.
2439**
2440** Third-party implementations of AFP are available. But this code here
2441** only works on OSX.
2442*/
2443
drhd2cb50b2009-01-09 21:41:17 +00002444#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002445/*
2446** The afpLockingContext structure contains all afp lock specific state
2447*/
drhbfe66312006-10-03 17:40:40 +00002448typedef struct afpLockingContext afpLockingContext;
2449struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002450 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002451 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002452};
2453
2454struct ByteRangeLockPB2
2455{
2456 unsigned long long offset; /* offset to first byte to lock */
2457 unsigned long long length; /* nbr of bytes to lock */
2458 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2459 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2460 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2461 int fd; /* file desc to assoc this lock with */
2462};
2463
drhfd131da2007-08-07 17:13:03 +00002464#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002465
drh6b9d6dd2008-12-03 19:34:47 +00002466/*
2467** This is a utility for setting or clearing a bit-range lock on an
2468** AFP filesystem.
2469**
2470** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2471*/
2472static int afpSetLock(
2473 const char *path, /* Name of the file to be locked or unlocked */
2474 unixFile *pFile, /* Open file descriptor on path */
2475 unsigned long long offset, /* First byte to be locked */
2476 unsigned long long length, /* Number of bytes to lock */
2477 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002478){
drh6b9d6dd2008-12-03 19:34:47 +00002479 struct ByteRangeLockPB2 pb;
2480 int err;
drhbfe66312006-10-03 17:40:40 +00002481
2482 pb.unLockFlag = setLockFlag ? 0 : 1;
2483 pb.startEndFlag = 0;
2484 pb.offset = offset;
2485 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002486 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002487
drh308c2a52010-05-14 11:30:18 +00002488 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002489 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002490 offset, length));
drhbfe66312006-10-03 17:40:40 +00002491 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2492 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002493 int rc;
2494 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002495 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2496 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002497#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2498 rc = SQLITE_BUSY;
2499#else
drh734c9862008-11-28 15:37:20 +00002500 rc = sqliteErrorFromPosixError(tErrno,
2501 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002502#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002503 if( IS_LOCK_ERROR(rc) ){
2504 pFile->lastErrno = tErrno;
2505 }
2506 return rc;
drhbfe66312006-10-03 17:40:40 +00002507 } else {
aswift5b1a2562008-08-22 00:22:35 +00002508 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002509 }
2510}
2511
drh6b9d6dd2008-12-03 19:34:47 +00002512/*
2513** This routine checks if there is a RESERVED lock held on the specified
2514** file by this or any other process. If such a lock is held, set *pResOut
2515** to a non-zero value otherwise *pResOut is set to zero. The return value
2516** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2517*/
danielk1977e339d652008-06-28 11:23:00 +00002518static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002519 int rc = SQLITE_OK;
2520 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002521 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002522 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002523
aswift5b1a2562008-08-22 00:22:35 +00002524 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2525
2526 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002527 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002528 if( context->reserved ){
2529 *pResOut = 1;
2530 return SQLITE_OK;
2531 }
drh8af6c222010-05-14 12:43:01 +00002532 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002533
2534 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002535 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002536 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002537 }
2538
2539 /* Otherwise see if some other process holds it.
2540 */
aswift5b1a2562008-08-22 00:22:35 +00002541 if( !reserved ){
2542 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002543 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002544 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002545 /* if we succeeded in taking the reserved lock, unlock it to restore
2546 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002547 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002548 } else {
2549 /* if we failed to get the lock then someone else must have it */
2550 reserved = 1;
2551 }
2552 if( IS_LOCK_ERROR(lrc) ){
2553 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002554 }
2555 }
drhbfe66312006-10-03 17:40:40 +00002556
drh7ed97b92010-01-20 13:07:21 +00002557 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002558 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002559
2560 *pResOut = reserved;
2561 return rc;
drhbfe66312006-10-03 17:40:40 +00002562}
2563
drh6b9d6dd2008-12-03 19:34:47 +00002564/*
drh308c2a52010-05-14 11:30:18 +00002565** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002566** of the following:
2567**
2568** (1) SHARED_LOCK
2569** (2) RESERVED_LOCK
2570** (3) PENDING_LOCK
2571** (4) EXCLUSIVE_LOCK
2572**
2573** Sometimes when requesting one lock state, additional lock states
2574** are inserted in between. The locking might fail on one of the later
2575** transitions leaving the lock state different from what it started but
2576** still short of its goal. The following chart shows the allowed
2577** transitions and the inserted intermediate states:
2578**
2579** UNLOCKED -> SHARED
2580** SHARED -> RESERVED
2581** SHARED -> (PENDING) -> EXCLUSIVE
2582** RESERVED -> (PENDING) -> EXCLUSIVE
2583** PENDING -> EXCLUSIVE
2584**
2585** This routine will only increase a lock. Use the sqlite3OsUnlock()
2586** routine to lower a locking level.
2587*/
drh308c2a52010-05-14 11:30:18 +00002588static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002589 int rc = SQLITE_OK;
2590 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002591 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002592 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002593
2594 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002595 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2596 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002597 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002598
drhbfe66312006-10-03 17:40:40 +00002599 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002600 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002601 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002602 */
drh308c2a52010-05-14 11:30:18 +00002603 if( pFile->eFileLock>=eFileLock ){
2604 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2605 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002606 return SQLITE_OK;
2607 }
2608
2609 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002610 ** (1) We never move from unlocked to anything higher than shared lock.
2611 ** (2) SQLite never explicitly requests a pendig lock.
2612 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002613 */
drh308c2a52010-05-14 11:30:18 +00002614 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2615 assert( eFileLock!=PENDING_LOCK );
2616 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002617
drh8af6c222010-05-14 12:43:01 +00002618 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002619 */
drh6c7d5c52008-11-21 20:32:33 +00002620 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002621 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002622
2623 /* If some thread using this PID has a lock via a different unixFile*
2624 ** handle that precludes the requested lock, return BUSY.
2625 */
drh8af6c222010-05-14 12:43:01 +00002626 if( (pFile->eFileLock!=pInode->eFileLock &&
2627 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002628 ){
2629 rc = SQLITE_BUSY;
2630 goto afp_end_lock;
2631 }
2632
2633 /* If a SHARED lock is requested, and some thread using this PID already
2634 ** has a SHARED or RESERVED lock, then increment reference counts and
2635 ** return SQLITE_OK.
2636 */
drh308c2a52010-05-14 11:30:18 +00002637 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002638 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002639 assert( eFileLock==SHARED_LOCK );
2640 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002641 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002642 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002643 pInode->nShared++;
2644 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002645 goto afp_end_lock;
2646 }
drhbfe66312006-10-03 17:40:40 +00002647
2648 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002649 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2650 ** be released.
2651 */
drh308c2a52010-05-14 11:30:18 +00002652 if( eFileLock==SHARED_LOCK
2653 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002654 ){
2655 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002656 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002657 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002658 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002659 goto afp_end_lock;
2660 }
2661 }
2662
2663 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002664 ** operating system calls for the specified lock.
2665 */
drh308c2a52010-05-14 11:30:18 +00002666 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002667 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002668 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002669
drh8af6c222010-05-14 12:43:01 +00002670 assert( pInode->nShared==0 );
2671 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002672
2673 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002674 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002675 /* note that the quality of the randomness doesn't matter that much */
2676 lk = random();
drh8af6c222010-05-14 12:43:01 +00002677 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002678 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002679 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002680 if( IS_LOCK_ERROR(lrc1) ){
2681 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002682 }
aswift5b1a2562008-08-22 00:22:35 +00002683 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002684 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002685
aswift5b1a2562008-08-22 00:22:35 +00002686 if( IS_LOCK_ERROR(lrc1) ) {
2687 pFile->lastErrno = lrc1Errno;
2688 rc = lrc1;
2689 goto afp_end_lock;
2690 } else if( IS_LOCK_ERROR(lrc2) ){
2691 rc = lrc2;
2692 goto afp_end_lock;
2693 } else if( lrc1 != SQLITE_OK ) {
2694 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002695 } else {
drh308c2a52010-05-14 11:30:18 +00002696 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002697 pInode->nLock++;
2698 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002699 }
drh8af6c222010-05-14 12:43:01 +00002700 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002701 /* We are trying for an exclusive lock but another thread in this
2702 ** same process is still holding a shared lock. */
2703 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002704 }else{
2705 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2706 ** assumed that there is a SHARED or greater lock on the file
2707 ** already.
2708 */
2709 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002710 assert( 0!=pFile->eFileLock );
2711 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002712 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002713 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002714 if( !failed ){
2715 context->reserved = 1;
2716 }
drhbfe66312006-10-03 17:40:40 +00002717 }
drh308c2a52010-05-14 11:30:18 +00002718 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002719 /* Acquire an EXCLUSIVE lock */
2720
2721 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002722 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002723 */
drh6b9d6dd2008-12-03 19:34:47 +00002724 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002725 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002726 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002727 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002728 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002729 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002730 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002731 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002732 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2733 ** a critical I/O error
2734 */
2735 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2736 SQLITE_IOERR_LOCK;
2737 goto afp_end_lock;
2738 }
2739 }else{
aswift5b1a2562008-08-22 00:22:35 +00002740 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002741 }
2742 }
aswift5b1a2562008-08-22 00:22:35 +00002743 if( failed ){
2744 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002745 }
2746 }
2747
2748 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002749 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002750 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002751 }else if( eFileLock==EXCLUSIVE_LOCK ){
2752 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002753 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002754 }
2755
2756afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002757 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002758 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2759 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002760 return rc;
2761}
2762
2763/*
drh308c2a52010-05-14 11:30:18 +00002764** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002765** must be either NO_LOCK or SHARED_LOCK.
2766**
2767** If the locking level of the file descriptor is already at or below
2768** the requested locking level, this routine is a no-op.
2769*/
drh308c2a52010-05-14 11:30:18 +00002770static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002771 int rc = SQLITE_OK;
2772 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002773 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002774 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2775 int skipShared = 0;
2776#ifdef SQLITE_TEST
2777 int h = pFile->h;
2778#endif
drhbfe66312006-10-03 17:40:40 +00002779
2780 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002781 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002782 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002783 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002784
drh308c2a52010-05-14 11:30:18 +00002785 assert( eFileLock<=SHARED_LOCK );
2786 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002787 return SQLITE_OK;
2788 }
drh6c7d5c52008-11-21 20:32:33 +00002789 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002790 pInode = pFile->pInode;
2791 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002792 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002793 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002794 SimulateIOErrorBenign(1);
2795 SimulateIOError( h=(-1) )
2796 SimulateIOErrorBenign(0);
2797
2798#ifndef NDEBUG
2799 /* When reducing a lock such that other processes can start
2800 ** reading the database file again, make sure that the
2801 ** transaction counter was updated if any part of the database
2802 ** file changed. If the transaction counter is not updated,
2803 ** other connections to the same file might not realize that
2804 ** the file has changed and hence might not know to flush their
2805 ** cache. The use of a stale cache can lead to database corruption.
2806 */
2807 assert( pFile->inNormalWrite==0
2808 || pFile->dbUpdate==0
2809 || pFile->transCntrChng==1 );
2810 pFile->inNormalWrite = 0;
2811#endif
aswiftaebf4132008-11-21 00:10:35 +00002812
drh308c2a52010-05-14 11:30:18 +00002813 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002814 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002815 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002816 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002817 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002818 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2819 } else {
2820 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002821 }
2822 }
drh308c2a52010-05-14 11:30:18 +00002823 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002824 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002825 }
drh308c2a52010-05-14 11:30:18 +00002826 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002827 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2828 if( !rc ){
2829 context->reserved = 0;
2830 }
aswiftaebf4132008-11-21 00:10:35 +00002831 }
drh8af6c222010-05-14 12:43:01 +00002832 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2833 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002834 }
aswiftaebf4132008-11-21 00:10:35 +00002835 }
drh308c2a52010-05-14 11:30:18 +00002836 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002837
drh7ed97b92010-01-20 13:07:21 +00002838 /* Decrement the shared lock counter. Release the lock using an
2839 ** OS call only when all threads in this same process have released
2840 ** the lock.
2841 */
drh8af6c222010-05-14 12:43:01 +00002842 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2843 pInode->nShared--;
2844 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002845 SimulateIOErrorBenign(1);
2846 SimulateIOError( h=(-1) )
2847 SimulateIOErrorBenign(0);
2848 if( !skipShared ){
2849 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2850 }
2851 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002852 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002853 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002854 }
2855 }
2856 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002857 pInode->nLock--;
2858 assert( pInode->nLock>=0 );
2859 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002860 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002861 }
2862 }
drhbfe66312006-10-03 17:40:40 +00002863 }
drh7ed97b92010-01-20 13:07:21 +00002864
drh6c7d5c52008-11-21 20:32:33 +00002865 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002866 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002867 return rc;
2868}
2869
2870/*
drh339eb0b2008-03-07 15:34:11 +00002871** Close a file & cleanup AFP specific locking context
2872*/
danielk1977e339d652008-06-28 11:23:00 +00002873static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002874 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002875 if( id ){
2876 unixFile *pFile = (unixFile*)id;
2877 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002878 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002879 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002880 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002881 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002882 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002883 ** the last lock is cleared.
2884 */
dan08da86a2009-08-21 17:18:03 +00002885 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002886 }
danb0ac3e32010-06-16 10:55:42 +00002887 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002888 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002889 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002890 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002891 }
drh7ed97b92010-01-20 13:07:21 +00002892 return rc;
drhbfe66312006-10-03 17:40:40 +00002893}
2894
drhd2cb50b2009-01-09 21:41:17 +00002895#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002896/*
2897** The code above is the AFP lock implementation. The code is specific
2898** to MacOSX and does not work on other unix platforms. No alternative
2899** is available. If you don't compile for a mac, then the "unix-afp"
2900** VFS is not available.
2901**
2902********************* End of the AFP lock implementation **********************
2903******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002904
drh7ed97b92010-01-20 13:07:21 +00002905/******************************************************************************
2906*************************** Begin NFS Locking ********************************/
2907
2908#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2909/*
drh308c2a52010-05-14 11:30:18 +00002910 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002911 ** must be either NO_LOCK or SHARED_LOCK.
2912 **
2913 ** If the locking level of the file descriptor is already at or below
2914 ** the requested locking level, this routine is a no-op.
2915 */
drh308c2a52010-05-14 11:30:18 +00002916static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002917 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002918}
2919
2920#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2921/*
2922** The code above is the NFS lock implementation. The code is specific
2923** to MacOSX and does not work on other unix platforms. No alternative
2924** is available.
2925**
2926********************* End of the NFS lock implementation **********************
2927******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002928
2929/******************************************************************************
2930**************** Non-locking sqlite3_file methods *****************************
2931**
2932** The next division contains implementations for all methods of the
2933** sqlite3_file object other than the locking methods. The locking
2934** methods were defined in divisions above (one locking method per
2935** division). Those methods that are common to all locking modes
2936** are gather together into this division.
2937*/
drhbfe66312006-10-03 17:40:40 +00002938
2939/*
drh734c9862008-11-28 15:37:20 +00002940** Seek to the offset passed as the second argument, then read cnt
2941** bytes into pBuf. Return the number of bytes actually read.
2942**
2943** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2944** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2945** one system to another. Since SQLite does not define USE_PREAD
2946** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2947** See tickets #2741 and #2681.
2948**
2949** To avoid stomping the errno value on a failed read the lastErrno value
2950** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002951*/
drh734c9862008-11-28 15:37:20 +00002952static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2953 int got;
drh7ed97b92010-01-20 13:07:21 +00002954#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002955 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002956#endif
drh734c9862008-11-28 15:37:20 +00002957 TIMER_START;
2958#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002959 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002960 SimulateIOError( got = -1 );
2961#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002962 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002963 SimulateIOError( got = -1 );
2964#else
2965 newOffset = lseek(id->h, offset, SEEK_SET);
2966 SimulateIOError( newOffset-- );
2967 if( newOffset!=offset ){
2968 if( newOffset == -1 ){
2969 ((unixFile*)id)->lastErrno = errno;
2970 }else{
2971 ((unixFile*)id)->lastErrno = 0;
2972 }
2973 return -1;
2974 }
drhe562be52011-03-02 18:01:10 +00002975 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002976#endif
2977 TIMER_END;
2978 if( got<0 ){
2979 ((unixFile*)id)->lastErrno = errno;
2980 }
drh308c2a52010-05-14 11:30:18 +00002981 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002982 return got;
drhbfe66312006-10-03 17:40:40 +00002983}
2984
2985/*
drh734c9862008-11-28 15:37:20 +00002986** Read data from a file into a buffer. Return SQLITE_OK if all
2987** bytes were read successfully and SQLITE_IOERR if anything goes
2988** wrong.
drh339eb0b2008-03-07 15:34:11 +00002989*/
drh734c9862008-11-28 15:37:20 +00002990static int unixRead(
2991 sqlite3_file *id,
2992 void *pBuf,
2993 int amt,
2994 sqlite3_int64 offset
2995){
dan08da86a2009-08-21 17:18:03 +00002996 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002997 int got;
2998 assert( id );
drh08c6d442009-02-09 17:34:07 +00002999
dan08da86a2009-08-21 17:18:03 +00003000 /* If this is a database file (not a journal, master-journal or temp
3001 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003002#if 0
dane946c392009-08-22 11:39:46 +00003003 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003004 || offset>=PENDING_BYTE+512
3005 || offset+amt<=PENDING_BYTE
3006 );
dan7c246102010-04-12 19:00:29 +00003007#endif
drh08c6d442009-02-09 17:34:07 +00003008
dan08da86a2009-08-21 17:18:03 +00003009 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003010 if( got==amt ){
3011 return SQLITE_OK;
3012 }else if( got<0 ){
3013 /* lastErrno set by seekAndRead */
3014 return SQLITE_IOERR_READ;
3015 }else{
dan08da86a2009-08-21 17:18:03 +00003016 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003017 /* Unread parts of the buffer must be zero-filled */
3018 memset(&((char*)pBuf)[got], 0, amt-got);
3019 return SQLITE_IOERR_SHORT_READ;
3020 }
3021}
3022
3023/*
3024** Seek to the offset in id->offset then read cnt bytes into pBuf.
3025** Return the number of bytes actually read. Update the offset.
3026**
3027** To avoid stomping the errno value on a failed write the lastErrno value
3028** is set before returning.
3029*/
3030static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3031 int got;
drh7ed97b92010-01-20 13:07:21 +00003032#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003033 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003034#endif
drh734c9862008-11-28 15:37:20 +00003035 TIMER_START;
3036#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003037 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003038#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003039 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003040#else
drhbd1e50c2011-08-19 14:54:12 +00003041 do{
3042 newOffset = lseek(id->h, offset, SEEK_SET);
3043 SimulateIOError( newOffset-- );
3044 if( newOffset!=offset ){
3045 if( newOffset == -1 ){
3046 ((unixFile*)id)->lastErrno = errno;
3047 }else{
3048 ((unixFile*)id)->lastErrno = 0;
3049 }
3050 return -1;
drh734c9862008-11-28 15:37:20 +00003051 }
drhbd1e50c2011-08-19 14:54:12 +00003052 got = osWrite(id->h, pBuf, cnt);
3053 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003054#endif
3055 TIMER_END;
3056 if( got<0 ){
3057 ((unixFile*)id)->lastErrno = errno;
3058 }
3059
drh308c2a52010-05-14 11:30:18 +00003060 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003061 return got;
3062}
3063
3064
3065/*
3066** Write data from a buffer into a file. Return SQLITE_OK on success
3067** or some other error code on failure.
3068*/
3069static int unixWrite(
3070 sqlite3_file *id,
3071 const void *pBuf,
3072 int amt,
3073 sqlite3_int64 offset
3074){
dan08da86a2009-08-21 17:18:03 +00003075 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003076 int wrote = 0;
3077 assert( id );
3078 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003079
dan08da86a2009-08-21 17:18:03 +00003080 /* If this is a database file (not a journal, master-journal or temp
3081 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003082#if 0
dane946c392009-08-22 11:39:46 +00003083 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003084 || offset>=PENDING_BYTE+512
3085 || offset+amt<=PENDING_BYTE
3086 );
dan7c246102010-04-12 19:00:29 +00003087#endif
drh08c6d442009-02-09 17:34:07 +00003088
drh8f941bc2009-01-14 23:03:40 +00003089#ifndef NDEBUG
3090 /* If we are doing a normal write to a database file (as opposed to
3091 ** doing a hot-journal rollback or a write to some file other than a
3092 ** normal database file) then record the fact that the database
3093 ** has changed. If the transaction counter is modified, record that
3094 ** fact too.
3095 */
dan08da86a2009-08-21 17:18:03 +00003096 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003097 pFile->dbUpdate = 1; /* The database has been modified */
3098 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003099 int rc;
drh8f941bc2009-01-14 23:03:40 +00003100 char oldCntr[4];
3101 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003102 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003103 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003104 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003105 pFile->transCntrChng = 1; /* The transaction counter has changed */
3106 }
3107 }
3108 }
3109#endif
3110
dan08da86a2009-08-21 17:18:03 +00003111 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003112 amt -= wrote;
3113 offset += wrote;
3114 pBuf = &((char*)pBuf)[wrote];
3115 }
3116 SimulateIOError(( wrote=(-1), amt=1 ));
3117 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003118
drh734c9862008-11-28 15:37:20 +00003119 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003120 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003121 /* lastErrno set by seekAndWrite */
3122 return SQLITE_IOERR_WRITE;
3123 }else{
dan08da86a2009-08-21 17:18:03 +00003124 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003125 return SQLITE_FULL;
3126 }
3127 }
dan6e09d692010-07-27 18:34:15 +00003128
drh734c9862008-11-28 15:37:20 +00003129 return SQLITE_OK;
3130}
3131
3132#ifdef SQLITE_TEST
3133/*
3134** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003135** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003136*/
3137int sqlite3_sync_count = 0;
3138int sqlite3_fullsync_count = 0;
3139#endif
3140
3141/*
drh89240432009-03-25 01:06:01 +00003142** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003143** Others do no. To be safe, we will stick with the (slightly slower)
3144** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003145** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003146*/
drh20f8e132011-08-31 21:01:55 +00003147#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003148# define fdatasync fsync
3149#endif
3150
3151/*
3152** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3153** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3154** only available on Mac OS X. But that could change.
3155*/
3156#ifdef F_FULLFSYNC
3157# define HAVE_FULLFSYNC 1
3158#else
3159# define HAVE_FULLFSYNC 0
3160#endif
3161
3162
3163/*
3164** The fsync() system call does not work as advertised on many
3165** unix systems. The following procedure is an attempt to make
3166** it work better.
3167**
3168** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3169** for testing when we want to run through the test suite quickly.
3170** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3171** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3172** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003173**
3174** SQLite sets the dataOnly flag if the size of the file is unchanged.
3175** The idea behind dataOnly is that it should only write the file content
3176** to disk, not the inode. We only set dataOnly if the file size is
3177** unchanged since the file size is part of the inode. However,
3178** Ted Ts'o tells us that fdatasync() will also write the inode if the
3179** file size has changed. The only real difference between fdatasync()
3180** and fsync(), Ted tells us, is that fdatasync() will not flush the
3181** inode if the mtime or owner or other inode attributes have changed.
3182** We only care about the file size, not the other file attributes, so
3183** as far as SQLite is concerned, an fdatasync() is always adequate.
3184** So, we always use fdatasync() if it is available, regardless of
3185** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003186*/
3187static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003188 int rc;
drh734c9862008-11-28 15:37:20 +00003189
3190 /* The following "ifdef/elif/else/" block has the same structure as
3191 ** the one below. It is replicated here solely to avoid cluttering
3192 ** up the real code with the UNUSED_PARAMETER() macros.
3193 */
3194#ifdef SQLITE_NO_SYNC
3195 UNUSED_PARAMETER(fd);
3196 UNUSED_PARAMETER(fullSync);
3197 UNUSED_PARAMETER(dataOnly);
3198#elif HAVE_FULLFSYNC
3199 UNUSED_PARAMETER(dataOnly);
3200#else
3201 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003202 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003203#endif
3204
3205 /* Record the number of times that we do a normal fsync() and
3206 ** FULLSYNC. This is used during testing to verify that this procedure
3207 ** gets called with the correct arguments.
3208 */
3209#ifdef SQLITE_TEST
3210 if( fullSync ) sqlite3_fullsync_count++;
3211 sqlite3_sync_count++;
3212#endif
3213
3214 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3215 ** no-op
3216 */
3217#ifdef SQLITE_NO_SYNC
3218 rc = SQLITE_OK;
3219#elif HAVE_FULLFSYNC
3220 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003221 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003222 }else{
3223 rc = 1;
3224 }
3225 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003226 ** It shouldn't be possible for fullfsync to fail on the local
3227 ** file system (on OSX), so failure indicates that FULLFSYNC
3228 ** isn't supported for this file system. So, attempt an fsync
3229 ** and (for now) ignore the overhead of a superfluous fcntl call.
3230 ** It'd be better to detect fullfsync support once and avoid
3231 ** the fcntl call every time sync is called.
3232 */
drh734c9862008-11-28 15:37:20 +00003233 if( rc ) rc = fsync(fd);
3234
drh7ed97b92010-01-20 13:07:21 +00003235#elif defined(__APPLE__)
3236 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3237 ** so currently we default to the macro that redefines fdatasync to fsync
3238 */
3239 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003240#else
drh0b647ff2009-03-21 14:41:04 +00003241 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003242#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003243 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003244 rc = fsync(fd);
3245 }
drh0b647ff2009-03-21 14:41:04 +00003246#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003247#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3248
3249 if( OS_VXWORKS && rc!= -1 ){
3250 rc = 0;
3251 }
chw97185482008-11-17 08:05:31 +00003252 return rc;
drhbfe66312006-10-03 17:40:40 +00003253}
3254
drh734c9862008-11-28 15:37:20 +00003255/*
drh0059eae2011-08-08 23:48:40 +00003256** Open a file descriptor to the directory containing file zFilename.
3257** If successful, *pFd is set to the opened file descriptor and
3258** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3259** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3260** value.
3261**
drh90315a22011-08-10 01:52:12 +00003262** The directory file descriptor is used for only one thing - to
3263** fsync() a directory to make sure file creation and deletion events
3264** are flushed to disk. Such fsyncs are not needed on newer
3265** journaling filesystems, but are required on older filesystems.
3266**
3267** This routine can be overridden using the xSetSysCall interface.
3268** The ability to override this routine was added in support of the
3269** chromium sandbox. Opening a directory is a security risk (we are
3270** told) so making it overrideable allows the chromium sandbox to
3271** replace this routine with a harmless no-op. To make this routine
3272** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3273** *pFd set to a negative number.
3274**
drh0059eae2011-08-08 23:48:40 +00003275** If SQLITE_OK is returned, the caller is responsible for closing
3276** the file descriptor *pFd using close().
3277*/
3278static int openDirectory(const char *zFilename, int *pFd){
3279 int ii;
3280 int fd = -1;
3281 char zDirname[MAX_PATHNAME+1];
3282
3283 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3284 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3285 if( ii>0 ){
3286 zDirname[ii] = '\0';
3287 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3288 if( fd>=0 ){
3289#ifdef FD_CLOEXEC
3290 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3291#endif
3292 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3293 }
3294 }
3295 *pFd = fd;
3296 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3297}
3298
3299/*
drh734c9862008-11-28 15:37:20 +00003300** Make sure all writes to a particular file are committed to disk.
3301**
3302** If dataOnly==0 then both the file itself and its metadata (file
3303** size, access time, etc) are synced. If dataOnly!=0 then only the
3304** file data is synced.
3305**
3306** Under Unix, also make sure that the directory entry for the file
3307** has been created by fsync-ing the directory that contains the file.
3308** If we do not do this and we encounter a power failure, the directory
3309** entry for the journal might not exist after we reboot. The next
3310** SQLite to access the file will not know that the journal exists (because
3311** the directory entry for the journal was never created) and the transaction
3312** will not roll back - possibly leading to database corruption.
3313*/
3314static int unixSync(sqlite3_file *id, int flags){
3315 int rc;
3316 unixFile *pFile = (unixFile*)id;
3317
3318 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3319 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3320
3321 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3322 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3323 || (flags&0x0F)==SQLITE_SYNC_FULL
3324 );
3325
3326 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3327 ** line is to test that doing so does not cause any problems.
3328 */
3329 SimulateDiskfullError( return SQLITE_FULL );
3330
3331 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003332 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003333 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3334 SimulateIOError( rc=1 );
3335 if( rc ){
3336 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003337 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003338 }
drh0059eae2011-08-08 23:48:40 +00003339
3340 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003341 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3342 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003343 */
3344 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3345 int dirfd;
3346 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003347 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003348 rc = osOpenDirectory(pFile->zPath, &dirfd);
3349 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003350 full_fsync(dirfd, 0, 0);
3351 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003352 }else if( rc==SQLITE_CANTOPEN ){
3353 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003354 }
drh0059eae2011-08-08 23:48:40 +00003355 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003356 }
3357 return rc;
3358}
3359
3360/*
3361** Truncate an open file to a specified size
3362*/
3363static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003364 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003365 int rc;
dan6e09d692010-07-27 18:34:15 +00003366 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003367 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003368
3369 /* If the user has configured a chunk-size for this file, truncate the
3370 ** file so that it consists of an integer number of chunks (i.e. the
3371 ** actual file size after the operation may be larger than the requested
3372 ** size).
3373 */
3374 if( pFile->szChunk ){
3375 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3376 }
3377
drhff812312011-02-23 13:33:46 +00003378 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003379 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003380 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003381 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003382 }else{
drh3313b142009-11-06 04:13:18 +00003383#ifndef NDEBUG
3384 /* If we are doing a normal write to a database file (as opposed to
3385 ** doing a hot-journal rollback or a write to some file other than a
3386 ** normal database file) and we truncate the file to zero length,
3387 ** that effectively updates the change counter. This might happen
3388 ** when restoring a database using the backup API from a zero-length
3389 ** source.
3390 */
dan6e09d692010-07-27 18:34:15 +00003391 if( pFile->inNormalWrite && nByte==0 ){
3392 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003393 }
3394#endif
3395
drh734c9862008-11-28 15:37:20 +00003396 return SQLITE_OK;
3397 }
3398}
3399
3400/*
3401** Determine the current size of a file in bytes
3402*/
3403static int unixFileSize(sqlite3_file *id, i64 *pSize){
3404 int rc;
3405 struct stat buf;
3406 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003407 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003408 SimulateIOError( rc=1 );
3409 if( rc!=0 ){
3410 ((unixFile*)id)->lastErrno = errno;
3411 return SQLITE_IOERR_FSTAT;
3412 }
3413 *pSize = buf.st_size;
3414
drh8af6c222010-05-14 12:43:01 +00003415 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003416 ** writes a single byte into that file in order to work around a bug
3417 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3418 ** layers, we need to report this file size as zero even though it is
3419 ** really 1. Ticket #3260.
3420 */
3421 if( *pSize==1 ) *pSize = 0;
3422
3423
3424 return SQLITE_OK;
3425}
3426
drhd2cb50b2009-01-09 21:41:17 +00003427#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003428/*
3429** Handler for proxy-locking file-control verbs. Defined below in the
3430** proxying locking division.
3431*/
3432static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003433#endif
drh715ff302008-12-03 22:32:44 +00003434
dan502019c2010-07-28 14:26:17 +00003435/*
3436** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003437** file-control operation. Enlarge the database to nBytes in size
3438** (rounded up to the next chunk-size). If the database is already
3439** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003440*/
3441static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003442 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003443 i64 nSize; /* Required file size */
3444 struct stat buf; /* Used to hold return values of fstat() */
3445
drh99ab3b12011-03-02 15:09:07 +00003446 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003447
3448 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3449 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003450
dan502019c2010-07-28 14:26:17 +00003451#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003452 /* The code below is handling the return value of osFallocate()
3453 ** correctly. posix_fallocate() is defined to "returns zero on success,
3454 ** or an error number on failure". See the manpage for details. */
3455 int err;
drhff812312011-02-23 13:33:46 +00003456 do{
dan661d71a2011-03-30 19:08:03 +00003457 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3458 }while( err==EINTR );
3459 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003460#else
3461 /* If the OS does not have posix_fallocate(), fake it. First use
3462 ** ftruncate() to set the file size, then write a single byte to
3463 ** the last byte in each block within the extended region. This
3464 ** is the same technique used by glibc to implement posix_fallocate()
3465 ** on systems that do not have a real fallocate() system call.
3466 */
3467 int nBlk = buf.st_blksize; /* File-system block size */
3468 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003469
drhff812312011-02-23 13:33:46 +00003470 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003471 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003472 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003473 }
3474 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003475 while( iWrite<nSize ){
3476 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3477 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003478 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003479 }
dan502019c2010-07-28 14:26:17 +00003480#endif
3481 }
3482 }
3483
3484 return SQLITE_OK;
3485}
danielk1977ad94b582007-08-20 06:44:22 +00003486
danielk1977e3026632004-06-22 11:29:02 +00003487/*
drh9e33c2c2007-08-31 18:34:59 +00003488** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003489*/
drhcc6bb3e2007-08-31 16:11:35 +00003490static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003491 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003492 switch( op ){
3493 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003494 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003495 return SQLITE_OK;
3496 }
drh7708e972008-11-29 00:56:52 +00003497 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003498 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003499 return SQLITE_OK;
3500 }
dan6e09d692010-07-27 18:34:15 +00003501 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003502 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003503 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003504 }
drh9ff27ec2010-05-19 19:26:05 +00003505 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003506 int rc;
3507 SimulateIOErrorBenign(1);
3508 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3509 SimulateIOErrorBenign(0);
3510 return rc;
drhf0b190d2011-07-26 16:03:07 +00003511 }
3512 case SQLITE_FCNTL_PERSIST_WAL: {
3513 int bPersist = *(int*)pArg;
3514 if( bPersist<0 ){
drh253cea52011-07-26 16:23:25 +00003515 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
drhf0b190d2011-07-26 16:03:07 +00003516 }else if( bPersist==0 ){
3517 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
3518 }else{
3519 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
3520 }
3521 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003522 }
drh8f941bc2009-01-14 23:03:40 +00003523#ifndef NDEBUG
3524 /* The pager calls this method to signal that it has done
3525 ** a rollback and that the database is therefore unchanged and
3526 ** it hence it is OK for the transaction change counter to be
3527 ** unchanged.
3528 */
3529 case SQLITE_FCNTL_DB_UNCHANGED: {
3530 ((unixFile*)id)->dbUpdate = 0;
3531 return SQLITE_OK;
3532 }
3533#endif
drhd2cb50b2009-01-09 21:41:17 +00003534#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003535 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003536 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003537 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003538 }
drhd2cb50b2009-01-09 21:41:17 +00003539#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003540 case SQLITE_FCNTL_SYNC_OMITTED: {
3541 return SQLITE_OK; /* A no-op */
3542 }
drh9e33c2c2007-08-31 18:34:59 +00003543 }
drh0b52b7d2011-01-26 19:46:22 +00003544 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003545}
3546
3547/*
danielk1977a3d4c882007-03-23 10:08:38 +00003548** Return the sector size in bytes of the underlying block device for
3549** the specified file. This is almost always 512 bytes, but may be
3550** larger for some devices.
3551**
3552** SQLite code assumes this function cannot fail. It also assumes that
3553** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003554** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003555** same for both.
3556*/
danielk1977397d65f2008-11-19 11:35:39 +00003557static int unixSectorSize(sqlite3_file *NotUsed){
3558 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003559 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003560}
3561
danielk197790949c22007-08-17 16:50:38 +00003562/*
danielk1977397d65f2008-11-19 11:35:39 +00003563** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003564*/
danielk1977397d65f2008-11-19 11:35:39 +00003565static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3566 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003567 return 0;
3568}
3569
drhd9e5c4f2010-05-12 18:01:39 +00003570#ifndef SQLITE_OMIT_WAL
3571
3572
3573/*
drhd91c68f2010-05-14 14:52:25 +00003574** Object used to represent an shared memory buffer.
3575**
3576** When multiple threads all reference the same wal-index, each thread
3577** has its own unixShm object, but they all point to a single instance
3578** of this unixShmNode object. In other words, each wal-index is opened
3579** only once per process.
3580**
3581** Each unixShmNode object is connected to a single unixInodeInfo object.
3582** We could coalesce this object into unixInodeInfo, but that would mean
3583** every open file that does not use shared memory (in other words, most
3584** open files) would have to carry around this extra information. So
3585** the unixInodeInfo object contains a pointer to this unixShmNode object
3586** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003587**
3588** unixMutexHeld() must be true when creating or destroying
3589** this object or while reading or writing the following fields:
3590**
3591** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003592**
3593** The following fields are read-only after the object is created:
3594**
3595** fid
3596** zFilename
3597**
drhd91c68f2010-05-14 14:52:25 +00003598** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003599** unixMutexHeld() is true when reading or writing any other field
3600** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003601*/
drhd91c68f2010-05-14 14:52:25 +00003602struct unixShmNode {
3603 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003604 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003605 char *zFilename; /* Name of the mmapped file */
3606 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003607 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003608 u16 nRegion; /* Size of array apRegion */
3609 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003610 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003611 int nRef; /* Number of unixShm objects pointing to this */
3612 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003613#ifdef SQLITE_DEBUG
3614 u8 exclMask; /* Mask of exclusive locks held */
3615 u8 sharedMask; /* Mask of shared locks held */
3616 u8 nextShmId; /* Next available unixShm.id value */
3617#endif
3618};
3619
3620/*
drhd9e5c4f2010-05-12 18:01:39 +00003621** Structure used internally by this VFS to record the state of an
3622** open shared memory connection.
3623**
drhd91c68f2010-05-14 14:52:25 +00003624** The following fields are initialized when this object is created and
3625** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003626**
drhd91c68f2010-05-14 14:52:25 +00003627** unixShm.pFile
3628** unixShm.id
3629**
3630** All other fields are read/write. The unixShm.pFile->mutex must be held
3631** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003632*/
3633struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003634 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3635 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003636 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003637 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003638 u16 sharedMask; /* Mask of shared locks held */
3639 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003640};
3641
3642/*
drhd9e5c4f2010-05-12 18:01:39 +00003643** Constants used for locking
3644*/
drhbd9676c2010-06-23 17:58:38 +00003645#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003646#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003647
drhd9e5c4f2010-05-12 18:01:39 +00003648/*
drh73b64e42010-05-30 19:55:15 +00003649** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003650**
3651** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3652** otherwise.
3653*/
3654static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003655 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3656 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003657 int ofst, /* First byte of the locking range */
3658 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003659){
3660 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003661 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003662
drhd91c68f2010-05-14 14:52:25 +00003663 /* Access to the unixShmNode object is serialized by the caller */
3664 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003665
drh73b64e42010-05-30 19:55:15 +00003666 /* Shared locks never span more than one byte */
3667 assert( n==1 || lockType!=F_RDLCK );
3668
3669 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003670 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003671
drh3cb93392011-03-12 18:10:44 +00003672 if( pShmNode->h>=0 ){
3673 /* Initialize the locking parameters */
3674 memset(&f, 0, sizeof(f));
3675 f.l_type = lockType;
3676 f.l_whence = SEEK_SET;
3677 f.l_start = ofst;
3678 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003679
drh3cb93392011-03-12 18:10:44 +00003680 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3681 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3682 }
drhd9e5c4f2010-05-12 18:01:39 +00003683
3684 /* Update the global lock state and do debug tracing */
3685#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003686 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003687 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003688 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003689 if( rc==SQLITE_OK ){
3690 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003691 OSTRACE(("unlock %d ok", ofst));
3692 pShmNode->exclMask &= ~mask;
3693 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003694 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003695 OSTRACE(("read-lock %d ok", ofst));
3696 pShmNode->exclMask &= ~mask;
3697 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003698 }else{
3699 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003700 OSTRACE(("write-lock %d ok", ofst));
3701 pShmNode->exclMask |= mask;
3702 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003703 }
3704 }else{
3705 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003706 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003707 }else if( lockType==F_RDLCK ){
3708 OSTRACE(("read-lock failed"));
3709 }else{
3710 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003711 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003712 }
3713 }
drh20e1f082010-05-31 16:10:12 +00003714 OSTRACE((" - afterwards %03x,%03x\n",
3715 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003716 }
drhd9e5c4f2010-05-12 18:01:39 +00003717#endif
3718
3719 return rc;
3720}
3721
drhd9e5c4f2010-05-12 18:01:39 +00003722
3723/*
drhd91c68f2010-05-14 14:52:25 +00003724** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003725**
3726** This is not a VFS shared-memory method; it is a utility function called
3727** by VFS shared-memory methods.
3728*/
drhd91c68f2010-05-14 14:52:25 +00003729static void unixShmPurge(unixFile *pFd){
3730 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003731 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003732 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003733 int i;
drhd91c68f2010-05-14 14:52:25 +00003734 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003735 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003736 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003737 if( p->h>=0 ){
3738 munmap(p->apRegion[i], p->szRegion);
3739 }else{
3740 sqlite3_free(p->apRegion[i]);
3741 }
dan13a3cb82010-06-11 19:04:21 +00003742 }
dan18801912010-06-14 14:07:50 +00003743 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003744 if( p->h>=0 ){
3745 robust_close(pFd, p->h, __LINE__);
3746 p->h = -1;
3747 }
drhd91c68f2010-05-14 14:52:25 +00003748 p->pInode->pShmNode = 0;
3749 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003750 }
3751}
3752
3753/*
danda9fe0c2010-07-13 18:44:03 +00003754** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003755** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003756**
drh7234c6d2010-06-19 15:10:09 +00003757** The file used to implement shared-memory is in the same directory
3758** as the open database file and has the same name as the open database
3759** file with the "-shm" suffix added. For example, if the database file
3760** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003761** for shared memory will be called "/home/user1/config.db-shm".
3762**
3763** Another approach to is to use files in /dev/shm or /dev/tmp or an
3764** some other tmpfs mount. But if a file in a different directory
3765** from the database file is used, then differing access permissions
3766** or a chroot() might cause two different processes on the same
3767** database to end up using different files for shared memory -
3768** meaning that their memory would not really be shared - resulting
3769** in database corruption. Nevertheless, this tmpfs file usage
3770** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3771** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3772** option results in an incompatible build of SQLite; builds of SQLite
3773** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3774** same database file at the same time, database corruption will likely
3775** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3776** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003777**
3778** When opening a new shared-memory file, if no other instances of that
3779** file are currently open, in this process or in other processes, then
3780** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003781**
3782** If the original database file (pDbFd) is using the "unix-excl" VFS
3783** that means that an exclusive lock is held on the database file and
3784** that no other processes are able to read or write the database. In
3785** that case, we do not really need shared memory. No shared memory
3786** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003787*/
danda9fe0c2010-07-13 18:44:03 +00003788static int unixOpenSharedMemory(unixFile *pDbFd){
3789 struct unixShm *p = 0; /* The connection to be opened */
3790 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3791 int rc; /* Result code */
3792 unixInodeInfo *pInode; /* The inode of fd */
3793 char *zShmFilename; /* Name of the file used for SHM */
3794 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003795
danda9fe0c2010-07-13 18:44:03 +00003796 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003797 p = sqlite3_malloc( sizeof(*p) );
3798 if( p==0 ) return SQLITE_NOMEM;
3799 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003800 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003801
danda9fe0c2010-07-13 18:44:03 +00003802 /* Check to see if a unixShmNode object already exists. Reuse an existing
3803 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003804 */
3805 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003806 pInode = pDbFd->pInode;
3807 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003808 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003809 struct stat sStat; /* fstat() info for database file */
3810
3811 /* Call fstat() to figure out the permissions on the database file. If
3812 ** a new *-shm file is created, an attempt will be made to create it
3813 ** with the same permissions. The actual permissions the file is created
3814 ** with are subject to the current umask setting.
3815 */
drh3cb93392011-03-12 18:10:44 +00003816 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003817 rc = SQLITE_IOERR_FSTAT;
3818 goto shm_open_err;
3819 }
3820
drha4ced192010-07-15 18:32:40 +00003821#ifdef SQLITE_SHM_DIRECTORY
3822 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3823#else
drh7234c6d2010-06-19 15:10:09 +00003824 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003825#endif
drh7234c6d2010-06-19 15:10:09 +00003826 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003827 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003828 rc = SQLITE_NOMEM;
3829 goto shm_open_err;
3830 }
drhd91c68f2010-05-14 14:52:25 +00003831 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003832 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003833#ifdef SQLITE_SHM_DIRECTORY
3834 sqlite3_snprintf(nShmFilename, zShmFilename,
3835 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3836 (u32)sStat.st_ino, (u32)sStat.st_dev);
3837#else
drh7234c6d2010-06-19 15:10:09 +00003838 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003839 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003840#endif
drhd91c68f2010-05-14 14:52:25 +00003841 pShmNode->h = -1;
3842 pDbFd->pInode->pShmNode = pShmNode;
3843 pShmNode->pInode = pDbFd->pInode;
3844 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3845 if( pShmNode->mutex==0 ){
3846 rc = SQLITE_NOMEM;
3847 goto shm_open_err;
3848 }
drhd9e5c4f2010-05-12 18:01:39 +00003849
drh3cb93392011-03-12 18:10:44 +00003850 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003851 const char *zRO;
3852 int openFlags = O_RDWR | O_CREAT;
3853 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
3854 if( zRO && sqlite3GetBoolean(zRO) ){
3855 openFlags = O_RDONLY;
3856 pShmNode->isReadonly = 1;
3857 }
3858 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003859 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003860 if( pShmNode->h<0 ){
3861 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3862 goto shm_open_err;
3863 }
drhd9e5c4f2010-05-12 18:01:39 +00003864 }
drh3cb93392011-03-12 18:10:44 +00003865
3866 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003867 ** If not, truncate the file to zero length.
3868 */
3869 rc = SQLITE_OK;
3870 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3871 if( robust_ftruncate(pShmNode->h, 0) ){
3872 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003873 }
3874 }
drh66dfec8b2011-06-01 20:01:49 +00003875 if( rc==SQLITE_OK ){
3876 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3877 }
3878 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003879 }
drhd9e5c4f2010-05-12 18:01:39 +00003880 }
3881
drhd91c68f2010-05-14 14:52:25 +00003882 /* Make the new connection a child of the unixShmNode */
3883 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003884#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003885 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003886#endif
drhd91c68f2010-05-14 14:52:25 +00003887 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003888 pDbFd->pShm = p;
3889 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003890
3891 /* The reference count on pShmNode has already been incremented under
3892 ** the cover of the unixEnterMutex() mutex and the pointer from the
3893 ** new (struct unixShm) object to the pShmNode has been set. All that is
3894 ** left to do is to link the new object into the linked list starting
3895 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3896 ** mutex.
3897 */
3898 sqlite3_mutex_enter(pShmNode->mutex);
3899 p->pNext = pShmNode->pFirst;
3900 pShmNode->pFirst = p;
3901 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003902 return SQLITE_OK;
3903
3904 /* Jump here on any error */
3905shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003906 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003907 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003908 unixLeaveMutex();
3909 return rc;
3910}
3911
3912/*
danda9fe0c2010-07-13 18:44:03 +00003913** This function is called to obtain a pointer to region iRegion of the
3914** shared-memory associated with the database file fd. Shared-memory regions
3915** are numbered starting from zero. Each shared-memory region is szRegion
3916** bytes in size.
3917**
3918** If an error occurs, an error code is returned and *pp is set to NULL.
3919**
3920** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3921** region has not been allocated (by any client, including one running in a
3922** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3923** bExtend is non-zero and the requested shared-memory region has not yet
3924** been allocated, it is allocated by this function.
3925**
3926** If the shared-memory region has already been allocated or is allocated by
3927** this call as described above, then it is mapped into this processes
3928** address space (if it is not already), *pp is set to point to the mapped
3929** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003930*/
danda9fe0c2010-07-13 18:44:03 +00003931static int unixShmMap(
3932 sqlite3_file *fd, /* Handle open on database file */
3933 int iRegion, /* Region to retrieve */
3934 int szRegion, /* Size of regions */
3935 int bExtend, /* True to extend file if necessary */
3936 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003937){
danda9fe0c2010-07-13 18:44:03 +00003938 unixFile *pDbFd = (unixFile*)fd;
3939 unixShm *p;
3940 unixShmNode *pShmNode;
3941 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003942
danda9fe0c2010-07-13 18:44:03 +00003943 /* If the shared-memory file has not yet been opened, open it now. */
3944 if( pDbFd->pShm==0 ){
3945 rc = unixOpenSharedMemory(pDbFd);
3946 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003947 }
drhd9e5c4f2010-05-12 18:01:39 +00003948
danda9fe0c2010-07-13 18:44:03 +00003949 p = pDbFd->pShm;
3950 pShmNode = p->pShmNode;
3951 sqlite3_mutex_enter(pShmNode->mutex);
3952 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003953 assert( pShmNode->pInode==pDbFd->pInode );
3954 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3955 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003956
3957 if( pShmNode->nRegion<=iRegion ){
3958 char **apNew; /* New apRegion[] array */
3959 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3960 struct stat sStat; /* Used by fstat() */
3961
3962 pShmNode->szRegion = szRegion;
3963
drh3cb93392011-03-12 18:10:44 +00003964 if( pShmNode->h>=0 ){
3965 /* The requested region is not mapped into this processes address space.
3966 ** Check to see if it has been allocated (i.e. if the wal-index file is
3967 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003968 */
drh3cb93392011-03-12 18:10:44 +00003969 if( osFstat(pShmNode->h, &sStat) ){
3970 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003971 goto shmpage_out;
3972 }
drh3cb93392011-03-12 18:10:44 +00003973
3974 if( sStat.st_size<nByte ){
3975 /* The requested memory region does not exist. If bExtend is set to
3976 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3977 **
3978 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3979 ** the requested memory region.
3980 */
3981 if( !bExtend ) goto shmpage_out;
3982 if( robust_ftruncate(pShmNode->h, nByte) ){
3983 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3984 pShmNode->zFilename);
3985 goto shmpage_out;
3986 }
3987 }
danda9fe0c2010-07-13 18:44:03 +00003988 }
3989
3990 /* Map the requested memory region into this processes address space. */
3991 apNew = (char **)sqlite3_realloc(
3992 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3993 );
3994 if( !apNew ){
3995 rc = SQLITE_IOERR_NOMEM;
3996 goto shmpage_out;
3997 }
3998 pShmNode->apRegion = apNew;
3999 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004000 void *pMem;
4001 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004002 pMem = mmap(0, szRegion,
4003 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004004 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4005 );
4006 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004007 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004008 goto shmpage_out;
4009 }
4010 }else{
4011 pMem = sqlite3_malloc(szRegion);
4012 if( pMem==0 ){
4013 rc = SQLITE_NOMEM;
4014 goto shmpage_out;
4015 }
4016 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004017 }
4018 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4019 pShmNode->nRegion++;
4020 }
4021 }
4022
4023shmpage_out:
4024 if( pShmNode->nRegion>iRegion ){
4025 *pp = pShmNode->apRegion[iRegion];
4026 }else{
4027 *pp = 0;
4028 }
drh66dfec8b2011-06-01 20:01:49 +00004029 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004030 sqlite3_mutex_leave(pShmNode->mutex);
4031 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004032}
4033
4034/*
drhd9e5c4f2010-05-12 18:01:39 +00004035** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004036**
4037** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4038** different here than in posix. In xShmLock(), one can go from unlocked
4039** to shared and back or from unlocked to exclusive and back. But one may
4040** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004041*/
4042static int unixShmLock(
4043 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004044 int ofst, /* First lock to acquire or release */
4045 int n, /* Number of locks to acquire or release */
4046 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004047){
drh73b64e42010-05-30 19:55:15 +00004048 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4049 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4050 unixShm *pX; /* For looping over all siblings */
4051 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4052 int rc = SQLITE_OK; /* Result code */
4053 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004054
drhd91c68f2010-05-14 14:52:25 +00004055 assert( pShmNode==pDbFd->pInode->pShmNode );
4056 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004057 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004058 assert( n>=1 );
4059 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4060 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4061 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4062 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4063 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004064 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4065 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004066
drhc99597c2010-05-31 01:41:15 +00004067 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004068 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004069 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004070 if( flags & SQLITE_SHM_UNLOCK ){
4071 u16 allMask = 0; /* Mask of locks held by siblings */
4072
4073 /* See if any siblings hold this same lock */
4074 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4075 if( pX==p ) continue;
4076 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4077 allMask |= pX->sharedMask;
4078 }
4079
4080 /* Unlock the system-level locks */
4081 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004082 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004083 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004084 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004085 }
drh73b64e42010-05-30 19:55:15 +00004086
4087 /* Undo the local locks */
4088 if( rc==SQLITE_OK ){
4089 p->exclMask &= ~mask;
4090 p->sharedMask &= ~mask;
4091 }
4092 }else if( flags & SQLITE_SHM_SHARED ){
4093 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4094
4095 /* Find out which shared locks are already held by sibling connections.
4096 ** If any sibling already holds an exclusive lock, go ahead and return
4097 ** SQLITE_BUSY.
4098 */
4099 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004100 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004101 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004102 break;
4103 }
4104 allShared |= pX->sharedMask;
4105 }
4106
4107 /* Get shared locks at the system level, if necessary */
4108 if( rc==SQLITE_OK ){
4109 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004110 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004111 }else{
drh73b64e42010-05-30 19:55:15 +00004112 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004113 }
drhd9e5c4f2010-05-12 18:01:39 +00004114 }
drh73b64e42010-05-30 19:55:15 +00004115
4116 /* Get the local shared locks */
4117 if( rc==SQLITE_OK ){
4118 p->sharedMask |= mask;
4119 }
4120 }else{
4121 /* Make sure no sibling connections hold locks that will block this
4122 ** lock. If any do, return SQLITE_BUSY right away.
4123 */
4124 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004125 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4126 rc = SQLITE_BUSY;
4127 break;
4128 }
4129 }
4130
4131 /* Get the exclusive locks at the system level. Then if successful
4132 ** also mark the local connection as being locked.
4133 */
4134 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004135 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004136 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004137 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004138 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004139 }
drhd9e5c4f2010-05-12 18:01:39 +00004140 }
4141 }
drhd91c68f2010-05-14 14:52:25 +00004142 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004143 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4144 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004145 return rc;
4146}
4147
drh286a2882010-05-20 23:51:06 +00004148/*
4149** Implement a memory barrier or memory fence on shared memory.
4150**
4151** All loads and stores begun before the barrier must complete before
4152** any load or store begun after the barrier.
4153*/
4154static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004155 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004156){
drhff828942010-06-26 21:34:06 +00004157 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004158 unixEnterMutex();
4159 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004160}
4161
dan18801912010-06-14 14:07:50 +00004162/*
danda9fe0c2010-07-13 18:44:03 +00004163** Close a connection to shared-memory. Delete the underlying
4164** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004165**
4166** If there is no shared memory associated with the connection then this
4167** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004168*/
danda9fe0c2010-07-13 18:44:03 +00004169static int unixShmUnmap(
4170 sqlite3_file *fd, /* The underlying database file */
4171 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004172){
danda9fe0c2010-07-13 18:44:03 +00004173 unixShm *p; /* The connection to be closed */
4174 unixShmNode *pShmNode; /* The underlying shared-memory file */
4175 unixShm **pp; /* For looping over sibling connections */
4176 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004177
danda9fe0c2010-07-13 18:44:03 +00004178 pDbFd = (unixFile*)fd;
4179 p = pDbFd->pShm;
4180 if( p==0 ) return SQLITE_OK;
4181 pShmNode = p->pShmNode;
4182
4183 assert( pShmNode==pDbFd->pInode->pShmNode );
4184 assert( pShmNode->pInode==pDbFd->pInode );
4185
4186 /* Remove connection p from the set of connections associated
4187 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004188 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004189 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4190 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004191
danda9fe0c2010-07-13 18:44:03 +00004192 /* Free the connection p */
4193 sqlite3_free(p);
4194 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004195 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004196
4197 /* If pShmNode->nRef has reached 0, then close the underlying
4198 ** shared-memory file, too */
4199 unixEnterMutex();
4200 assert( pShmNode->nRef>0 );
4201 pShmNode->nRef--;
4202 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004203 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004204 unixShmPurge(pDbFd);
4205 }
4206 unixLeaveMutex();
4207
4208 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004209}
drh286a2882010-05-20 23:51:06 +00004210
danda9fe0c2010-07-13 18:44:03 +00004211
drhd9e5c4f2010-05-12 18:01:39 +00004212#else
drh6b017cc2010-06-14 18:01:46 +00004213# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004214# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004215# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004216# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004217#endif /* #ifndef SQLITE_OMIT_WAL */
4218
drh734c9862008-11-28 15:37:20 +00004219/*
4220** Here ends the implementation of all sqlite3_file methods.
4221**
4222********************** End sqlite3_file Methods *******************************
4223******************************************************************************/
4224
4225/*
drh6b9d6dd2008-12-03 19:34:47 +00004226** This division contains definitions of sqlite3_io_methods objects that
4227** implement various file locking strategies. It also contains definitions
4228** of "finder" functions. A finder-function is used to locate the appropriate
4229** sqlite3_io_methods object for a particular database file. The pAppData
4230** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4231** the correct finder-function for that VFS.
4232**
4233** Most finder functions return a pointer to a fixed sqlite3_io_methods
4234** object. The only interesting finder-function is autolockIoFinder, which
4235** looks at the filesystem type and tries to guess the best locking
4236** strategy from that.
4237**
drh1875f7a2008-12-08 18:19:17 +00004238** For finder-funtion F, two objects are created:
4239**
4240** (1) The real finder-function named "FImpt()".
4241**
dane946c392009-08-22 11:39:46 +00004242** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004243**
4244**
4245** A pointer to the F pointer is used as the pAppData value for VFS
4246** objects. We have to do this instead of letting pAppData point
4247** directly at the finder-function since C90 rules prevent a void*
4248** from be cast into a function pointer.
4249**
drh6b9d6dd2008-12-03 19:34:47 +00004250**
drh7708e972008-11-29 00:56:52 +00004251** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004252**
drh7708e972008-11-29 00:56:52 +00004253** * A constant sqlite3_io_methods object call METHOD that has locking
4254** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4255**
4256** * An I/O method finder function called FINDER that returns a pointer
4257** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004258*/
drhd9e5c4f2010-05-12 18:01:39 +00004259#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004260static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004261 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004262 CLOSE, /* xClose */ \
4263 unixRead, /* xRead */ \
4264 unixWrite, /* xWrite */ \
4265 unixTruncate, /* xTruncate */ \
4266 unixSync, /* xSync */ \
4267 unixFileSize, /* xFileSize */ \
4268 LOCK, /* xLock */ \
4269 UNLOCK, /* xUnlock */ \
4270 CKLOCK, /* xCheckReservedLock */ \
4271 unixFileControl, /* xFileControl */ \
4272 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004273 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004274 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004275 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004276 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004277 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004278}; \
drh0c2694b2009-09-03 16:23:44 +00004279static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4280 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004281 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004282} \
drh0c2694b2009-09-03 16:23:44 +00004283static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004284 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004285
4286/*
4287** Here are all of the sqlite3_io_methods objects for each of the
4288** locking strategies. Functions that return pointers to these methods
4289** are also created.
4290*/
4291IOMETHODS(
4292 posixIoFinder, /* Finder function name */
4293 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004294 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004295 unixClose, /* xClose method */
4296 unixLock, /* xLock method */
4297 unixUnlock, /* xUnlock method */
4298 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004299)
drh7708e972008-11-29 00:56:52 +00004300IOMETHODS(
4301 nolockIoFinder, /* Finder function name */
4302 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004303 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004304 nolockClose, /* xClose method */
4305 nolockLock, /* xLock method */
4306 nolockUnlock, /* xUnlock method */
4307 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004308)
drh7708e972008-11-29 00:56:52 +00004309IOMETHODS(
4310 dotlockIoFinder, /* Finder function name */
4311 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004312 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004313 dotlockClose, /* xClose method */
4314 dotlockLock, /* xLock method */
4315 dotlockUnlock, /* xUnlock method */
4316 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004317)
drh7708e972008-11-29 00:56:52 +00004318
chw78a13182009-04-07 05:35:03 +00004319#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004320IOMETHODS(
4321 flockIoFinder, /* Finder function name */
4322 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004323 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004324 flockClose, /* xClose method */
4325 flockLock, /* xLock method */
4326 flockUnlock, /* xUnlock method */
4327 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004328)
drh7708e972008-11-29 00:56:52 +00004329#endif
4330
drh6c7d5c52008-11-21 20:32:33 +00004331#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004332IOMETHODS(
4333 semIoFinder, /* Finder function name */
4334 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004335 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004336 semClose, /* xClose method */
4337 semLock, /* xLock method */
4338 semUnlock, /* xUnlock method */
4339 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004340)
aswiftaebf4132008-11-21 00:10:35 +00004341#endif
drh7708e972008-11-29 00:56:52 +00004342
drhd2cb50b2009-01-09 21:41:17 +00004343#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004344IOMETHODS(
4345 afpIoFinder, /* Finder function name */
4346 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004347 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004348 afpClose, /* xClose method */
4349 afpLock, /* xLock method */
4350 afpUnlock, /* xUnlock method */
4351 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004352)
drh715ff302008-12-03 22:32:44 +00004353#endif
4354
4355/*
4356** The proxy locking method is a "super-method" in the sense that it
4357** opens secondary file descriptors for the conch and lock files and
4358** it uses proxy, dot-file, AFP, and flock() locking methods on those
4359** secondary files. For this reason, the division that implements
4360** proxy locking is located much further down in the file. But we need
4361** to go ahead and define the sqlite3_io_methods and finder function
4362** for proxy locking here. So we forward declare the I/O methods.
4363*/
drhd2cb50b2009-01-09 21:41:17 +00004364#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004365static int proxyClose(sqlite3_file*);
4366static int proxyLock(sqlite3_file*, int);
4367static int proxyUnlock(sqlite3_file*, int);
4368static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004369IOMETHODS(
4370 proxyIoFinder, /* Finder function name */
4371 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004372 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004373 proxyClose, /* xClose method */
4374 proxyLock, /* xLock method */
4375 proxyUnlock, /* xUnlock method */
4376 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004377)
aswiftaebf4132008-11-21 00:10:35 +00004378#endif
drh7708e972008-11-29 00:56:52 +00004379
drh7ed97b92010-01-20 13:07:21 +00004380/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4381#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4382IOMETHODS(
4383 nfsIoFinder, /* Finder function name */
4384 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004385 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004386 unixClose, /* xClose method */
4387 unixLock, /* xLock method */
4388 nfsUnlock, /* xUnlock method */
4389 unixCheckReservedLock /* xCheckReservedLock method */
4390)
4391#endif
drh7708e972008-11-29 00:56:52 +00004392
drhd2cb50b2009-01-09 21:41:17 +00004393#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004394/*
drh6b9d6dd2008-12-03 19:34:47 +00004395** This "finder" function attempts to determine the best locking strategy
4396** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004397** object that implements that strategy.
4398**
4399** This is for MacOSX only.
4400*/
drh1875f7a2008-12-08 18:19:17 +00004401static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004402 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004403 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004404){
4405 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004406 const char *zFilesystem; /* Filesystem type name */
4407 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004408 } aMap[] = {
4409 { "hfs", &posixIoMethods },
4410 { "ufs", &posixIoMethods },
4411 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004412 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004413 { "webdav", &nolockIoMethods },
4414 { 0, 0 }
4415 };
4416 int i;
4417 struct statfs fsInfo;
4418 struct flock lockInfo;
4419
4420 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004421 /* If filePath==NULL that means we are dealing with a transient file
4422 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004423 return &nolockIoMethods;
4424 }
4425 if( statfs(filePath, &fsInfo) != -1 ){
4426 if( fsInfo.f_flags & MNT_RDONLY ){
4427 return &nolockIoMethods;
4428 }
4429 for(i=0; aMap[i].zFilesystem; i++){
4430 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4431 return aMap[i].pMethods;
4432 }
4433 }
4434 }
4435
4436 /* Default case. Handles, amongst others, "nfs".
4437 ** Test byte-range lock using fcntl(). If the call succeeds,
4438 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004439 */
drh7708e972008-11-29 00:56:52 +00004440 lockInfo.l_len = 1;
4441 lockInfo.l_start = 0;
4442 lockInfo.l_whence = SEEK_SET;
4443 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004444 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004445 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4446 return &nfsIoMethods;
4447 } else {
4448 return &posixIoMethods;
4449 }
drh7708e972008-11-29 00:56:52 +00004450 }else{
4451 return &dotlockIoMethods;
4452 }
4453}
drh0c2694b2009-09-03 16:23:44 +00004454static const sqlite3_io_methods
4455 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004456
drhd2cb50b2009-01-09 21:41:17 +00004457#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004458
chw78a13182009-04-07 05:35:03 +00004459#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4460/*
4461** This "finder" function attempts to determine the best locking strategy
4462** for the database file "filePath". It then returns the sqlite3_io_methods
4463** object that implements that strategy.
4464**
4465** This is for VXWorks only.
4466*/
4467static const sqlite3_io_methods *autolockIoFinderImpl(
4468 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004469 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004470){
4471 struct flock lockInfo;
4472
4473 if( !filePath ){
4474 /* If filePath==NULL that means we are dealing with a transient file
4475 ** that does not need to be locked. */
4476 return &nolockIoMethods;
4477 }
4478
4479 /* Test if fcntl() is supported and use POSIX style locks.
4480 ** Otherwise fall back to the named semaphore method.
4481 */
4482 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 ) {
chw78a13182009-04-07 05:35:03 +00004487 return &posixIoMethods;
4488 }else{
4489 return &semIoMethods;
4490 }
4491}
drh0c2694b2009-09-03 16:23:44 +00004492static const sqlite3_io_methods
4493 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004494
4495#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4496
drh7708e972008-11-29 00:56:52 +00004497/*
4498** An abstract type for a pointer to a IO method finder function:
4499*/
drh0c2694b2009-09-03 16:23:44 +00004500typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004501
aswiftaebf4132008-11-21 00:10:35 +00004502
drh734c9862008-11-28 15:37:20 +00004503/****************************************************************************
4504**************************** sqlite3_vfs methods ****************************
4505**
4506** This division contains the implementation of methods on the
4507** sqlite3_vfs object.
4508*/
4509
danielk1977a3d4c882007-03-23 10:08:38 +00004510/*
danielk1977e339d652008-06-28 11:23:00 +00004511** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004512*/
4513static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004514 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004515 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004516 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004517 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004518 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004519 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004520 int isDelete, /* Delete on close if true */
4521 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004522){
drh7708e972008-11-29 00:56:52 +00004523 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004524 unixFile *pNew = (unixFile *)pId;
4525 int rc = SQLITE_OK;
4526
drh8af6c222010-05-14 12:43:01 +00004527 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004528
dane946c392009-08-22 11:39:46 +00004529 /* Parameter isDelete is only used on vxworks. Express this explicitly
4530 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004531 */
drh7708e972008-11-29 00:56:52 +00004532 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004533
dan00157392010-10-05 11:33:15 +00004534 /* Usually the path zFilename should not be a relative pathname. The
4535 ** exception is when opening the proxy "conch" file in builds that
4536 ** include the special Apple locking styles.
4537 */
dan00157392010-10-05 11:33:15 +00004538#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004539 assert( zFilename==0 || zFilename[0]=='/'
4540 || pVfs->pAppData==(void*)&autolockIoFinder );
4541#else
4542 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004543#endif
dan00157392010-10-05 11:33:15 +00004544
drhb07028f2011-10-14 21:49:18 +00004545 /* No locking occurs in temporary files */
4546 assert( zFilename!=0 || noLock );
4547
drh308c2a52010-05-14 11:30:18 +00004548 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004549 pNew->h = h;
drhd9e5c4f2010-05-12 18:01:39 +00004550 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004551 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4552 pNew->ctrlFlags = UNIXFILE_EXCL;
4553 }else{
4554 pNew->ctrlFlags = 0;
4555 }
drh77197112011-03-15 19:08:48 +00004556 if( isReadOnly ){
4557 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4558 }
drh0059eae2011-08-08 23:48:40 +00004559 if( syncDir ){
4560 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4561 }
drh339eb0b2008-03-07 15:34:11 +00004562
drh6c7d5c52008-11-21 20:32:33 +00004563#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004564 pNew->pId = vxworksFindFileId(zFilename);
4565 if( pNew->pId==0 ){
4566 noLock = 1;
4567 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004568 }
4569#endif
4570
drhda0e7682008-07-30 15:27:54 +00004571 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004572 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004573 }else{
drh0c2694b2009-09-03 16:23:44 +00004574 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004575#if SQLITE_ENABLE_LOCKING_STYLE
4576 /* Cache zFilename in the locking context (AFP and dotlock override) for
4577 ** proxyLock activation is possible (remote proxy is based on db name)
4578 ** zFilename remains valid until file is closed, to support */
4579 pNew->lockingContext = (void*)zFilename;
4580#endif
drhda0e7682008-07-30 15:27:54 +00004581 }
danielk1977e339d652008-06-28 11:23:00 +00004582
drh7ed97b92010-01-20 13:07:21 +00004583 if( pLockingStyle == &posixIoMethods
4584#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4585 || pLockingStyle == &nfsIoMethods
4586#endif
4587 ){
drh7708e972008-11-29 00:56:52 +00004588 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004589 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004590 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004591 /* If an error occured in findInodeInfo(), close the file descriptor
4592 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004593 ** in two scenarios:
4594 **
4595 ** (a) A call to fstat() failed.
4596 ** (b) A malloc failed.
4597 **
4598 ** Scenario (b) may only occur if the process is holding no other
4599 ** file descriptors open on the same file. If there were other file
4600 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004601 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004602 ** handle h - as it is guaranteed that no posix locks will be released
4603 ** by doing so.
4604 **
4605 ** If scenario (a) caused the error then things are not so safe. The
4606 ** implicit assumption here is that if fstat() fails, things are in
4607 ** such bad shape that dropping a lock or two doesn't matter much.
4608 */
drh0e9365c2011-03-02 02:08:13 +00004609 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004610 h = -1;
4611 }
drh7708e972008-11-29 00:56:52 +00004612 unixLeaveMutex();
4613 }
danielk1977e339d652008-06-28 11:23:00 +00004614
drhd2cb50b2009-01-09 21:41:17 +00004615#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004616 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004617 /* AFP locking uses the file path so it needs to be included in
4618 ** the afpLockingContext.
4619 */
4620 afpLockingContext *pCtx;
4621 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4622 if( pCtx==0 ){
4623 rc = SQLITE_NOMEM;
4624 }else{
4625 /* NB: zFilename exists and remains valid until the file is closed
4626 ** according to requirement F11141. So we do not need to make a
4627 ** copy of the filename. */
4628 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004629 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004630 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004631 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004632 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004633 if( rc!=SQLITE_OK ){
4634 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004635 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004636 h = -1;
4637 }
drh7708e972008-11-29 00:56:52 +00004638 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004639 }
drh7708e972008-11-29 00:56:52 +00004640 }
4641#endif
danielk1977e339d652008-06-28 11:23:00 +00004642
drh7708e972008-11-29 00:56:52 +00004643 else if( pLockingStyle == &dotlockIoMethods ){
4644 /* Dotfile locking uses the file path so it needs to be included in
4645 ** the dotlockLockingContext
4646 */
4647 char *zLockFile;
4648 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004649 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004650 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004651 zLockFile = (char *)sqlite3_malloc(nFilename);
4652 if( zLockFile==0 ){
4653 rc = SQLITE_NOMEM;
4654 }else{
4655 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004656 }
drh7708e972008-11-29 00:56:52 +00004657 pNew->lockingContext = zLockFile;
4658 }
danielk1977e339d652008-06-28 11:23:00 +00004659
drh6c7d5c52008-11-21 20:32:33 +00004660#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004661 else if( pLockingStyle == &semIoMethods ){
4662 /* Named semaphore locking uses the file path so it needs to be
4663 ** included in the semLockingContext
4664 */
4665 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004666 rc = findInodeInfo(pNew, &pNew->pInode);
4667 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4668 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004669 int n;
drh2238dcc2009-08-27 17:56:20 +00004670 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004671 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004672 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004673 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004674 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4675 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004676 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004677 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004678 }
chw97185482008-11-17 08:05:31 +00004679 }
drh7708e972008-11-29 00:56:52 +00004680 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004681 }
drh7708e972008-11-29 00:56:52 +00004682#endif
aswift5b1a2562008-08-22 00:22:35 +00004683
4684 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004685#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004686 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004687 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004688 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004689 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004690 isDelete = 0;
4691 }
4692 pNew->isDelete = isDelete;
4693#endif
danielk1977e339d652008-06-28 11:23:00 +00004694 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004695 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004696 }else{
drh7708e972008-11-29 00:56:52 +00004697 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004698 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004699 }
danielk1977e339d652008-06-28 11:23:00 +00004700 return rc;
drh054889e2005-11-30 03:20:31 +00004701}
drh9c06c952005-11-26 00:25:00 +00004702
danielk1977ad94b582007-08-20 06:44:22 +00004703/*
drh8b3cf822010-06-01 21:02:51 +00004704** Return the name of a directory in which to put temporary files.
4705** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004706*/
drh7234c6d2010-06-19 15:10:09 +00004707static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004708 static const char *azDirs[] = {
4709 0,
aswiftaebf4132008-11-21 00:10:35 +00004710 0,
danielk197717b90b52008-06-06 11:11:25 +00004711 "/var/tmp",
4712 "/usr/tmp",
4713 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004714 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004715 };
drh8b3cf822010-06-01 21:02:51 +00004716 unsigned int i;
4717 struct stat buf;
4718 const char *zDir = 0;
4719
4720 azDirs[0] = sqlite3_temp_directory;
4721 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004722 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004723 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004724 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004725 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004726 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004727 break;
4728 }
4729 return zDir;
4730}
4731
4732/*
4733** Create a temporary file name in zBuf. zBuf must be allocated
4734** by the calling process and must be big enough to hold at least
4735** pVfs->mxPathname bytes.
4736*/
4737static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004738 static const unsigned char zChars[] =
4739 "abcdefghijklmnopqrstuvwxyz"
4740 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4741 "0123456789";
drh41022642008-11-21 00:24:42 +00004742 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004743 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004744
4745 /* It's odd to simulate an io-error here, but really this is just
4746 ** using the io-error infrastructure to test that SQLite handles this
4747 ** function failing.
4748 */
4749 SimulateIOError( return SQLITE_IOERR );
4750
drh7234c6d2010-06-19 15:10:09 +00004751 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004752 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004753
4754 /* Check that the output buffer is large enough for the temporary file
4755 ** name. If it is not, return SQLITE_ERROR.
4756 */
danielk197700e13612008-11-17 19:18:54 +00004757 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004758 return SQLITE_ERROR;
4759 }
4760
4761 do{
4762 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004763 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004764 sqlite3_randomness(15, &zBuf[j]);
4765 for(i=0; i<15; i++, j++){
4766 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4767 }
4768 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004769 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004770 return SQLITE_OK;
4771}
4772
drhd2cb50b2009-01-09 21:41:17 +00004773#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004774/*
4775** Routine to transform a unixFile into a proxy-locking unixFile.
4776** Implementation in the proxy-lock division, but used by unixOpen()
4777** if SQLITE_PREFER_PROXY_LOCKING is defined.
4778*/
4779static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004780#endif
drhc66d5b62008-12-03 22:48:32 +00004781
dan08da86a2009-08-21 17:18:03 +00004782/*
4783** Search for an unused file descriptor that was opened on the database
4784** file (not a journal or master-journal file) identified by pathname
4785** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4786** argument to this function.
4787**
4788** Such a file descriptor may exist if a database connection was closed
4789** but the associated file descriptor could not be closed because some
4790** other file descriptor open on the same file is holding a file-lock.
4791** Refer to comments in the unixClose() function and the lengthy comment
4792** describing "Posix Advisory Locking" at the start of this file for
4793** further details. Also, ticket #4018.
4794**
4795** If a suitable file descriptor is found, then it is returned. If no
4796** such file descriptor is located, -1 is returned.
4797*/
dane946c392009-08-22 11:39:46 +00004798static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4799 UnixUnusedFd *pUnused = 0;
4800
4801 /* Do not search for an unused file descriptor on vxworks. Not because
4802 ** vxworks would not benefit from the change (it might, we're not sure),
4803 ** but because no way to test it is currently available. It is better
4804 ** not to risk breaking vxworks support for the sake of such an obscure
4805 ** feature. */
4806#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004807 struct stat sStat; /* Results of stat() call */
4808
4809 /* A stat() call may fail for various reasons. If this happens, it is
4810 ** almost certain that an open() call on the same path will also fail.
4811 ** For this reason, if an error occurs in the stat() call here, it is
4812 ** ignored and -1 is returned. The caller will try to open a new file
4813 ** descriptor on the same path, fail, and return an error to SQLite.
4814 **
4815 ** Even if a subsequent open() call does succeed, the consequences of
4816 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004817 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004818 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004819
4820 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004821 pInode = inodeList;
4822 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4823 || pInode->fileId.ino!=sStat.st_ino) ){
4824 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004825 }
drh8af6c222010-05-14 12:43:01 +00004826 if( pInode ){
dane946c392009-08-22 11:39:46 +00004827 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004828 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004829 pUnused = *pp;
4830 if( pUnused ){
4831 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004832 }
4833 }
4834 unixLeaveMutex();
4835 }
dane946c392009-08-22 11:39:46 +00004836#endif /* if !OS_VXWORKS */
4837 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004838}
danielk197717b90b52008-06-06 11:11:25 +00004839
4840/*
danddb0ac42010-07-14 14:48:58 +00004841** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004842** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004843** and a value suitable for passing as the third argument to open(2) is
4844** written to *pMode. If an IO error occurs, an SQLite error code is
4845** returned and the value of *pMode is not modified.
4846**
4847** If the file being opened is a temporary file, it is always created with
4848** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004849** is a database or master journal file, it is created with the permissions
4850** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004851**
drh8ab58662010-07-15 18:38:39 +00004852** Finally, if the file being opened is a WAL or regular journal file, then
4853** this function queries the file-system for the permissions on the
4854** corresponding database file and sets *pMode to this value. Whenever
4855** possible, WAL and journal files are created using the same permissions
4856** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004857**
4858** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4859** original filename is unavailable. But 8_3_NAMES is only used for
4860** FAT filesystems and permissions do not matter there, so just use
4861** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004862*/
4863static int findCreateFileMode(
4864 const char *zPath, /* Path of file (possibly) being created */
4865 int flags, /* Flags passed as 4th argument to xOpen() */
4866 mode_t *pMode /* OUT: Permissions to open file with */
4867){
4868 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004869 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004870 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004871 char zDb[MAX_PATHNAME+1]; /* Database file path */
4872 int nDb; /* Number of valid bytes in zDb */
4873 struct stat sStat; /* Output of stat() on database file */
4874
dana0c989d2010-11-05 18:07:37 +00004875 /* zPath is a path to a WAL or journal file. The following block derives
4876 ** the path to the associated database file from zPath. This block handles
4877 ** the following naming conventions:
4878 **
4879 ** "<path to db>-journal"
4880 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004881 ** "<path to db>-journalNN"
4882 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004883 **
drhd337c5b2011-10-20 18:23:35 +00004884 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004885 ** used by the test_multiplex.c module.
4886 */
4887 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004888#ifdef SQLITE_ENABLE_8_3_NAMES
drhd337c5b2011-10-20 18:23:35 +00004889 while( nDb>0 && !sqlite3Isalnum(zPath[nDb]) ) nDb--;
4890 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004891#else
4892 while( zPath[nDb]!='-' ){
4893 assert( nDb>0 );
4894 assert( zPath[nDb]!='\n' );
4895 nDb--;
4896 }
4897#endif
danddb0ac42010-07-14 14:48:58 +00004898 memcpy(zDb, zPath, nDb);
4899 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004900
drh58384f12011-07-28 00:14:45 +00004901 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004902 *pMode = sStat.st_mode & 0777;
4903 }else{
4904 rc = SQLITE_IOERR_FSTAT;
4905 }
4906 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4907 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004908 }
4909 return rc;
4910}
4911
4912/*
danielk1977ad94b582007-08-20 06:44:22 +00004913** Open the file zPath.
4914**
danielk1977b4b47412007-08-17 15:53:36 +00004915** Previously, the SQLite OS layer used three functions in place of this
4916** one:
4917**
4918** sqlite3OsOpenReadWrite();
4919** sqlite3OsOpenReadOnly();
4920** sqlite3OsOpenExclusive();
4921**
4922** These calls correspond to the following combinations of flags:
4923**
4924** ReadWrite() -> (READWRITE | CREATE)
4925** ReadOnly() -> (READONLY)
4926** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4927**
4928** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4929** true, the file was configured to be automatically deleted when the
4930** file handle closed. To achieve the same effect using this new
4931** interface, add the DELETEONCLOSE flag to those specified above for
4932** OpenExclusive().
4933*/
4934static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004935 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4936 const char *zPath, /* Pathname of file to be opened */
4937 sqlite3_file *pFile, /* The file descriptor to be filled in */
4938 int flags, /* Input flags to control the opening */
4939 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004940){
dan08da86a2009-08-21 17:18:03 +00004941 unixFile *p = (unixFile *)pFile;
4942 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004943 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004944 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004945 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004946 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004947
4948 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4949 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4950 int isCreate = (flags & SQLITE_OPEN_CREATE);
4951 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4952 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004953#if SQLITE_ENABLE_LOCKING_STYLE
4954 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4955#endif
drh3d4435b2011-08-26 20:55:50 +00004956#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4957 struct statfs fsInfo;
4958#endif
danielk1977b4b47412007-08-17 15:53:36 +00004959
danielk1977fee2d252007-08-18 10:59:19 +00004960 /* If creating a master or main-file journal, this function will open
4961 ** a file-descriptor on the directory too. The first time unixSync()
4962 ** is called the directory file descriptor will be fsync()ed and close()d.
4963 */
drh0059eae2011-08-08 23:48:40 +00004964 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00004965 eType==SQLITE_OPEN_MASTER_JOURNAL
4966 || eType==SQLITE_OPEN_MAIN_JOURNAL
4967 || eType==SQLITE_OPEN_WAL
4968 ));
danielk1977fee2d252007-08-18 10:59:19 +00004969
danielk197717b90b52008-06-06 11:11:25 +00004970 /* If argument zPath is a NULL pointer, this function is required to open
4971 ** a temporary file. Use this buffer to store the file name in.
4972 */
4973 char zTmpname[MAX_PATHNAME+1];
4974 const char *zName = zPath;
4975
danielk1977fee2d252007-08-18 10:59:19 +00004976 /* Check the following statements are true:
4977 **
4978 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4979 ** (b) if CREATE is set, then READWRITE must also be set, and
4980 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004981 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004982 */
danielk1977b4b47412007-08-17 15:53:36 +00004983 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004984 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004985 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004986 assert(isDelete==0 || isCreate);
4987
danddb0ac42010-07-14 14:48:58 +00004988 /* The main DB, main journal, WAL file and master journal are never
4989 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004990 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4991 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4992 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004993 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004994
danielk1977fee2d252007-08-18 10:59:19 +00004995 /* Assert that the upper layer has set one of the "file-type" flags. */
4996 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4997 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4998 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004999 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005000 );
5001
dan08da86a2009-08-21 17:18:03 +00005002 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005003
dan08da86a2009-08-21 17:18:03 +00005004 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005005 UnixUnusedFd *pUnused;
5006 pUnused = findReusableFd(zName, flags);
5007 if( pUnused ){
5008 fd = pUnused->fd;
5009 }else{
dan6aa657f2009-08-24 18:57:58 +00005010 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005011 if( !pUnused ){
5012 return SQLITE_NOMEM;
5013 }
5014 }
5015 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00005016 }else if( !zName ){
5017 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005018 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00005019 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005020 if( rc!=SQLITE_OK ){
5021 return rc;
5022 }
5023 zName = zTmpname;
5024 }
5025
dan08da86a2009-08-21 17:18:03 +00005026 /* Determine the value of the flags parameter passed to POSIX function
5027 ** open(). These must be calculated even if open() is not called, as
5028 ** they may be stored as part of the file handle and used by the
5029 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005030 if( isReadonly ) openFlags |= O_RDONLY;
5031 if( isReadWrite ) openFlags |= O_RDWR;
5032 if( isCreate ) openFlags |= O_CREAT;
5033 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5034 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005035
danielk1977b4b47412007-08-17 15:53:36 +00005036 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005037 mode_t openMode; /* Permissions to create file with */
5038 rc = findCreateFileMode(zName, flags, &openMode);
5039 if( rc!=SQLITE_OK ){
5040 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005041 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005042 return rc;
5043 }
drhad4f1e52011-03-04 15:43:57 +00005044 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005045 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005046 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5047 /* Failed to open the file for read/write access. Try read-only. */
5048 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005049 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005050 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005051 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005052 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005053 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005054 }
5055 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005056 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005057 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005058 }
danielk1977b4b47412007-08-17 15:53:36 +00005059 }
dan08da86a2009-08-21 17:18:03 +00005060 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005061 if( pOutFlags ){
5062 *pOutFlags = flags;
5063 }
5064
dane946c392009-08-22 11:39:46 +00005065 if( p->pUnused ){
5066 p->pUnused->fd = fd;
5067 p->pUnused->flags = flags;
5068 }
5069
danielk1977b4b47412007-08-17 15:53:36 +00005070 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005071#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005072 zPath = zName;
5073#else
drh036ac7f2011-08-08 23:18:05 +00005074 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005075#endif
danielk1977b4b47412007-08-17 15:53:36 +00005076 }
drh41022642008-11-21 00:24:42 +00005077#if SQLITE_ENABLE_LOCKING_STYLE
5078 else{
dan08da86a2009-08-21 17:18:03 +00005079 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005080 }
5081#endif
5082
danielk1977e339d652008-06-28 11:23:00 +00005083#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005084 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005085#endif
5086
drhda0e7682008-07-30 15:27:54 +00005087 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005088
drh7ed97b92010-01-20 13:07:21 +00005089
5090#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005091 if( fstatfs(fd, &fsInfo) == -1 ){
5092 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005093 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005094 return SQLITE_IOERR_ACCESS;
5095 }
5096 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5097 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5098 }
5099#endif
5100
5101#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005102#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005103 isAutoProxy = 1;
5104#endif
5105 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005106 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5107 int useProxy = 0;
5108
dan08da86a2009-08-21 17:18:03 +00005109 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5110 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005111 if( envforce!=NULL ){
5112 useProxy = atoi(envforce)>0;
5113 }else{
aswiftaebf4132008-11-21 00:10:35 +00005114 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005115 /* In theory, the close(fd) call is sub-optimal. If the file opened
5116 ** with fd is a database file, and there are other connections open
5117 ** on that file that are currently holding advisory locks on it,
5118 ** then the call to close() will cancel those locks. In practice,
5119 ** we're assuming that statfs() doesn't fail very often. At least
5120 ** not while other file descriptors opened by the same process on
5121 ** the same file are working. */
5122 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005123 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005124 rc = SQLITE_IOERR_ACCESS;
5125 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005126 }
5127 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5128 }
5129 if( useProxy ){
drh0059eae2011-08-08 23:48:40 +00005130 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005131 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005132 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005133 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005134 if( rc!=SQLITE_OK ){
5135 /* Use unixClose to clean up the resources added in fillInUnixFile
5136 ** and clear all the structure's references. Specifically,
5137 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5138 */
5139 unixClose(pFile);
5140 return rc;
5141 }
aswiftaebf4132008-11-21 00:10:35 +00005142 }
dane946c392009-08-22 11:39:46 +00005143 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005144 }
5145 }
5146#endif
5147
drh0059eae2011-08-08 23:48:40 +00005148 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005149 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005150open_finished:
5151 if( rc!=SQLITE_OK ){
5152 sqlite3_free(p->pUnused);
5153 }
5154 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005155}
5156
dane946c392009-08-22 11:39:46 +00005157
danielk1977b4b47412007-08-17 15:53:36 +00005158/*
danielk1977fee2d252007-08-18 10:59:19 +00005159** Delete the file at zPath. If the dirSync argument is true, fsync()
5160** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005161*/
drh6b9d6dd2008-12-03 19:34:47 +00005162static int unixDelete(
5163 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5164 const char *zPath, /* Name of file to be deleted */
5165 int dirSync /* If true, fsync() directory after deleting file */
5166){
danielk1977fee2d252007-08-18 10:59:19 +00005167 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005168 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005169 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005170 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005171 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005172 }
danielk1977d39fa702008-10-16 13:27:40 +00005173#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005174 if( dirSync ){
5175 int fd;
drh90315a22011-08-10 01:52:12 +00005176 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005177 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005178#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005179 if( fsync(fd)==-1 )
5180#else
5181 if( fsync(fd) )
5182#endif
5183 {
dane18d4952011-02-21 11:46:24 +00005184 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005185 }
drh0e9365c2011-03-02 02:08:13 +00005186 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005187 }else if( rc==SQLITE_CANTOPEN ){
5188 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005189 }
5190 }
danielk1977d138dd82008-10-15 16:02:48 +00005191#endif
danielk1977fee2d252007-08-18 10:59:19 +00005192 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005193}
5194
danielk197790949c22007-08-17 16:50:38 +00005195/*
5196** Test the existance of or access permissions of file zPath. The
5197** test performed depends on the value of flags:
5198**
5199** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5200** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5201** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5202**
5203** Otherwise return 0.
5204*/
danielk1977861f7452008-06-05 11:39:11 +00005205static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005206 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5207 const char *zPath, /* Path of the file to examine */
5208 int flags, /* What do we want to learn about the zPath file? */
5209 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005210){
rse25c0d1a2007-09-20 08:38:14 +00005211 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005212 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005213 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005214 switch( flags ){
5215 case SQLITE_ACCESS_EXISTS:
5216 amode = F_OK;
5217 break;
5218 case SQLITE_ACCESS_READWRITE:
5219 amode = W_OK|R_OK;
5220 break;
drh50d3f902007-08-27 21:10:36 +00005221 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005222 amode = R_OK;
5223 break;
5224
5225 default:
5226 assert(!"Invalid flags argument");
5227 }
drh99ab3b12011-03-02 15:09:07 +00005228 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005229 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5230 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005231 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005232 *pResOut = 0;
5233 }
5234 }
danielk1977861f7452008-06-05 11:39:11 +00005235 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005236}
5237
danielk1977b4b47412007-08-17 15:53:36 +00005238
5239/*
5240** Turn a relative pathname into a full pathname. The relative path
5241** is stored as a nul-terminated string in the buffer pointed to by
5242** zPath.
5243**
5244** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5245** (in this case, MAX_PATHNAME bytes). The full-path is written to
5246** this buffer before returning.
5247*/
danielk1977adfb9b02007-09-17 07:02:56 +00005248static int unixFullPathname(
5249 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5250 const char *zPath, /* Possibly relative input path */
5251 int nOut, /* Size of output buffer in bytes */
5252 char *zOut /* Output buffer */
5253){
danielk1977843e65f2007-09-01 16:16:15 +00005254
5255 /* It's odd to simulate an io-error here, but really this is just
5256 ** using the io-error infrastructure to test that SQLite handles this
5257 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005258 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005259 */
5260 SimulateIOError( return SQLITE_ERROR );
5261
drh153c62c2007-08-24 03:51:33 +00005262 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005263 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005264
drh3c7f2dc2007-12-06 13:26:20 +00005265 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005266 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005267 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005268 }else{
5269 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005270 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005271 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005272 }
drhea678832008-12-10 19:26:22 +00005273 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005274 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005275 }
5276 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005277}
5278
drh0ccebe72005-06-07 22:22:50 +00005279
drh761df872006-12-21 01:29:22 +00005280#ifndef SQLITE_OMIT_LOAD_EXTENSION
5281/*
5282** Interfaces for opening a shared library, finding entry points
5283** within the shared library, and closing the shared library.
5284*/
5285#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005286static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5287 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005288 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5289}
danielk197795c8a542007-09-01 06:51:27 +00005290
5291/*
5292** SQLite calls this function immediately after a call to unixDlSym() or
5293** unixDlOpen() fails (returns a null pointer). If a more detailed error
5294** message is available, it is written to zBufOut. If no error message
5295** is available, zBufOut is left unmodified and SQLite uses a default
5296** error message.
5297*/
danielk1977397d65f2008-11-19 11:35:39 +00005298static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005299 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005300 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005301 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005302 zErr = dlerror();
5303 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005304 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005305 }
drh6c7d5c52008-11-21 20:32:33 +00005306 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005307}
drh1875f7a2008-12-08 18:19:17 +00005308static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5309 /*
5310 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5311 ** cast into a pointer to a function. And yet the library dlsym() routine
5312 ** returns a void* which is really a pointer to a function. So how do we
5313 ** use dlsym() with -pedantic-errors?
5314 **
5315 ** Variable x below is defined to be a pointer to a function taking
5316 ** parameters void* and const char* and returning a pointer to a function.
5317 ** We initialize x by assigning it a pointer to the dlsym() function.
5318 ** (That assignment requires a cast.) Then we call the function that
5319 ** x points to.
5320 **
5321 ** This work-around is unlikely to work correctly on any system where
5322 ** you really cannot cast a function pointer into void*. But then, on the
5323 ** other hand, dlsym() will not work on such a system either, so we have
5324 ** not really lost anything.
5325 */
5326 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005327 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005328 x = (void(*(*)(void*,const char*))(void))dlsym;
5329 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005330}
danielk1977397d65f2008-11-19 11:35:39 +00005331static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5332 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005333 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005334}
danielk1977b4b47412007-08-17 15:53:36 +00005335#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5336 #define unixDlOpen 0
5337 #define unixDlError 0
5338 #define unixDlSym 0
5339 #define unixDlClose 0
5340#endif
5341
5342/*
danielk197790949c22007-08-17 16:50:38 +00005343** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005344*/
danielk1977397d65f2008-11-19 11:35:39 +00005345static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5346 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005347 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005348
drhbbd42a62004-05-22 17:41:58 +00005349 /* We have to initialize zBuf to prevent valgrind from reporting
5350 ** errors. The reports issued by valgrind are incorrect - we would
5351 ** prefer that the randomness be increased by making use of the
5352 ** uninitialized space in zBuf - but valgrind errors tend to worry
5353 ** some users. Rather than argue, it seems easier just to initialize
5354 ** the whole array and silence valgrind, even if that means less randomness
5355 ** in the random seed.
5356 **
5357 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005358 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005359 ** tests repeatable.
5360 */
danielk1977b4b47412007-08-17 15:53:36 +00005361 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005362#if !defined(SQLITE_TEST)
5363 {
drh842b8642005-01-21 17:53:17 +00005364 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005365 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005366 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005367 time_t t;
5368 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005369 memcpy(zBuf, &t, sizeof(t));
5370 pid = getpid();
5371 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005372 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005373 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005374 }else{
drhe562be52011-03-02 18:01:10 +00005375 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005376 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005377 }
drhbbd42a62004-05-22 17:41:58 +00005378 }
5379#endif
drh72cbd072008-10-14 17:58:38 +00005380 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005381}
5382
danielk1977b4b47412007-08-17 15:53:36 +00005383
drhbbd42a62004-05-22 17:41:58 +00005384/*
5385** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005386** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005387** The return value is the number of microseconds of sleep actually
5388** requested from the underlying operating system, a number which
5389** might be greater than or equal to the argument, but not less
5390** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005391*/
danielk1977397d65f2008-11-19 11:35:39 +00005392static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005393#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005394 struct timespec sp;
5395
5396 sp.tv_sec = microseconds / 1000000;
5397 sp.tv_nsec = (microseconds % 1000000) * 1000;
5398 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005399 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005400 return microseconds;
5401#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005402 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005403 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005404 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005405#else
danielk1977b4b47412007-08-17 15:53:36 +00005406 int seconds = (microseconds+999999)/1000000;
5407 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005408 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005409 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005410#endif
drh88f474a2006-01-02 20:00:12 +00005411}
5412
5413/*
drh6b9d6dd2008-12-03 19:34:47 +00005414** The following variable, if set to a non-zero value, is interpreted as
5415** the number of seconds since 1970 and is used to set the result of
5416** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005417*/
5418#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005419int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005420#endif
5421
5422/*
drhb7e8ea22010-05-03 14:32:30 +00005423** Find the current time (in Universal Coordinated Time). Write into *piNow
5424** the current time and date as a Julian Day number times 86_400_000. In
5425** other words, write into *piNow the number of milliseconds since the Julian
5426** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5427** proleptic Gregorian calendar.
5428**
drh31702252011-10-12 23:13:43 +00005429** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5430** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005431*/
5432static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5433 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005434 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005435#if defined(NO_GETTOD)
5436 time_t t;
5437 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005438 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005439#elif OS_VXWORKS
5440 struct timespec sNow;
5441 clock_gettime(CLOCK_REALTIME, &sNow);
5442 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5443#else
5444 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005445 if( gettimeofday(&sNow, 0)==0 ){
5446 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5447 }else{
5448 rc = SQLITE_ERROR;
5449 }
drhb7e8ea22010-05-03 14:32:30 +00005450#endif
5451
5452#ifdef SQLITE_TEST
5453 if( sqlite3_current_time ){
5454 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5455 }
5456#endif
5457 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005458 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005459}
5460
5461/*
drhbbd42a62004-05-22 17:41:58 +00005462** Find the current time (in Universal Coordinated Time). Write the
5463** current time and date as a Julian Day number into *prNow and
5464** return 0. Return 1 if the time and date cannot be found.
5465*/
danielk1977397d65f2008-11-19 11:35:39 +00005466static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005467 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005468 int rc;
drhff828942010-06-26 21:34:06 +00005469 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005470 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005471 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005472 return rc;
drhbbd42a62004-05-22 17:41:58 +00005473}
danielk1977b4b47412007-08-17 15:53:36 +00005474
drh6b9d6dd2008-12-03 19:34:47 +00005475/*
5476** We added the xGetLastError() method with the intention of providing
5477** better low-level error messages when operating-system problems come up
5478** during SQLite operation. But so far, none of that has been implemented
5479** in the core. So this routine is never called. For now, it is merely
5480** a place-holder.
5481*/
danielk1977397d65f2008-11-19 11:35:39 +00005482static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5483 UNUSED_PARAMETER(NotUsed);
5484 UNUSED_PARAMETER(NotUsed2);
5485 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005486 return 0;
5487}
5488
drhf2424c52010-04-26 00:04:55 +00005489
5490/*
drh734c9862008-11-28 15:37:20 +00005491************************ End of sqlite3_vfs methods ***************************
5492******************************************************************************/
5493
drh715ff302008-12-03 22:32:44 +00005494/******************************************************************************
5495************************** Begin Proxy Locking ********************************
5496**
5497** Proxy locking is a "uber-locking-method" in this sense: It uses the
5498** other locking methods on secondary lock files. Proxy locking is a
5499** meta-layer over top of the primitive locking implemented above. For
5500** this reason, the division that implements of proxy locking is deferred
5501** until late in the file (here) after all of the other I/O methods have
5502** been defined - so that the primitive locking methods are available
5503** as services to help with the implementation of proxy locking.
5504**
5505****
5506**
5507** The default locking schemes in SQLite use byte-range locks on the
5508** database file to coordinate safe, concurrent access by multiple readers
5509** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5510** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5511** as POSIX read & write locks over fixed set of locations (via fsctl),
5512** on AFP and SMB only exclusive byte-range locks are available via fsctl
5513** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5514** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5515** address in the shared range is taken for a SHARED lock, the entire
5516** shared range is taken for an EXCLUSIVE lock):
5517**
5518** PENDING_BYTE 0x40000000
5519** RESERVED_BYTE 0x40000001
5520** SHARED_RANGE 0x40000002 -> 0x40000200
5521**
5522** This works well on the local file system, but shows a nearly 100x
5523** slowdown in read performance on AFP because the AFP client disables
5524** the read cache when byte-range locks are present. Enabling the read
5525** cache exposes a cache coherency problem that is present on all OS X
5526** supported network file systems. NFS and AFP both observe the
5527** close-to-open semantics for ensuring cache coherency
5528** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5529** address the requirements for concurrent database access by multiple
5530** readers and writers
5531** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5532**
5533** To address the performance and cache coherency issues, proxy file locking
5534** changes the way database access is controlled by limiting access to a
5535** single host at a time and moving file locks off of the database file
5536** and onto a proxy file on the local file system.
5537**
5538**
5539** Using proxy locks
5540** -----------------
5541**
5542** C APIs
5543**
5544** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5545** <proxy_path> | ":auto:");
5546** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5547**
5548**
5549** SQL pragmas
5550**
5551** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5552** PRAGMA [database.]lock_proxy_file
5553**
5554** Specifying ":auto:" means that if there is a conch file with a matching
5555** host ID in it, the proxy path in the conch file will be used, otherwise
5556** a proxy path based on the user's temp dir
5557** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5558** actual proxy file name is generated from the name and path of the
5559** database file. For example:
5560**
5561** For database path "/Users/me/foo.db"
5562** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5563**
5564** Once a lock proxy is configured for a database connection, it can not
5565** be removed, however it may be switched to a different proxy path via
5566** the above APIs (assuming the conch file is not being held by another
5567** connection or process).
5568**
5569**
5570** How proxy locking works
5571** -----------------------
5572**
5573** Proxy file locking relies primarily on two new supporting files:
5574**
5575** * conch file to limit access to the database file to a single host
5576** at a time
5577**
5578** * proxy file to act as a proxy for the advisory locks normally
5579** taken on the database
5580**
5581** The conch file - to use a proxy file, sqlite must first "hold the conch"
5582** by taking an sqlite-style shared lock on the conch file, reading the
5583** contents and comparing the host's unique host ID (see below) and lock
5584** proxy path against the values stored in the conch. The conch file is
5585** stored in the same directory as the database file and the file name
5586** is patterned after the database file name as ".<databasename>-conch".
5587** If the conch file does not exist, or it's contents do not match the
5588** host ID and/or proxy path, then the lock is escalated to an exclusive
5589** lock and the conch file contents is updated with the host ID and proxy
5590** path and the lock is downgraded to a shared lock again. If the conch
5591** is held by another process (with a shared lock), the exclusive lock
5592** will fail and SQLITE_BUSY is returned.
5593**
5594** The proxy file - a single-byte file used for all advisory file locks
5595** normally taken on the database file. This allows for safe sharing
5596** of the database file for multiple readers and writers on the same
5597** host (the conch ensures that they all use the same local lock file).
5598**
drh715ff302008-12-03 22:32:44 +00005599** Requesting the lock proxy does not immediately take the conch, it is
5600** only taken when the first request to lock database file is made.
5601** This matches the semantics of the traditional locking behavior, where
5602** opening a connection to a database file does not take a lock on it.
5603** The shared lock and an open file descriptor are maintained until
5604** the connection to the database is closed.
5605**
5606** The proxy file and the lock file are never deleted so they only need
5607** to be created the first time they are used.
5608**
5609** Configuration options
5610** ---------------------
5611**
5612** SQLITE_PREFER_PROXY_LOCKING
5613**
5614** Database files accessed on non-local file systems are
5615** automatically configured for proxy locking, lock files are
5616** named automatically using the same logic as
5617** PRAGMA lock_proxy_file=":auto:"
5618**
5619** SQLITE_PROXY_DEBUG
5620**
5621** Enables the logging of error messages during host id file
5622** retrieval and creation
5623**
drh715ff302008-12-03 22:32:44 +00005624** LOCKPROXYDIR
5625**
5626** Overrides the default directory used for lock proxy files that
5627** are named automatically via the ":auto:" setting
5628**
5629** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5630**
5631** Permissions to use when creating a directory for storing the
5632** lock proxy files, only used when LOCKPROXYDIR is not set.
5633**
5634**
5635** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5636** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5637** force proxy locking to be used for every database file opened, and 0
5638** will force automatic proxy locking to be disabled for all database
5639** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5640** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5641*/
5642
5643/*
5644** Proxy locking is only available on MacOSX
5645*/
drhd2cb50b2009-01-09 21:41:17 +00005646#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005647
drh715ff302008-12-03 22:32:44 +00005648/*
5649** The proxyLockingContext has the path and file structures for the remote
5650** and local proxy files in it
5651*/
5652typedef struct proxyLockingContext proxyLockingContext;
5653struct proxyLockingContext {
5654 unixFile *conchFile; /* Open conch file */
5655 char *conchFilePath; /* Name of the conch file */
5656 unixFile *lockProxy; /* Open proxy lock file */
5657 char *lockProxyPath; /* Name of the proxy lock file */
5658 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005659 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005660 void *oldLockingContext; /* Original lockingcontext to restore on close */
5661 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5662};
5663
drh7ed97b92010-01-20 13:07:21 +00005664/*
5665** The proxy lock file path for the database at dbPath is written into lPath,
5666** which must point to valid, writable memory large enough for a maxLen length
5667** file path.
drh715ff302008-12-03 22:32:44 +00005668*/
drh715ff302008-12-03 22:32:44 +00005669static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5670 int len;
5671 int dbLen;
5672 int i;
5673
5674#ifdef LOCKPROXYDIR
5675 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5676#else
5677# ifdef _CS_DARWIN_USER_TEMP_DIR
5678 {
drh7ed97b92010-01-20 13:07:21 +00005679 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005680 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5681 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005682 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005683 }
drh7ed97b92010-01-20 13:07:21 +00005684 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005685 }
5686# else
5687 len = strlcpy(lPath, "/tmp/", maxLen);
5688# endif
5689#endif
5690
5691 if( lPath[len-1]!='/' ){
5692 len = strlcat(lPath, "/", maxLen);
5693 }
5694
5695 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005696 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005697 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005698 char c = dbPath[i];
5699 lPath[i+len] = (c=='/')?'_':c;
5700 }
5701 lPath[i+len]='\0';
5702 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005703 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005704 return SQLITE_OK;
5705}
5706
drh7ed97b92010-01-20 13:07:21 +00005707/*
5708 ** Creates the lock file and any missing directories in lockPath
5709 */
5710static int proxyCreateLockPath(const char *lockPath){
5711 int i, len;
5712 char buf[MAXPATHLEN];
5713 int start = 0;
5714
5715 assert(lockPath!=NULL);
5716 /* try to create all the intermediate directories */
5717 len = (int)strlen(lockPath);
5718 buf[0] = lockPath[0];
5719 for( i=1; i<len; i++ ){
5720 if( lockPath[i] == '/' && (i - start > 0) ){
5721 /* only mkdir if leaf dir != "." or "/" or ".." */
5722 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5723 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5724 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005725 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005726 int err=errno;
5727 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005728 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005729 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005730 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005731 return err;
5732 }
5733 }
5734 }
5735 start=i+1;
5736 }
5737 buf[i] = lockPath[i];
5738 }
drh308c2a52010-05-14 11:30:18 +00005739 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005740 return 0;
5741}
5742
drh715ff302008-12-03 22:32:44 +00005743/*
5744** Create a new VFS file descriptor (stored in memory obtained from
5745** sqlite3_malloc) and open the file named "path" in the file descriptor.
5746**
5747** The caller is responsible not only for closing the file descriptor
5748** but also for freeing the memory associated with the file descriptor.
5749*/
drh7ed97b92010-01-20 13:07:21 +00005750static int proxyCreateUnixFile(
5751 const char *path, /* path for the new unixFile */
5752 unixFile **ppFile, /* unixFile created and returned by ref */
5753 int islockfile /* if non zero missing dirs will be created */
5754) {
5755 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005756 unixFile *pNew;
5757 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005758 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005759 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005760 int terrno = 0;
5761 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005762
drh7ed97b92010-01-20 13:07:21 +00005763 /* 1. first try to open/create the file
5764 ** 2. if that fails, and this is a lock file (not-conch), try creating
5765 ** the parent directories and then try again.
5766 ** 3. if that fails, try to open the file read-only
5767 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5768 */
5769 pUnused = findReusableFd(path, openFlags);
5770 if( pUnused ){
5771 fd = pUnused->fd;
5772 }else{
5773 pUnused = sqlite3_malloc(sizeof(*pUnused));
5774 if( !pUnused ){
5775 return SQLITE_NOMEM;
5776 }
5777 }
5778 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005779 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005780 terrno = errno;
5781 if( fd<0 && errno==ENOENT && islockfile ){
5782 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005783 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005784 }
5785 }
5786 }
5787 if( fd<0 ){
5788 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005789 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005790 terrno = errno;
5791 }
5792 if( fd<0 ){
5793 if( islockfile ){
5794 return SQLITE_BUSY;
5795 }
5796 switch (terrno) {
5797 case EACCES:
5798 return SQLITE_PERM;
5799 case EIO:
5800 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5801 default:
drh9978c972010-02-23 17:36:32 +00005802 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005803 }
5804 }
5805
5806 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5807 if( pNew==NULL ){
5808 rc = SQLITE_NOMEM;
5809 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005810 }
5811 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005812 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005813 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005814 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005815 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005816 pUnused->fd = fd;
5817 pUnused->flags = openFlags;
5818 pNew->pUnused = pUnused;
5819
drh0059eae2011-08-08 23:48:40 +00005820 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005821 if( rc==SQLITE_OK ){
5822 *ppFile = pNew;
5823 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005824 }
drh7ed97b92010-01-20 13:07:21 +00005825end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005826 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005827 sqlite3_free(pNew);
5828 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005829 return rc;
5830}
5831
drh7ed97b92010-01-20 13:07:21 +00005832#ifdef SQLITE_TEST
5833/* simulate multiple hosts by creating unique hostid file paths */
5834int sqlite3_hostid_num = 0;
5835#endif
5836
5837#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5838
drh0ab216a2010-07-02 17:10:40 +00005839/* Not always defined in the headers as it ought to be */
5840extern int gethostuuid(uuid_t id, const struct timespec *wait);
5841
drh7ed97b92010-01-20 13:07:21 +00005842/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5843** bytes of writable memory.
5844*/
5845static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005846 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5847 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005848#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5849 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005850 {
5851 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5852 if( gethostuuid(pHostID, &timeout) ){
5853 int err = errno;
5854 if( pError ){
5855 *pError = err;
5856 }
5857 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005858 }
drh7ed97b92010-01-20 13:07:21 +00005859 }
drh3d4435b2011-08-26 20:55:50 +00005860#else
5861 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005862#endif
drh7ed97b92010-01-20 13:07:21 +00005863#ifdef SQLITE_TEST
5864 /* simulate multiple hosts by creating unique hostid file paths */
5865 if( sqlite3_hostid_num != 0){
5866 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5867 }
5868#endif
5869
5870 return SQLITE_OK;
5871}
5872
5873/* The conch file contains the header, host id and lock file path
5874 */
5875#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5876#define PROXY_HEADERLEN 1 /* conch file header length */
5877#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5878#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5879
5880/*
5881** Takes an open conch file, copies the contents to a new path and then moves
5882** it back. The newly created file's file descriptor is assigned to the
5883** conch file structure and finally the original conch file descriptor is
5884** closed. Returns zero if successful.
5885*/
5886static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5887 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5888 unixFile *conchFile = pCtx->conchFile;
5889 char tPath[MAXPATHLEN];
5890 char buf[PROXY_MAXCONCHLEN];
5891 char *cPath = pCtx->conchFilePath;
5892 size_t readLen = 0;
5893 size_t pathLen = 0;
5894 char errmsg[64] = "";
5895 int fd = -1;
5896 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005897 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005898
5899 /* create a new path by replace the trailing '-conch' with '-break' */
5900 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5901 if( pathLen>MAXPATHLEN || pathLen<6 ||
5902 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005903 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005904 goto end_breaklock;
5905 }
5906 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005907 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005908 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005909 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005910 goto end_breaklock;
5911 }
5912 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005913 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5914 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005915 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005916 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005917 goto end_breaklock;
5918 }
drhe562be52011-03-02 18:01:10 +00005919 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005920 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005921 goto end_breaklock;
5922 }
5923 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005924 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005925 goto end_breaklock;
5926 }
5927 rc = 0;
5928 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005929 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005930 conchFile->h = fd;
5931 conchFile->openFlags = O_RDWR | O_CREAT;
5932
5933end_breaklock:
5934 if( rc ){
5935 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005936 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005937 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005938 }
5939 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5940 }
5941 return rc;
5942}
5943
5944/* Take the requested lock on the conch file and break a stale lock if the
5945** host id matches.
5946*/
5947static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5948 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5949 unixFile *conchFile = pCtx->conchFile;
5950 int rc = SQLITE_OK;
5951 int nTries = 0;
5952 struct timespec conchModTime;
5953
drh3d4435b2011-08-26 20:55:50 +00005954 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00005955 do {
5956 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5957 nTries ++;
5958 if( rc==SQLITE_BUSY ){
5959 /* If the lock failed (busy):
5960 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5961 * 2nd try: fail if the mod time changed or host id is different, wait
5962 * 10 sec and try again
5963 * 3rd try: break the lock unless the mod time has changed.
5964 */
5965 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005966 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005967 pFile->lastErrno = errno;
5968 return SQLITE_IOERR_LOCK;
5969 }
5970
5971 if( nTries==1 ){
5972 conchModTime = buf.st_mtimespec;
5973 usleep(500000); /* wait 0.5 sec and try the lock again*/
5974 continue;
5975 }
5976
5977 assert( nTries>1 );
5978 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5979 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5980 return SQLITE_BUSY;
5981 }
5982
5983 if( nTries==2 ){
5984 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005985 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005986 if( len<0 ){
5987 pFile->lastErrno = errno;
5988 return SQLITE_IOERR_LOCK;
5989 }
5990 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5991 /* don't break the lock if the host id doesn't match */
5992 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5993 return SQLITE_BUSY;
5994 }
5995 }else{
5996 /* don't break the lock on short read or a version mismatch */
5997 return SQLITE_BUSY;
5998 }
5999 usleep(10000000); /* wait 10 sec and try the lock again */
6000 continue;
6001 }
6002
6003 assert( nTries==3 );
6004 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6005 rc = SQLITE_OK;
6006 if( lockType==EXCLUSIVE_LOCK ){
6007 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6008 }
6009 if( !rc ){
6010 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6011 }
6012 }
6013 }
6014 } while( rc==SQLITE_BUSY && nTries<3 );
6015
6016 return rc;
6017}
6018
6019/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006020** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6021** lockPath means that the lockPath in the conch file will be used if the
6022** host IDs match, or a new lock path will be generated automatically
6023** and written to the conch file.
6024*/
6025static int proxyTakeConch(unixFile *pFile){
6026 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6027
drh7ed97b92010-01-20 13:07:21 +00006028 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006029 return SQLITE_OK;
6030 }else{
6031 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006032 uuid_t myHostID;
6033 int pError = 0;
6034 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006035 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006036 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006037 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006038 int createConch = 0;
6039 int hostIdMatch = 0;
6040 int readLen = 0;
6041 int tryOldLockPath = 0;
6042 int forceNewLockPath = 0;
6043
drh308c2a52010-05-14 11:30:18 +00006044 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6045 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006046
drh7ed97b92010-01-20 13:07:21 +00006047 rc = proxyGetHostID(myHostID, &pError);
6048 if( (rc&0xff)==SQLITE_IOERR ){
6049 pFile->lastErrno = pError;
6050 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006051 }
drh7ed97b92010-01-20 13:07:21 +00006052 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006053 if( rc!=SQLITE_OK ){
6054 goto end_takeconch;
6055 }
drh7ed97b92010-01-20 13:07:21 +00006056 /* read the existing conch file */
6057 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6058 if( readLen<0 ){
6059 /* I/O error: lastErrno set by seekAndRead */
6060 pFile->lastErrno = conchFile->lastErrno;
6061 rc = SQLITE_IOERR_READ;
6062 goto end_takeconch;
6063 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6064 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6065 /* a short read or version format mismatch means we need to create a new
6066 ** conch file.
6067 */
6068 createConch = 1;
6069 }
6070 /* if the host id matches and the lock path already exists in the conch
6071 ** we'll try to use the path there, if we can't open that path, we'll
6072 ** retry with a new auto-generated path
6073 */
6074 do { /* in case we need to try again for an :auto: named lock file */
6075
6076 if( !createConch && !forceNewLockPath ){
6077 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6078 PROXY_HOSTIDLEN);
6079 /* if the conch has data compare the contents */
6080 if( !pCtx->lockProxyPath ){
6081 /* for auto-named local lock file, just check the host ID and we'll
6082 ** use the local lock file path that's already in there
6083 */
6084 if( hostIdMatch ){
6085 size_t pathLen = (readLen - PROXY_PATHINDEX);
6086
6087 if( pathLen>=MAXPATHLEN ){
6088 pathLen=MAXPATHLEN-1;
6089 }
6090 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6091 lockPath[pathLen] = 0;
6092 tempLockPath = lockPath;
6093 tryOldLockPath = 1;
6094 /* create a copy of the lock path if the conch is taken */
6095 goto end_takeconch;
6096 }
6097 }else if( hostIdMatch
6098 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6099 readLen-PROXY_PATHINDEX)
6100 ){
6101 /* conch host and lock path match */
6102 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006103 }
drh7ed97b92010-01-20 13:07:21 +00006104 }
6105
6106 /* if the conch isn't writable and doesn't match, we can't take it */
6107 if( (conchFile->openFlags&O_RDWR) == 0 ){
6108 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006109 goto end_takeconch;
6110 }
drh7ed97b92010-01-20 13:07:21 +00006111
6112 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006113 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006114 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6115 tempLockPath = lockPath;
6116 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006117 }
drh7ed97b92010-01-20 13:07:21 +00006118
6119 /* update conch with host and path (this will fail if other process
6120 ** has a shared lock already), if the host id matches, use the big
6121 ** stick.
drh715ff302008-12-03 22:32:44 +00006122 */
drh7ed97b92010-01-20 13:07:21 +00006123 futimes(conchFile->h, NULL);
6124 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006125 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006126 /* We are trying for an exclusive lock but another thread in this
6127 ** same process is still holding a shared lock. */
6128 rc = SQLITE_BUSY;
6129 } else {
6130 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006131 }
drh715ff302008-12-03 22:32:44 +00006132 }else{
drh7ed97b92010-01-20 13:07:21 +00006133 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006134 }
drh7ed97b92010-01-20 13:07:21 +00006135 if( rc==SQLITE_OK ){
6136 char writeBuffer[PROXY_MAXCONCHLEN];
6137 int writeSize = 0;
6138
6139 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6140 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6141 if( pCtx->lockProxyPath!=NULL ){
6142 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6143 }else{
6144 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6145 }
6146 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006147 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006148 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6149 fsync(conchFile->h);
6150 /* If we created a new conch file (not just updated the contents of a
6151 ** valid conch file), try to match the permissions of the database
6152 */
6153 if( rc==SQLITE_OK && createConch ){
6154 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006155 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006156 if( err==0 ){
6157 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6158 S_IROTH|S_IWOTH);
6159 /* try to match the database file R/W permissions, ignore failure */
6160#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006161 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006162#else
drhff812312011-02-23 13:33:46 +00006163 do{
drhe562be52011-03-02 18:01:10 +00006164 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006165 }while( rc==(-1) && errno==EINTR );
6166 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006167 int code = errno;
6168 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6169 cmode, code, strerror(code));
6170 } else {
6171 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6172 }
6173 }else{
6174 int code = errno;
6175 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6176 err, code, strerror(code));
6177#endif
6178 }
drh715ff302008-12-03 22:32:44 +00006179 }
6180 }
drh7ed97b92010-01-20 13:07:21 +00006181 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6182
6183 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006184 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006185 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006186 int fd;
drh7ed97b92010-01-20 13:07:21 +00006187 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006188 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006189 }
6190 pFile->h = -1;
drh3d4435b2011-08-26 20:55:50 +00006191 fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006192 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006193 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006194 if( fd>=0 ){
6195 pFile->h = fd;
6196 }else{
drh9978c972010-02-23 17:36:32 +00006197 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006198 during locking */
6199 }
6200 }
6201 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6202 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6203 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6204 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6205 /* we couldn't create the proxy lock file with the old lock file path
6206 ** so try again via auto-naming
6207 */
6208 forceNewLockPath = 1;
6209 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006210 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006211 }
6212 }
6213 if( rc==SQLITE_OK ){
6214 /* Need to make a copy of path if we extracted the value
6215 ** from the conch file or the path was allocated on the stack
6216 */
6217 if( tempLockPath ){
6218 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6219 if( !pCtx->lockProxyPath ){
6220 rc = SQLITE_NOMEM;
6221 }
6222 }
6223 }
6224 if( rc==SQLITE_OK ){
6225 pCtx->conchHeld = 1;
6226
6227 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6228 afpLockingContext *afpCtx;
6229 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6230 afpCtx->dbPath = pCtx->lockProxyPath;
6231 }
6232 } else {
6233 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6234 }
drh308c2a52010-05-14 11:30:18 +00006235 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6236 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006237 return rc;
drh308c2a52010-05-14 11:30:18 +00006238 } while (1); /* in case we need to retry the :auto: lock file -
6239 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006240 }
6241}
6242
6243/*
6244** If pFile holds a lock on a conch file, then release that lock.
6245*/
6246static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006247 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006248 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6249 unixFile *conchFile; /* Name of the conch file */
6250
6251 pCtx = (proxyLockingContext *)pFile->lockingContext;
6252 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006253 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006254 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006255 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006256 if( pCtx->conchHeld>0 ){
6257 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6258 }
drh715ff302008-12-03 22:32:44 +00006259 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006260 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6261 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006262 return rc;
6263}
6264
6265/*
6266** Given the name of a database file, compute the name of its conch file.
6267** Store the conch filename in memory obtained from sqlite3_malloc().
6268** Make *pConchPath point to the new name. Return SQLITE_OK on success
6269** or SQLITE_NOMEM if unable to obtain memory.
6270**
6271** The caller is responsible for ensuring that the allocated memory
6272** space is eventually freed.
6273**
6274** *pConchPath is set to NULL if a memory allocation error occurs.
6275*/
6276static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6277 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006278 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006279 char *conchPath; /* buffer in which to construct conch name */
6280
6281 /* Allocate space for the conch filename and initialize the name to
6282 ** the name of the original database file. */
6283 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6284 if( conchPath==0 ){
6285 return SQLITE_NOMEM;
6286 }
6287 memcpy(conchPath, dbPath, len+1);
6288
6289 /* now insert a "." before the last / character */
6290 for( i=(len-1); i>=0; i-- ){
6291 if( conchPath[i]=='/' ){
6292 i++;
6293 break;
6294 }
6295 }
6296 conchPath[i]='.';
6297 while ( i<len ){
6298 conchPath[i+1]=dbPath[i];
6299 i++;
6300 }
6301
6302 /* append the "-conch" suffix to the file */
6303 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006304 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006305
6306 return SQLITE_OK;
6307}
6308
6309
6310/* Takes a fully configured proxy locking-style unix file and switches
6311** the local lock file path
6312*/
6313static int switchLockProxyPath(unixFile *pFile, const char *path) {
6314 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6315 char *oldPath = pCtx->lockProxyPath;
6316 int rc = SQLITE_OK;
6317
drh308c2a52010-05-14 11:30:18 +00006318 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006319 return SQLITE_BUSY;
6320 }
6321
6322 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6323 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6324 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6325 return SQLITE_OK;
6326 }else{
6327 unixFile *lockProxy = pCtx->lockProxy;
6328 pCtx->lockProxy=NULL;
6329 pCtx->conchHeld = 0;
6330 if( lockProxy!=NULL ){
6331 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6332 if( rc ) return rc;
6333 sqlite3_free(lockProxy);
6334 }
6335 sqlite3_free(oldPath);
6336 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6337 }
6338
6339 return rc;
6340}
6341
6342/*
6343** pFile is a file that has been opened by a prior xOpen call. dbPath
6344** is a string buffer at least MAXPATHLEN+1 characters in size.
6345**
6346** This routine find the filename associated with pFile and writes it
6347** int dbPath.
6348*/
6349static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006350#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006351 if( pFile->pMethod == &afpIoMethods ){
6352 /* afp style keeps a reference to the db path in the filePath field
6353 ** of the struct */
drhea678832008-12-10 19:26:22 +00006354 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006355 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6356 } else
drh715ff302008-12-03 22:32:44 +00006357#endif
6358 if( pFile->pMethod == &dotlockIoMethods ){
6359 /* dot lock style uses the locking context to store the dot lock
6360 ** file path */
6361 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6362 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6363 }else{
6364 /* all other styles use the locking context to store the db file path */
6365 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006366 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006367 }
6368 return SQLITE_OK;
6369}
6370
6371/*
6372** Takes an already filled in unix file and alters it so all file locking
6373** will be performed on the local proxy lock file. The following fields
6374** are preserved in the locking context so that they can be restored and
6375** the unix structure properly cleaned up at close time:
6376** ->lockingContext
6377** ->pMethod
6378*/
6379static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6380 proxyLockingContext *pCtx;
6381 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6382 char *lockPath=NULL;
6383 int rc = SQLITE_OK;
6384
drh308c2a52010-05-14 11:30:18 +00006385 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006386 return SQLITE_BUSY;
6387 }
6388 proxyGetDbPathForUnixFile(pFile, dbPath);
6389 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6390 lockPath=NULL;
6391 }else{
6392 lockPath=(char *)path;
6393 }
6394
drh308c2a52010-05-14 11:30:18 +00006395 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6396 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006397
6398 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6399 if( pCtx==0 ){
6400 return SQLITE_NOMEM;
6401 }
6402 memset(pCtx, 0, sizeof(*pCtx));
6403
6404 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6405 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006406 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6407 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6408 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6409 ** (c) the file system is read-only, then enable no-locking access.
6410 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6411 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6412 */
6413 struct statfs fsInfo;
6414 struct stat conchInfo;
6415 int goLockless = 0;
6416
drh99ab3b12011-03-02 15:09:07 +00006417 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006418 int err = errno;
6419 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6420 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6421 }
6422 }
6423 if( goLockless ){
6424 pCtx->conchHeld = -1; /* read only FS/ lockless */
6425 rc = SQLITE_OK;
6426 }
6427 }
drh715ff302008-12-03 22:32:44 +00006428 }
6429 if( rc==SQLITE_OK && lockPath ){
6430 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6431 }
6432
6433 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006434 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6435 if( pCtx->dbPath==NULL ){
6436 rc = SQLITE_NOMEM;
6437 }
6438 }
6439 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006440 /* all memory is allocated, proxys are created and assigned,
6441 ** switch the locking context and pMethod then return.
6442 */
drh715ff302008-12-03 22:32:44 +00006443 pCtx->oldLockingContext = pFile->lockingContext;
6444 pFile->lockingContext = pCtx;
6445 pCtx->pOldMethod = pFile->pMethod;
6446 pFile->pMethod = &proxyIoMethods;
6447 }else{
6448 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006449 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006450 sqlite3_free(pCtx->conchFile);
6451 }
drhd56b1212010-08-11 06:14:15 +00006452 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006453 sqlite3_free(pCtx->conchFilePath);
6454 sqlite3_free(pCtx);
6455 }
drh308c2a52010-05-14 11:30:18 +00006456 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6457 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006458 return rc;
6459}
6460
6461
6462/*
6463** This routine handles sqlite3_file_control() calls that are specific
6464** to proxy locking.
6465*/
6466static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6467 switch( op ){
6468 case SQLITE_GET_LOCKPROXYFILE: {
6469 unixFile *pFile = (unixFile*)id;
6470 if( pFile->pMethod == &proxyIoMethods ){
6471 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6472 proxyTakeConch(pFile);
6473 if( pCtx->lockProxyPath ){
6474 *(const char **)pArg = pCtx->lockProxyPath;
6475 }else{
6476 *(const char **)pArg = ":auto: (not held)";
6477 }
6478 } else {
6479 *(const char **)pArg = NULL;
6480 }
6481 return SQLITE_OK;
6482 }
6483 case SQLITE_SET_LOCKPROXYFILE: {
6484 unixFile *pFile = (unixFile*)id;
6485 int rc = SQLITE_OK;
6486 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6487 if( pArg==NULL || (const char *)pArg==0 ){
6488 if( isProxyStyle ){
6489 /* turn off proxy locking - not supported */
6490 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6491 }else{
6492 /* turn off proxy locking - already off - NOOP */
6493 rc = SQLITE_OK;
6494 }
6495 }else{
6496 const char *proxyPath = (const char *)pArg;
6497 if( isProxyStyle ){
6498 proxyLockingContext *pCtx =
6499 (proxyLockingContext*)pFile->lockingContext;
6500 if( !strcmp(pArg, ":auto:")
6501 || (pCtx->lockProxyPath &&
6502 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6503 ){
6504 rc = SQLITE_OK;
6505 }else{
6506 rc = switchLockProxyPath(pFile, proxyPath);
6507 }
6508 }else{
6509 /* turn on proxy file locking */
6510 rc = proxyTransformUnixFile(pFile, proxyPath);
6511 }
6512 }
6513 return rc;
6514 }
6515 default: {
6516 assert( 0 ); /* The call assures that only valid opcodes are sent */
6517 }
6518 }
6519 /*NOTREACHED*/
6520 return SQLITE_ERROR;
6521}
6522
6523/*
6524** Within this division (the proxying locking implementation) the procedures
6525** above this point are all utilities. The lock-related methods of the
6526** proxy-locking sqlite3_io_method object follow.
6527*/
6528
6529
6530/*
6531** This routine checks if there is a RESERVED lock held on the specified
6532** file by this or any other process. If such a lock is held, set *pResOut
6533** to a non-zero value otherwise *pResOut is set to zero. The return value
6534** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6535*/
6536static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6537 unixFile *pFile = (unixFile*)id;
6538 int rc = proxyTakeConch(pFile);
6539 if( rc==SQLITE_OK ){
6540 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006541 if( pCtx->conchHeld>0 ){
6542 unixFile *proxy = pCtx->lockProxy;
6543 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6544 }else{ /* conchHeld < 0 is lockless */
6545 pResOut=0;
6546 }
drh715ff302008-12-03 22:32:44 +00006547 }
6548 return rc;
6549}
6550
6551/*
drh308c2a52010-05-14 11:30:18 +00006552** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006553** of the following:
6554**
6555** (1) SHARED_LOCK
6556** (2) RESERVED_LOCK
6557** (3) PENDING_LOCK
6558** (4) EXCLUSIVE_LOCK
6559**
6560** Sometimes when requesting one lock state, additional lock states
6561** are inserted in between. The locking might fail on one of the later
6562** transitions leaving the lock state different from what it started but
6563** still short of its goal. The following chart shows the allowed
6564** transitions and the inserted intermediate states:
6565**
6566** UNLOCKED -> SHARED
6567** SHARED -> RESERVED
6568** SHARED -> (PENDING) -> EXCLUSIVE
6569** RESERVED -> (PENDING) -> EXCLUSIVE
6570** PENDING -> EXCLUSIVE
6571**
6572** This routine will only increase a lock. Use the sqlite3OsUnlock()
6573** routine to lower a locking level.
6574*/
drh308c2a52010-05-14 11:30:18 +00006575static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006576 unixFile *pFile = (unixFile*)id;
6577 int rc = proxyTakeConch(pFile);
6578 if( rc==SQLITE_OK ){
6579 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006580 if( pCtx->conchHeld>0 ){
6581 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006582 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6583 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006584 }else{
6585 /* conchHeld < 0 is lockless */
6586 }
drh715ff302008-12-03 22:32:44 +00006587 }
6588 return rc;
6589}
6590
6591
6592/*
drh308c2a52010-05-14 11:30:18 +00006593** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006594** must be either NO_LOCK or SHARED_LOCK.
6595**
6596** If the locking level of the file descriptor is already at or below
6597** the requested locking level, this routine is a no-op.
6598*/
drh308c2a52010-05-14 11:30:18 +00006599static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006600 unixFile *pFile = (unixFile*)id;
6601 int rc = proxyTakeConch(pFile);
6602 if( rc==SQLITE_OK ){
6603 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006604 if( pCtx->conchHeld>0 ){
6605 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006606 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6607 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006608 }else{
6609 /* conchHeld < 0 is lockless */
6610 }
drh715ff302008-12-03 22:32:44 +00006611 }
6612 return rc;
6613}
6614
6615/*
6616** Close a file that uses proxy locks.
6617*/
6618static int proxyClose(sqlite3_file *id) {
6619 if( id ){
6620 unixFile *pFile = (unixFile*)id;
6621 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6622 unixFile *lockProxy = pCtx->lockProxy;
6623 unixFile *conchFile = pCtx->conchFile;
6624 int rc = SQLITE_OK;
6625
6626 if( lockProxy ){
6627 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6628 if( rc ) return rc;
6629 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6630 if( rc ) return rc;
6631 sqlite3_free(lockProxy);
6632 pCtx->lockProxy = 0;
6633 }
6634 if( conchFile ){
6635 if( pCtx->conchHeld ){
6636 rc = proxyReleaseConch(pFile);
6637 if( rc ) return rc;
6638 }
6639 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6640 if( rc ) return rc;
6641 sqlite3_free(conchFile);
6642 }
drhd56b1212010-08-11 06:14:15 +00006643 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006644 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006645 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006646 /* restore the original locking context and pMethod then close it */
6647 pFile->lockingContext = pCtx->oldLockingContext;
6648 pFile->pMethod = pCtx->pOldMethod;
6649 sqlite3_free(pCtx);
6650 return pFile->pMethod->xClose(id);
6651 }
6652 return SQLITE_OK;
6653}
6654
6655
6656
drhd2cb50b2009-01-09 21:41:17 +00006657#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006658/*
6659** The proxy locking style is intended for use with AFP filesystems.
6660** And since AFP is only supported on MacOSX, the proxy locking is also
6661** restricted to MacOSX.
6662**
6663**
6664******************* End of the proxy lock implementation **********************
6665******************************************************************************/
6666
drh734c9862008-11-28 15:37:20 +00006667/*
danielk1977e339d652008-06-28 11:23:00 +00006668** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006669**
6670** This routine registers all VFS implementations for unix-like operating
6671** systems. This routine, and the sqlite3_os_end() routine that follows,
6672** should be the only routines in this file that are visible from other
6673** files.
drh6b9d6dd2008-12-03 19:34:47 +00006674**
6675** This routine is called once during SQLite initialization and by a
6676** single thread. The memory allocation and mutex subsystems have not
6677** necessarily been initialized when this routine is called, and so they
6678** should not be used.
drh153c62c2007-08-24 03:51:33 +00006679*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006680int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006681 /*
6682 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006683 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6684 ** to the "finder" function. (pAppData is a pointer to a pointer because
6685 ** silly C90 rules prohibit a void* from being cast to a function pointer
6686 ** and so we have to go through the intermediate pointer to avoid problems
6687 ** when compiling with -pedantic-errors on GCC.)
6688 **
6689 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006690 ** finder-function. The finder-function returns a pointer to the
6691 ** sqlite_io_methods object that implements the desired locking
6692 ** behaviors. See the division above that contains the IOMETHODS
6693 ** macro for addition information on finder-functions.
6694 **
6695 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6696 ** object. But the "autolockIoFinder" available on MacOSX does a little
6697 ** more than that; it looks at the filesystem type that hosts the
6698 ** database file and tries to choose an locking method appropriate for
6699 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006700 */
drh7708e972008-11-29 00:56:52 +00006701 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006702 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006703 sizeof(unixFile), /* szOsFile */ \
6704 MAX_PATHNAME, /* mxPathname */ \
6705 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006706 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006707 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006708 unixOpen, /* xOpen */ \
6709 unixDelete, /* xDelete */ \
6710 unixAccess, /* xAccess */ \
6711 unixFullPathname, /* xFullPathname */ \
6712 unixDlOpen, /* xDlOpen */ \
6713 unixDlError, /* xDlError */ \
6714 unixDlSym, /* xDlSym */ \
6715 unixDlClose, /* xDlClose */ \
6716 unixRandomness, /* xRandomness */ \
6717 unixSleep, /* xSleep */ \
6718 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006719 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006720 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006721 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006722 unixGetSystemCall, /* xGetSystemCall */ \
6723 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006724 }
6725
drh6b9d6dd2008-12-03 19:34:47 +00006726 /*
6727 ** All default VFSes for unix are contained in the following array.
6728 **
6729 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6730 ** by the SQLite core when the VFS is registered. So the following
6731 ** array cannot be const.
6732 */
danielk1977e339d652008-06-28 11:23:00 +00006733 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006734#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006735 UNIXVFS("unix", autolockIoFinder ),
6736#else
6737 UNIXVFS("unix", posixIoFinder ),
6738#endif
6739 UNIXVFS("unix-none", nolockIoFinder ),
6740 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006741 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006742#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006743 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006744#endif
6745#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006746 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006747#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006748 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006749#endif
chw78a13182009-04-07 05:35:03 +00006750#endif
drhd2cb50b2009-01-09 21:41:17 +00006751#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006752 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006753 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006754 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006755#endif
drh153c62c2007-08-24 03:51:33 +00006756 };
drh6b9d6dd2008-12-03 19:34:47 +00006757 unsigned int i; /* Loop counter */
6758
drh2aa5a002011-04-13 13:42:25 +00006759 /* Double-check that the aSyscall[] array has been constructed
6760 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh9ef6bc42011-11-04 02:24:02 +00006761 assert( ArraySize(aSyscall)==20 );
drh2aa5a002011-04-13 13:42:25 +00006762
drh6b9d6dd2008-12-03 19:34:47 +00006763 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006764 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006765 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006766 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006767 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006768}
danielk1977e339d652008-06-28 11:23:00 +00006769
6770/*
drh6b9d6dd2008-12-03 19:34:47 +00006771** Shutdown the operating system interface.
6772**
6773** Some operating systems might need to do some cleanup in this routine,
6774** to release dynamically allocated objects. But not on unix.
6775** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006776*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006777int sqlite3_os_end(void){
6778 return SQLITE_OK;
6779}
drhdce8bdb2007-08-16 13:01:44 +00006780
danielk197729bafea2008-06-26 10:41:19 +00006781#endif /* SQLITE_OS_UNIX */