blob: dbf3c10120be27577212786d781379ebb588b696 [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 */
211 int dirfd; /* File descriptor for the directory */
212 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000213 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000214 int lastErrno; /* The unix errno from last I/O error */
215 void *lockingContext; /* Locking style specific state */
216 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000217 const char *zPath; /* Name of the file */
218 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000219 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000220#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000221 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000222#endif
drh7ed97b92010-01-20 13:07:21 +0000223#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000224 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
226#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000227 int isDelete; /* Delete on close if true */
228 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000229#endif
drh8f941bc2009-01-14 23:03:40 +0000230#ifndef NDEBUG
231 /* The next group of variables are used to track whether or not the
232 ** transaction counter in bytes 24-27 of database files are updated
233 ** whenever any part of the database changes. An assertion fault will
234 ** occur if a file is updated without also updating the transaction
235 ** counter. This test is made to avoid new problems similar to the
236 ** one described by ticket #3584.
237 */
238 unsigned char transCntrChng; /* True if the transaction counter changed */
239 unsigned char dbUpdate; /* True if any part of database file changed */
240 unsigned char inNormalWrite; /* True if in a normal write operation */
241#endif
danielk1977967a4a12007-08-20 14:23:44 +0000242#ifdef SQLITE_TEST
243 /* In test mode, increase the size of this structure a bit so that
244 ** it is larger than the struct CrashFile defined in test6.c.
245 */
246 char aPadding[32];
247#endif
drh9cbe6352005-11-29 03:13:21 +0000248};
249
drh0ccebe72005-06-07 22:22:50 +0000250/*
drha7e61d82011-03-12 17:02:57 +0000251** Allowed values for the unixFile.ctrlFlags bitmask:
252*/
drhf0b190d2011-07-26 16:03:07 +0000253#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
254#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
255#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
drha7e61d82011-03-12 17:02:57 +0000256
257/*
drh198bf392006-01-06 21:52:49 +0000258** Include code that is common to all os_*.c files
259*/
260#include "os_common.h"
261
262/*
drh0ccebe72005-06-07 22:22:50 +0000263** Define various macros that are missing from some systems.
264*/
drhbbd42a62004-05-22 17:41:58 +0000265#ifndef O_LARGEFILE
266# define O_LARGEFILE 0
267#endif
268#ifdef SQLITE_DISABLE_LFS
269# undef O_LARGEFILE
270# define O_LARGEFILE 0
271#endif
272#ifndef O_NOFOLLOW
273# define O_NOFOLLOW 0
274#endif
275#ifndef O_BINARY
276# define O_BINARY 0
277#endif
278
279/*
drh2b4b5962005-06-15 17:47:55 +0000280** The threadid macro resolves to the thread-id or to 0. Used for
281** testing and debugging only.
282*/
drhd677b3d2007-08-20 22:48:41 +0000283#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000284#define threadid pthread_self()
285#else
286#define threadid 0
287#endif
288
drh99ab3b12011-03-02 15:09:07 +0000289/*
drh9a3baf12011-04-25 18:01:27 +0000290** Different Unix systems declare open() in different ways. Same use
291** open(const char*,int,mode_t). Others use open(const char*,int,...).
292** The difference is important when using a pointer to the function.
293**
294** The safest way to deal with the problem is to always use this wrapper
295** which always has the same well-defined interface.
296*/
297static int posixOpen(const char *zFile, int flags, int mode){
298 return open(zFile, flags, mode);
299}
300
301/*
drh99ab3b12011-03-02 15:09:07 +0000302** Many system calls are accessed through pointer-to-functions so that
303** they may be overridden at runtime to facilitate fault injection during
304** testing and sandboxing. The following array holds the names and pointers
305** to all overrideable system calls.
306*/
307static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000308 const char *zName; /* Name of the sytem call */
309 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
310 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000311} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000312 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
313#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000314
drh58ad5802011-03-23 22:02:23 +0000315 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000316#define osClose ((int(*)(int))aSyscall[1].pCurrent)
317
drh58ad5802011-03-23 22:02:23 +0000318 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000319#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
320
drh58ad5802011-03-23 22:02:23 +0000321 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000322#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
323
drh58ad5802011-03-23 22:02:23 +0000324 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000325#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
326
327/*
328** The DJGPP compiler environment looks mostly like Unix, but it
329** lacks the fcntl() system call. So redefine fcntl() to be something
330** that always succeeds. This means that locking does not occur under
331** DJGPP. But it is DOS - what did you expect?
332*/
333#ifdef __DJGPP__
334 { "fstat", 0, 0 },
335#define osFstat(a,b,c) 0
336#else
drh58ad5802011-03-23 22:02:23 +0000337 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000338#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
339#endif
340
drh58ad5802011-03-23 22:02:23 +0000341 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000342#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
343
drh58ad5802011-03-23 22:02:23 +0000344 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000346
drh58ad5802011-03-23 22:02:23 +0000347 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000348#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
349
drhd4a80312011-04-15 14:33:20 +0000350#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000351 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000352#else
drh58ad5802011-03-23 22:02:23 +0000353 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000354#endif
355#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
356
357#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000358 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000359#else
drh58ad5802011-03-23 22:02:23 +0000360 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000361#endif
362#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
363
drh58ad5802011-03-23 22:02:23 +0000364 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000365#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
366
drhd4a80312011-04-15 14:33:20 +0000367#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000368 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000369#else
drh58ad5802011-03-23 22:02:23 +0000370 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000371#endif
372#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
373 aSyscall[12].pCurrent)
374
375#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000376 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000377#else
drh58ad5802011-03-23 22:02:23 +0000378 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000379#endif
380#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
381 aSyscall[13].pCurrent)
382
drha6c47492011-04-11 18:35:09 +0000383#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000384 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000385#else
386 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000387#endif
drh2aa5a002011-04-13 13:42:25 +0000388#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000389
390#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000391 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000392#else
drh58ad5802011-03-23 22:02:23 +0000393 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000394#endif
dan0fd7d862011-03-29 10:04:23 +0000395#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000396
397}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000398
399/*
400** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000401** "unix" VFSes. Return SQLITE_OK opon successfully updating the
402** system call pointer, or SQLITE_NOTFOUND if there is no configurable
403** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000404*/
405static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000406 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
407 const char *zName, /* Name of system call to override */
408 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000409){
drh58ad5802011-03-23 22:02:23 +0000410 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000411 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000412
413 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000414 if( zName==0 ){
415 /* If no zName is given, restore all system calls to their default
416 ** settings and return NULL
417 */
dan51438a72011-04-02 17:00:47 +0000418 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000419 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
420 if( aSyscall[i].pDefault ){
421 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000422 }
423 }
424 }else{
425 /* If zName is specified, operate on only the one system call
426 ** specified.
427 */
428 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
429 if( strcmp(zName, aSyscall[i].zName)==0 ){
430 if( aSyscall[i].pDefault==0 ){
431 aSyscall[i].pDefault = aSyscall[i].pCurrent;
432 }
drh1df30962011-03-02 19:06:42 +0000433 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000434 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
435 aSyscall[i].pCurrent = pNewFunc;
436 break;
437 }
438 }
439 }
440 return rc;
441}
442
drh1df30962011-03-02 19:06:42 +0000443/*
444** Return the value of a system call. Return NULL if zName is not a
445** recognized system call name. NULL is also returned if the system call
446** is currently undefined.
447*/
drh58ad5802011-03-23 22:02:23 +0000448static sqlite3_syscall_ptr unixGetSystemCall(
449 sqlite3_vfs *pNotUsed,
450 const char *zName
451){
452 unsigned int i;
453
454 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000455 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
456 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
457 }
458 return 0;
459}
460
461/*
462** Return the name of the first system call after zName. If zName==NULL
463** then return the name of the first system call. Return NULL if zName
464** is the last system call or if zName is not the name of a valid
465** system call.
466*/
467static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000468 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000469
470 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000471 if( zName ){
472 for(i=0; i<ArraySize(aSyscall)-1; i++){
473 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000474 }
475 }
dan0fd7d862011-03-29 10:04:23 +0000476 for(i++; i<ArraySize(aSyscall); i++){
477 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000478 }
479 return 0;
480}
481
drhad4f1e52011-03-04 15:43:57 +0000482/*
483** Retry open() calls that fail due to EINTR
484*/
485static int robust_open(const char *z, int f, int m){
486 int rc;
487 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
488 return rc;
489}
danielk197713adf8a2004-06-03 16:08:41 +0000490
drh107886a2008-11-21 22:21:50 +0000491/*
dan9359c7b2009-08-21 08:29:10 +0000492** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000493** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000494** vxworksFileId objects used by this file, all of which may be
495** shared by multiple threads.
496**
497** Function unixMutexHeld() is used to assert() that the global mutex
498** is held when required. This function is only used as part of assert()
499** statements. e.g.
500**
501** unixEnterMutex()
502** assert( unixMutexHeld() );
503** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000504*/
505static void unixEnterMutex(void){
506 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
507}
508static void unixLeaveMutex(void){
509 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
510}
dan9359c7b2009-08-21 08:29:10 +0000511#ifdef SQLITE_DEBUG
512static int unixMutexHeld(void) {
513 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
514}
515#endif
drh107886a2008-11-21 22:21:50 +0000516
drh734c9862008-11-28 15:37:20 +0000517
518#ifdef SQLITE_DEBUG
519/*
520** Helper function for printing out trace information from debugging
521** binaries. This returns the string represetation of the supplied
522** integer lock-type.
523*/
drh308c2a52010-05-14 11:30:18 +0000524static const char *azFileLock(int eFileLock){
525 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000526 case NO_LOCK: return "NONE";
527 case SHARED_LOCK: return "SHARED";
528 case RESERVED_LOCK: return "RESERVED";
529 case PENDING_LOCK: return "PENDING";
530 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000531 }
532 return "ERROR";
533}
534#endif
535
536#ifdef SQLITE_LOCK_TRACE
537/*
538** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000539**
drh734c9862008-11-28 15:37:20 +0000540** This routine is used for troubleshooting locks on multithreaded
541** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
542** command-line option on the compiler. This code is normally
543** turned off.
544*/
545static int lockTrace(int fd, int op, struct flock *p){
546 char *zOpName, *zType;
547 int s;
548 int savedErrno;
549 if( op==F_GETLK ){
550 zOpName = "GETLK";
551 }else if( op==F_SETLK ){
552 zOpName = "SETLK";
553 }else{
drh99ab3b12011-03-02 15:09:07 +0000554 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000555 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
556 return s;
557 }
558 if( p->l_type==F_RDLCK ){
559 zType = "RDLCK";
560 }else if( p->l_type==F_WRLCK ){
561 zType = "WRLCK";
562 }else if( p->l_type==F_UNLCK ){
563 zType = "UNLCK";
564 }else{
565 assert( 0 );
566 }
567 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000568 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000569 savedErrno = errno;
570 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
571 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
572 (int)p->l_pid, s);
573 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
574 struct flock l2;
575 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000576 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000577 if( l2.l_type==F_RDLCK ){
578 zType = "RDLCK";
579 }else if( l2.l_type==F_WRLCK ){
580 zType = "WRLCK";
581 }else if( l2.l_type==F_UNLCK ){
582 zType = "UNLCK";
583 }else{
584 assert( 0 );
585 }
586 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
587 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
588 }
589 errno = savedErrno;
590 return s;
591}
drh99ab3b12011-03-02 15:09:07 +0000592#undef osFcntl
593#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000594#endif /* SQLITE_LOCK_TRACE */
595
drhff812312011-02-23 13:33:46 +0000596/*
597** Retry ftruncate() calls that fail due to EINTR
598*/
drhff812312011-02-23 13:33:46 +0000599static int robust_ftruncate(int h, sqlite3_int64 sz){
600 int rc;
drh99ab3b12011-03-02 15:09:07 +0000601 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000602 return rc;
603}
drh734c9862008-11-28 15:37:20 +0000604
605/*
606** This routine translates a standard POSIX errno code into something
607** useful to the clients of the sqlite3 functions. Specifically, it is
608** intended to translate a variety of "try again" errors into SQLITE_BUSY
609** and a variety of "please close the file descriptor NOW" errors into
610** SQLITE_IOERR
611**
612** Errors during initialization of locks, or file system support for locks,
613** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
614*/
615static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
616 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000617#if 0
618 /* At one point this code was not commented out. In theory, this branch
619 ** should never be hit, as this function should only be called after
620 ** a locking-related function (i.e. fcntl()) has returned non-zero with
621 ** the value of errno as the first argument. Since a system call has failed,
622 ** errno should be non-zero.
623 **
624 ** Despite this, if errno really is zero, we still don't want to return
625 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
626 ** propagated back to the caller. Commenting this branch out means errno==0
627 ** will be handled by the "default:" case below.
628 */
drh734c9862008-11-28 15:37:20 +0000629 case 0:
630 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000631#endif
632
drh734c9862008-11-28 15:37:20 +0000633 case EAGAIN:
634 case ETIMEDOUT:
635 case EBUSY:
636 case EINTR:
637 case ENOLCK:
638 /* random NFS retry error, unless during file system support
639 * introspection, in which it actually means what it says */
640 return SQLITE_BUSY;
641
642 case EACCES:
643 /* EACCES is like EAGAIN during locking operations, but not any other time*/
644 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
645 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
646 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
647 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
648 return SQLITE_BUSY;
649 }
650 /* else fall through */
651 case EPERM:
652 return SQLITE_PERM;
653
danea83bc62011-04-01 11:56:32 +0000654 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
655 ** this module never makes such a call. And the code in SQLite itself
656 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
657 ** this case is also commented out. If the system does set errno to EDEADLK,
658 ** the default SQLITE_IOERR_XXX code will be returned. */
659#if 0
drh734c9862008-11-28 15:37:20 +0000660 case EDEADLK:
661 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000662#endif
drh734c9862008-11-28 15:37:20 +0000663
664#if EOPNOTSUPP!=ENOTSUP
665 case EOPNOTSUPP:
666 /* something went terribly awry, unless during file system support
667 * introspection, in which it actually means what it says */
668#endif
669#ifdef ENOTSUP
670 case ENOTSUP:
671 /* invalid fd, unless during file system support introspection, in which
672 * it actually means what it says */
673#endif
674 case EIO:
675 case EBADF:
676 case EINVAL:
677 case ENOTCONN:
678 case ENODEV:
679 case ENXIO:
680 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000681#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000682 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000683#endif
drh734c9862008-11-28 15:37:20 +0000684 case ENOSYS:
685 /* these should force the client to close the file and reconnect */
686
687 default:
688 return sqliteIOErr;
689 }
690}
691
692
693
694/******************************************************************************
695****************** Begin Unique File ID Utility Used By VxWorks ***************
696**
697** On most versions of unix, we can get a unique ID for a file by concatenating
698** the device number and the inode number. But this does not work on VxWorks.
699** On VxWorks, a unique file id must be based on the canonical filename.
700**
701** A pointer to an instance of the following structure can be used as a
702** unique file ID in VxWorks. Each instance of this structure contains
703** a copy of the canonical filename. There is also a reference count.
704** The structure is reclaimed when the number of pointers to it drops to
705** zero.
706**
707** There are never very many files open at one time and lookups are not
708** a performance-critical path, so it is sufficient to put these
709** structures on a linked list.
710*/
711struct vxworksFileId {
712 struct vxworksFileId *pNext; /* Next in a list of them all */
713 int nRef; /* Number of references to this one */
714 int nName; /* Length of the zCanonicalName[] string */
715 char *zCanonicalName; /* Canonical filename */
716};
717
718#if OS_VXWORKS
719/*
drh9b35ea62008-11-29 02:20:26 +0000720** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000721** variable:
722*/
723static struct vxworksFileId *vxworksFileList = 0;
724
725/*
726** Simplify a filename into its canonical form
727** by making the following changes:
728**
729** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000730** * convert /./ into just /
731** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000732**
733** Changes are made in-place. Return the new name length.
734**
735** The original filename is in z[0..n-1]. Return the number of
736** characters in the simplified name.
737*/
738static int vxworksSimplifyName(char *z, int n){
739 int i, j;
740 while( n>1 && z[n-1]=='/' ){ n--; }
741 for(i=j=0; i<n; i++){
742 if( z[i]=='/' ){
743 if( z[i+1]=='/' ) continue;
744 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
745 i += 1;
746 continue;
747 }
748 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
749 while( j>0 && z[j-1]!='/' ){ j--; }
750 if( j>0 ){ j--; }
751 i += 2;
752 continue;
753 }
754 }
755 z[j++] = z[i];
756 }
757 z[j] = 0;
758 return j;
759}
760
761/*
762** Find a unique file ID for the given absolute pathname. Return
763** a pointer to the vxworksFileId object. This pointer is the unique
764** file ID.
765**
766** The nRef field of the vxworksFileId object is incremented before
767** the object is returned. A new vxworksFileId object is created
768** and added to the global list if necessary.
769**
770** If a memory allocation error occurs, return NULL.
771*/
772static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
773 struct vxworksFileId *pNew; /* search key and new file ID */
774 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
775 int n; /* Length of zAbsoluteName string */
776
777 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000778 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000779 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
780 if( pNew==0 ) return 0;
781 pNew->zCanonicalName = (char*)&pNew[1];
782 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
783 n = vxworksSimplifyName(pNew->zCanonicalName, n);
784
785 /* Search for an existing entry that matching the canonical name.
786 ** If found, increment the reference count and return a pointer to
787 ** the existing file ID.
788 */
789 unixEnterMutex();
790 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
791 if( pCandidate->nName==n
792 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
793 ){
794 sqlite3_free(pNew);
795 pCandidate->nRef++;
796 unixLeaveMutex();
797 return pCandidate;
798 }
799 }
800
801 /* No match was found. We will make a new file ID */
802 pNew->nRef = 1;
803 pNew->nName = n;
804 pNew->pNext = vxworksFileList;
805 vxworksFileList = pNew;
806 unixLeaveMutex();
807 return pNew;
808}
809
810/*
811** Decrement the reference count on a vxworksFileId object. Free
812** the object when the reference count reaches zero.
813*/
814static void vxworksReleaseFileId(struct vxworksFileId *pId){
815 unixEnterMutex();
816 assert( pId->nRef>0 );
817 pId->nRef--;
818 if( pId->nRef==0 ){
819 struct vxworksFileId **pp;
820 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
821 assert( *pp==pId );
822 *pp = pId->pNext;
823 sqlite3_free(pId);
824 }
825 unixLeaveMutex();
826}
827#endif /* OS_VXWORKS */
828/*************** End of Unique File ID Utility Used By VxWorks ****************
829******************************************************************************/
830
831
832/******************************************************************************
833*************************** Posix Advisory Locking ****************************
834**
drh9b35ea62008-11-29 02:20:26 +0000835** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000836** section 6.5.2.2 lines 483 through 490 specify that when a process
837** sets or clears a lock, that operation overrides any prior locks set
838** by the same process. It does not explicitly say so, but this implies
839** that it overrides locks set by the same process using a different
840** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000841**
842** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000843** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
844**
845** Suppose ./file1 and ./file2 are really the same file (because
846** one is a hard or symbolic link to the other) then if you set
847** an exclusive lock on fd1, then try to get an exclusive lock
848** on fd2, it works. I would have expected the second lock to
849** fail since there was already a lock on the file due to fd1.
850** But not so. Since both locks came from the same process, the
851** second overrides the first, even though they were on different
852** file descriptors opened on different file names.
853**
drh734c9862008-11-28 15:37:20 +0000854** This means that we cannot use POSIX locks to synchronize file access
855** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000856** to synchronize access for threads in separate processes, but not
857** threads within the same process.
858**
859** To work around the problem, SQLite has to manage file locks internally
860** on its own. Whenever a new database is opened, we have to find the
861** specific inode of the database file (the inode is determined by the
862** st_dev and st_ino fields of the stat structure that fstat() fills in)
863** and check for locks already existing on that inode. When locks are
864** created or removed, we have to look at our own internal record of the
865** locks to see if another thread has previously set a lock on that same
866** inode.
867**
drh9b35ea62008-11-29 02:20:26 +0000868** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
869** For VxWorks, we have to use the alternative unique ID system based on
870** canonical filename and implemented in the previous division.)
871**
danielk1977ad94b582007-08-20 06:44:22 +0000872** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000873** descriptor. It is now a structure that holds the integer file
874** descriptor and a pointer to a structure that describes the internal
875** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000876** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000877** point to the same locking structure. The locking structure keeps
878** a reference count (so we will know when to delete it) and a "cnt"
879** field that tells us its internal lock status. cnt==0 means the
880** file is unlocked. cnt==-1 means the file has an exclusive lock.
881** cnt>0 means there are cnt shared locks on the file.
882**
883** Any attempt to lock or unlock a file first checks the locking
884** structure. The fcntl() system call is only invoked to set a
885** POSIX lock if the internal lock structure transitions between
886** a locked and an unlocked state.
887**
drh734c9862008-11-28 15:37:20 +0000888** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000889**
890** If you close a file descriptor that points to a file that has locks,
891** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000892** released. To work around this problem, each unixInodeInfo object
893** maintains a count of the number of pending locks on tha inode.
894** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000895** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000896** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000897** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000898** be closed and that list is walked (and cleared) when the last lock
899** clears.
900**
drh9b35ea62008-11-29 02:20:26 +0000901** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000902**
drh9b35ea62008-11-29 02:20:26 +0000903** Many older versions of linux use the LinuxThreads library which is
904** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000905** A cannot be modified or overridden by a different thread B.
906** Only thread A can modify the lock. Locking behavior is correct
907** if the appliation uses the newer Native Posix Thread Library (NPTL)
908** on linux - with NPTL a lock created by thread A can override locks
909** in thread B. But there is no way to know at compile-time which
910** threading library is being used. So there is no way to know at
911** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000912** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000913** current process.
drh5fdae772004-06-29 03:29:00 +0000914**
drh8af6c222010-05-14 12:43:01 +0000915** SQLite used to support LinuxThreads. But support for LinuxThreads
916** was dropped beginning with version 3.7.0. SQLite will still work with
917** LinuxThreads provided that (1) there is no more than one connection
918** per database file in the same process and (2) database connections
919** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000920*/
921
922/*
923** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000924** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000925*/
926struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000927 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000928#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000929 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000930#else
drh107886a2008-11-21 22:21:50 +0000931 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000932#endif
933};
934
935/*
drhbbd42a62004-05-22 17:41:58 +0000936** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000937** inode. Or, on LinuxThreads, there is one of these structures for
938** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000939**
danielk1977ad94b582007-08-20 06:44:22 +0000940** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000941** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000942** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000943*/
drh8af6c222010-05-14 12:43:01 +0000944struct unixInodeInfo {
945 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000946 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000947 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
948 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000949 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000950 unixShmNode *pShmNode; /* Shared memory associated with this inode */
951 int nLock; /* Number of outstanding file locks */
952 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
953 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
954 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000955#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000956 unsigned long long sharedByte; /* for AFP simulated shared lock */
957#endif
drh6c7d5c52008-11-21 20:32:33 +0000958#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000959 sem_t *pSem; /* Named POSIX semaphore */
960 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000961#endif
drhbbd42a62004-05-22 17:41:58 +0000962};
963
drhda0e7682008-07-30 15:27:54 +0000964/*
drh8af6c222010-05-14 12:43:01 +0000965** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000966*/
drhd91c68f2010-05-14 14:52:25 +0000967static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000968
drh5fdae772004-06-29 03:29:00 +0000969/*
dane18d4952011-02-21 11:46:24 +0000970**
971** This function - unixLogError_x(), is only ever called via the macro
972** unixLogError().
973**
974** It is invoked after an error occurs in an OS function and errno has been
975** set. It logs a message using sqlite3_log() containing the current value of
976** errno and, if possible, the human-readable equivalent from strerror() or
977** strerror_r().
978**
979** The first argument passed to the macro should be the error code that
980** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
981** The two subsequent arguments should be the name of the OS function that
982** failed (e.g. "unlink", "open") and the the associated file-system path,
983** if any.
984*/
drh0e9365c2011-03-02 02:08:13 +0000985#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
986static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000987 int errcode, /* SQLite error code */
988 const char *zFunc, /* Name of OS function that failed */
989 const char *zPath, /* File path associated with error */
990 int iLine /* Source line number where error occurred */
991){
992 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000993 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000994
995 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
996 ** the strerror() function to obtain the human-readable error message
997 ** equivalent to errno. Otherwise, use strerror_r().
998 */
999#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1000 char aErr[80];
1001 memset(aErr, 0, sizeof(aErr));
1002 zErr = aErr;
1003
1004 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1005 ** assume that the system provides the the GNU version of strerror_r() that
1006 ** returns a pointer to a buffer containing the error message. That pointer
1007 ** may point to aErr[], or it may point to some static storage somewhere.
1008 ** Otherwise, assume that the system provides the POSIX version of
1009 ** strerror_r(), which always writes an error message into aErr[].
1010 **
1011 ** If the code incorrectly assumes that it is the POSIX version that is
1012 ** available, the error message will often be an empty string. Not a
1013 ** huge problem. Incorrectly concluding that the GNU version is available
1014 ** could lead to a segfault though.
1015 */
1016#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1017 zErr =
1018# endif
drh0e9365c2011-03-02 02:08:13 +00001019 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001020
1021#elif SQLITE_THREADSAFE
1022 /* This is a threadsafe build, but strerror_r() is not available. */
1023 zErr = "";
1024#else
1025 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001026 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001027#endif
1028
1029 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001030 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001031 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001032 "os_unix.c:%d: (%d) %s(%s) - %s",
1033 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001034 );
1035
1036 return errcode;
1037}
1038
drh0e9365c2011-03-02 02:08:13 +00001039/*
1040** Close a file descriptor.
1041**
1042** We assume that close() almost always works, since it is only in a
1043** very sick application or on a very sick platform that it might fail.
1044** If it does fail, simply leak the file descriptor, but do log the
1045** error.
1046**
1047** Note that it is not safe to retry close() after EINTR since the
1048** file descriptor might have already been reused by another thread.
1049** So we don't even try to recover from an EINTR. Just log the error
1050** and move on.
1051*/
1052static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001053 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001054 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1055 pFile ? pFile->zPath : 0, lineno);
1056 }
1057}
dane18d4952011-02-21 11:46:24 +00001058
1059/*
danb0ac3e32010-06-16 10:55:42 +00001060** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001061*/
drh0e9365c2011-03-02 02:08:13 +00001062static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001063 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001064 UnixUnusedFd *p;
1065 UnixUnusedFd *pNext;
1066 for(p=pInode->pUnused; p; p=pNext){
1067 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001068 robust_close(pFile, p->fd, __LINE__);
1069 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001070 }
drh0e9365c2011-03-02 02:08:13 +00001071 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001072}
1073
1074/*
drh8af6c222010-05-14 12:43:01 +00001075** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001076**
1077** The mutex entered using the unixEnterMutex() function must be held
1078** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001079*/
danb0ac3e32010-06-16 10:55:42 +00001080static void releaseInodeInfo(unixFile *pFile){
1081 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001082 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001083 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001084 pInode->nRef--;
1085 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001086 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001087 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001088 if( pInode->pPrev ){
1089 assert( pInode->pPrev->pNext==pInode );
1090 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001091 }else{
drh8af6c222010-05-14 12:43:01 +00001092 assert( inodeList==pInode );
1093 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001094 }
drh8af6c222010-05-14 12:43:01 +00001095 if( pInode->pNext ){
1096 assert( pInode->pNext->pPrev==pInode );
1097 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001098 }
drh8af6c222010-05-14 12:43:01 +00001099 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001100 }
drhbbd42a62004-05-22 17:41:58 +00001101 }
1102}
1103
1104/*
drh8af6c222010-05-14 12:43:01 +00001105** Given a file descriptor, locate the unixInodeInfo object that
1106** describes that file descriptor. Create a new one if necessary. The
1107** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001108**
dan9359c7b2009-08-21 08:29:10 +00001109** The mutex entered using the unixEnterMutex() function must be held
1110** when this function is called.
1111**
drh6c7d5c52008-11-21 20:32:33 +00001112** Return an appropriate error code.
1113*/
drh8af6c222010-05-14 12:43:01 +00001114static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001115 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001116 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001117){
1118 int rc; /* System call return code */
1119 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001120 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1121 struct stat statbuf; /* Low-level file information */
1122 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001123
dan9359c7b2009-08-21 08:29:10 +00001124 assert( unixMutexHeld() );
1125
drh6c7d5c52008-11-21 20:32:33 +00001126 /* Get low-level information about the file that we can used to
1127 ** create a unique name for the file.
1128 */
1129 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001130 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001131 if( rc!=0 ){
1132 pFile->lastErrno = errno;
1133#ifdef EOVERFLOW
1134 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1135#endif
1136 return SQLITE_IOERR;
1137 }
1138
drheb0d74f2009-02-03 15:27:02 +00001139#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001140 /* On OS X on an msdos filesystem, the inode number is reported
1141 ** incorrectly for zero-size files. See ticket #3260. To work
1142 ** around this problem (we consider it a bug in OS X, not SQLite)
1143 ** we always increase the file size to 1 by writing a single byte
1144 ** prior to accessing the inode number. The one byte written is
1145 ** an ASCII 'S' character which also happens to be the first byte
1146 ** in the header of every SQLite database. In this way, if there
1147 ** is a race condition such that another thread has already populated
1148 ** the first page of the database, no damage is done.
1149 */
drh7ed97b92010-01-20 13:07:21 +00001150 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001151 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001152 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001153 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001154 return SQLITE_IOERR;
1155 }
drh99ab3b12011-03-02 15:09:07 +00001156 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001157 if( rc!=0 ){
1158 pFile->lastErrno = errno;
1159 return SQLITE_IOERR;
1160 }
1161 }
drheb0d74f2009-02-03 15:27:02 +00001162#endif
drh6c7d5c52008-11-21 20:32:33 +00001163
drh8af6c222010-05-14 12:43:01 +00001164 memset(&fileId, 0, sizeof(fileId));
1165 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001166#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001167 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001168#else
drh8af6c222010-05-14 12:43:01 +00001169 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001170#endif
drh8af6c222010-05-14 12:43:01 +00001171 pInode = inodeList;
1172 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1173 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001174 }
drh8af6c222010-05-14 12:43:01 +00001175 if( pInode==0 ){
1176 pInode = sqlite3_malloc( sizeof(*pInode) );
1177 if( pInode==0 ){
1178 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001179 }
drh8af6c222010-05-14 12:43:01 +00001180 memset(pInode, 0, sizeof(*pInode));
1181 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1182 pInode->nRef = 1;
1183 pInode->pNext = inodeList;
1184 pInode->pPrev = 0;
1185 if( inodeList ) inodeList->pPrev = pInode;
1186 inodeList = pInode;
1187 }else{
1188 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001189 }
drh8af6c222010-05-14 12:43:01 +00001190 *ppInode = pInode;
1191 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001192}
drh6c7d5c52008-11-21 20:32:33 +00001193
aswift5b1a2562008-08-22 00:22:35 +00001194
1195/*
danielk197713adf8a2004-06-03 16:08:41 +00001196** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001197** file by this or any other process. If such a lock is held, set *pResOut
1198** to a non-zero value otherwise *pResOut is set to zero. The return value
1199** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001200*/
danielk1977861f7452008-06-05 11:39:11 +00001201static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001202 int rc = SQLITE_OK;
1203 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001204 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001205
danielk1977861f7452008-06-05 11:39:11 +00001206 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1207
drh054889e2005-11-30 03:20:31 +00001208 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001209 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001210
1211 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001212 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001213 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001214 }
1215
drh2ac3ee92004-06-07 16:27:46 +00001216 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001217 */
danielk197709480a92009-02-09 05:32:32 +00001218#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001219 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001220 struct flock lock;
1221 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001222 lock.l_start = RESERVED_BYTE;
1223 lock.l_len = 1;
1224 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001225 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1226 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1227 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001228 } else if( lock.l_type!=F_UNLCK ){
1229 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001230 }
1231 }
danielk197709480a92009-02-09 05:32:32 +00001232#endif
danielk197713adf8a2004-06-03 16:08:41 +00001233
drh6c7d5c52008-11-21 20:32:33 +00001234 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001235 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001236
aswift5b1a2562008-08-22 00:22:35 +00001237 *pResOut = reserved;
1238 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001239}
1240
1241/*
drha7e61d82011-03-12 17:02:57 +00001242** Attempt to set a system-lock on the file pFile. The lock is
1243** described by pLock.
1244**
drh77197112011-03-15 19:08:48 +00001245** If the pFile was opened read/write from unix-excl, then the only lock
1246** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001247** the first time any lock is attempted. All subsequent system locking
1248** operations become no-ops. Locking operations still happen internally,
1249** in order to coordinate access between separate database connections
1250** within this process, but all of that is handled in memory and the
1251** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001252**
1253** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1254** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1255** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001256**
1257** Zero is returned if the call completes successfully, or -1 if a call
1258** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001259*/
1260static int unixFileLock(unixFile *pFile, struct flock *pLock){
1261 int rc;
drh3cb93392011-03-12 18:10:44 +00001262 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001263 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001264 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001265 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1266 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1267 ){
drh3cb93392011-03-12 18:10:44 +00001268 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001269 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001270 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001271 lock.l_whence = SEEK_SET;
1272 lock.l_start = SHARED_FIRST;
1273 lock.l_len = SHARED_SIZE;
1274 lock.l_type = F_WRLCK;
1275 rc = osFcntl(pFile->h, F_SETLK, &lock);
1276 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001277 pInode->bProcessLock = 1;
1278 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001279 }else{
1280 rc = 0;
1281 }
1282 }else{
1283 rc = osFcntl(pFile->h, F_SETLK, pLock);
1284 }
1285 return rc;
1286}
1287
1288/*
drh308c2a52010-05-14 11:30:18 +00001289** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001290** of the following:
1291**
drh2ac3ee92004-06-07 16:27:46 +00001292** (1) SHARED_LOCK
1293** (2) RESERVED_LOCK
1294** (3) PENDING_LOCK
1295** (4) EXCLUSIVE_LOCK
1296**
drhb3e04342004-06-08 00:47:47 +00001297** Sometimes when requesting one lock state, additional lock states
1298** are inserted in between. The locking might fail on one of the later
1299** transitions leaving the lock state different from what it started but
1300** still short of its goal. The following chart shows the allowed
1301** transitions and the inserted intermediate states:
1302**
1303** UNLOCKED -> SHARED
1304** SHARED -> RESERVED
1305** SHARED -> (PENDING) -> EXCLUSIVE
1306** RESERVED -> (PENDING) -> EXCLUSIVE
1307** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001308**
drha6abd042004-06-09 17:37:22 +00001309** This routine will only increase a lock. Use the sqlite3OsUnlock()
1310** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001311*/
drh308c2a52010-05-14 11:30:18 +00001312static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001313 /* The following describes the implementation of the various locks and
1314 ** lock transitions in terms of the POSIX advisory shared and exclusive
1315 ** lock primitives (called read-locks and write-locks below, to avoid
1316 ** confusion with SQLite lock names). The algorithms are complicated
1317 ** slightly in order to be compatible with windows systems simultaneously
1318 ** accessing the same database file, in case that is ever required.
1319 **
1320 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1321 ** byte', each single bytes at well known offsets, and the 'shared byte
1322 ** range', a range of 510 bytes at a well known offset.
1323 **
1324 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1325 ** byte'. If this is successful, a random byte from the 'shared byte
1326 ** range' is read-locked and the lock on the 'pending byte' released.
1327 **
danielk197790ba3bd2004-06-25 08:32:25 +00001328 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1329 ** A RESERVED lock is implemented by grabbing a write-lock on the
1330 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001331 **
1332 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001333 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1334 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1335 ** obtained, but existing SHARED locks are allowed to persist. A process
1336 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1337 ** This property is used by the algorithm for rolling back a journal file
1338 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001339 **
danielk197790ba3bd2004-06-25 08:32:25 +00001340 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1341 ** implemented by obtaining a write-lock on the entire 'shared byte
1342 ** range'. Since all other locks require a read-lock on one of the bytes
1343 ** within this range, this ensures that no other locks are held on the
1344 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001345 **
1346 ** The reason a single byte cannot be used instead of the 'shared byte
1347 ** range' is that some versions of windows do not support read-locks. By
1348 ** locking a random byte from a range, concurrent SHARED locks may exist
1349 ** even if the locking primitive used is always a write-lock.
1350 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001351 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001352 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001353 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001354 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001355 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001356
drh054889e2005-11-30 03:20:31 +00001357 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001358 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1359 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001360 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001361
1362 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001363 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001364 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001365 */
drh308c2a52010-05-14 11:30:18 +00001366 if( pFile->eFileLock>=eFileLock ){
1367 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1368 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001369 return SQLITE_OK;
1370 }
1371
drh0c2694b2009-09-03 16:23:44 +00001372 /* Make sure the locking sequence is correct.
1373 ** (1) We never move from unlocked to anything higher than shared lock.
1374 ** (2) SQLite never explicitly requests a pendig lock.
1375 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001376 */
drh308c2a52010-05-14 11:30:18 +00001377 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1378 assert( eFileLock!=PENDING_LOCK );
1379 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001380
drh8af6c222010-05-14 12:43:01 +00001381 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001382 */
drh6c7d5c52008-11-21 20:32:33 +00001383 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001384 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001385
danielk1977ad94b582007-08-20 06:44:22 +00001386 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001387 ** handle that precludes the requested lock, return BUSY.
1388 */
drh8af6c222010-05-14 12:43:01 +00001389 if( (pFile->eFileLock!=pInode->eFileLock &&
1390 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001391 ){
1392 rc = SQLITE_BUSY;
1393 goto end_lock;
1394 }
1395
1396 /* If a SHARED lock is requested, and some thread using this PID already
1397 ** has a SHARED or RESERVED lock, then increment reference counts and
1398 ** return SQLITE_OK.
1399 */
drh308c2a52010-05-14 11:30:18 +00001400 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001401 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001402 assert( eFileLock==SHARED_LOCK );
1403 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001404 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001405 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001406 pInode->nShared++;
1407 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001408 goto end_lock;
1409 }
1410
danielk19779a1d0ab2004-06-01 14:09:28 +00001411
drh3cde3bb2004-06-12 02:17:14 +00001412 /* A PENDING lock is needed before acquiring a SHARED lock and before
1413 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1414 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001415 */
drh0c2694b2009-09-03 16:23:44 +00001416 lock.l_len = 1L;
1417 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001418 if( eFileLock==SHARED_LOCK
1419 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001420 ){
drh308c2a52010-05-14 11:30:18 +00001421 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001422 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001423 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001424 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001425 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001426 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001427 pFile->lastErrno = tErrno;
1428 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001429 goto end_lock;
1430 }
drh3cde3bb2004-06-12 02:17:14 +00001431 }
1432
1433
1434 /* If control gets to this point, then actually go ahead and make
1435 ** operating system calls for the specified lock.
1436 */
drh308c2a52010-05-14 11:30:18 +00001437 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001438 assert( pInode->nShared==0 );
1439 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001440 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001441
drh2ac3ee92004-06-07 16:27:46 +00001442 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001443 lock.l_start = SHARED_FIRST;
1444 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001445 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001446 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001447 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001448 }
dan661d71a2011-03-30 19:08:03 +00001449
drh2ac3ee92004-06-07 16:27:46 +00001450 /* Drop the temporary PENDING lock */
1451 lock.l_start = PENDING_BYTE;
1452 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001453 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001454 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1455 /* This could happen with a network mount */
1456 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001457 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001458 }
dan661d71a2011-03-30 19:08:03 +00001459
1460 if( rc ){
1461 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001462 pFile->lastErrno = tErrno;
1463 }
dan661d71a2011-03-30 19:08:03 +00001464 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001465 }else{
drh308c2a52010-05-14 11:30:18 +00001466 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001467 pInode->nLock++;
1468 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001469 }
drh8af6c222010-05-14 12:43:01 +00001470 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001471 /* We are trying for an exclusive lock but another thread in this
1472 ** same process is still holding a shared lock. */
1473 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001474 }else{
drh3cde3bb2004-06-12 02:17:14 +00001475 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001476 ** assumed that there is a SHARED or greater lock on the file
1477 ** already.
1478 */
drh308c2a52010-05-14 11:30:18 +00001479 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001480 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001481
1482 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1483 if( eFileLock==RESERVED_LOCK ){
1484 lock.l_start = RESERVED_BYTE;
1485 lock.l_len = 1L;
1486 }else{
1487 lock.l_start = SHARED_FIRST;
1488 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001489 }
dan661d71a2011-03-30 19:08:03 +00001490
1491 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001492 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001493 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001494 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001495 pFile->lastErrno = tErrno;
1496 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001497 }
drhbbd42a62004-05-22 17:41:58 +00001498 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001499
drh8f941bc2009-01-14 23:03:40 +00001500
1501#ifndef NDEBUG
1502 /* Set up the transaction-counter change checking flags when
1503 ** transitioning from a SHARED to a RESERVED lock. The change
1504 ** from SHARED to RESERVED marks the beginning of a normal
1505 ** write operation (not a hot journal rollback).
1506 */
1507 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001508 && pFile->eFileLock<=SHARED_LOCK
1509 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001510 ){
1511 pFile->transCntrChng = 0;
1512 pFile->dbUpdate = 0;
1513 pFile->inNormalWrite = 1;
1514 }
1515#endif
1516
1517
danielk1977ecb2a962004-06-02 06:30:16 +00001518 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001519 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001520 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001521 }else if( eFileLock==EXCLUSIVE_LOCK ){
1522 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001523 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001524 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001525
1526end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001527 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001528 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1529 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001530 return rc;
1531}
1532
1533/*
dan08da86a2009-08-21 17:18:03 +00001534** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001535** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001536*/
1537static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001538 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001539 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001540 p->pNext = pInode->pUnused;
1541 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001542 pFile->h = -1;
1543 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001544}
1545
1546/*
drh308c2a52010-05-14 11:30:18 +00001547** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001548** must be either NO_LOCK or SHARED_LOCK.
1549**
1550** If the locking level of the file descriptor is already at or below
1551** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001552**
1553** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1554** the byte range is divided into 2 parts and the first part is unlocked then
1555** set to a read lock, then the other part is simply unlocked. This works
1556** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1557** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001558*/
drha7e61d82011-03-12 17:02:57 +00001559static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001560 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001561 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001562 struct flock lock;
1563 int rc = SQLITE_OK;
1564 int h;
drha6abd042004-06-09 17:37:22 +00001565
drh054889e2005-11-30 03:20:31 +00001566 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001567 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001568 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001569 getpid()));
drha6abd042004-06-09 17:37:22 +00001570
drh308c2a52010-05-14 11:30:18 +00001571 assert( eFileLock<=SHARED_LOCK );
1572 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001573 return SQLITE_OK;
1574 }
drh6c7d5c52008-11-21 20:32:33 +00001575 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001576 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001577 pInode = pFile->pInode;
1578 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001579 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001580 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001581 SimulateIOErrorBenign(1);
1582 SimulateIOError( h=(-1) )
1583 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001584
1585#ifndef NDEBUG
1586 /* When reducing a lock such that other processes can start
1587 ** reading the database file again, make sure that the
1588 ** transaction counter was updated if any part of the database
1589 ** file changed. If the transaction counter is not updated,
1590 ** other connections to the same file might not realize that
1591 ** the file has changed and hence might not know to flush their
1592 ** cache. The use of a stale cache can lead to database corruption.
1593 */
dan7c246102010-04-12 19:00:29 +00001594#if 0
drh8f941bc2009-01-14 23:03:40 +00001595 assert( pFile->inNormalWrite==0
1596 || pFile->dbUpdate==0
1597 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001598#endif
drh8f941bc2009-01-14 23:03:40 +00001599 pFile->inNormalWrite = 0;
1600#endif
1601
drh7ed97b92010-01-20 13:07:21 +00001602 /* downgrading to a shared lock on NFS involves clearing the write lock
1603 ** before establishing the readlock - to avoid a race condition we downgrade
1604 ** the lock in 2 blocks, so that part of the range will be covered by a
1605 ** write lock until the rest is covered by a read lock:
1606 ** 1: [WWWWW]
1607 ** 2: [....W]
1608 ** 3: [RRRRW]
1609 ** 4: [RRRR.]
1610 */
drh308c2a52010-05-14 11:30:18 +00001611 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001612
1613#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001614 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001615 assert( handleNFSUnlock==0 );
1616#endif
1617#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001618 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001619 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001620 off_t divSize = SHARED_SIZE - 1;
1621
1622 lock.l_type = F_UNLCK;
1623 lock.l_whence = SEEK_SET;
1624 lock.l_start = SHARED_FIRST;
1625 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001626 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001627 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001628 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001629 if( IS_LOCK_ERROR(rc) ){
1630 pFile->lastErrno = tErrno;
1631 }
1632 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001633 }
drh7ed97b92010-01-20 13:07:21 +00001634 lock.l_type = F_RDLCK;
1635 lock.l_whence = SEEK_SET;
1636 lock.l_start = SHARED_FIRST;
1637 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001638 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001639 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001640 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1641 if( IS_LOCK_ERROR(rc) ){
1642 pFile->lastErrno = tErrno;
1643 }
1644 goto end_unlock;
1645 }
1646 lock.l_type = F_UNLCK;
1647 lock.l_whence = SEEK_SET;
1648 lock.l_start = SHARED_FIRST+divSize;
1649 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001650 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001651 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001652 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001653 if( IS_LOCK_ERROR(rc) ){
1654 pFile->lastErrno = tErrno;
1655 }
1656 goto end_unlock;
1657 }
drh30f776f2011-02-25 03:25:07 +00001658 }else
1659#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1660 {
drh7ed97b92010-01-20 13:07:21 +00001661 lock.l_type = F_RDLCK;
1662 lock.l_whence = SEEK_SET;
1663 lock.l_start = SHARED_FIRST;
1664 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001665 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001666 /* In theory, the call to unixFileLock() cannot fail because another
1667 ** process is holding an incompatible lock. If it does, this
1668 ** indicates that the other process is not following the locking
1669 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1670 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1671 ** an assert to fail). */
1672 rc = SQLITE_IOERR_RDLOCK;
1673 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001674 goto end_unlock;
1675 }
drh9c105bb2004-10-02 20:38:28 +00001676 }
1677 }
drhbbd42a62004-05-22 17:41:58 +00001678 lock.l_type = F_UNLCK;
1679 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001680 lock.l_start = PENDING_BYTE;
1681 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001682 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001683 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001684 }else{
danea83bc62011-04-01 11:56:32 +00001685 rc = SQLITE_IOERR_UNLOCK;
1686 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001687 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001688 }
drhbbd42a62004-05-22 17:41:58 +00001689 }
drh308c2a52010-05-14 11:30:18 +00001690 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001691 /* Decrement the shared lock counter. Release the lock using an
1692 ** OS call only when all threads in this same process have released
1693 ** the lock.
1694 */
drh8af6c222010-05-14 12:43:01 +00001695 pInode->nShared--;
1696 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001697 lock.l_type = F_UNLCK;
1698 lock.l_whence = SEEK_SET;
1699 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001700 SimulateIOErrorBenign(1);
1701 SimulateIOError( h=(-1) )
1702 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001703 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001704 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001705 }else{
danea83bc62011-04-01 11:56:32 +00001706 rc = SQLITE_IOERR_UNLOCK;
1707 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001708 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001709 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001710 }
drha6abd042004-06-09 17:37:22 +00001711 }
1712
drhbbd42a62004-05-22 17:41:58 +00001713 /* Decrement the count of locks against this same file. When the
1714 ** count reaches zero, close any other file descriptors whose close
1715 ** was deferred because of outstanding locks.
1716 */
drh8af6c222010-05-14 12:43:01 +00001717 pInode->nLock--;
1718 assert( pInode->nLock>=0 );
1719 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001720 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001721 }
1722 }
aswift5b1a2562008-08-22 00:22:35 +00001723
1724end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001725 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001726 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001727 return rc;
drhbbd42a62004-05-22 17:41:58 +00001728}
1729
1730/*
drh308c2a52010-05-14 11:30:18 +00001731** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001732** must be either NO_LOCK or SHARED_LOCK.
1733**
1734** If the locking level of the file descriptor is already at or below
1735** the requested locking level, this routine is a no-op.
1736*/
drh308c2a52010-05-14 11:30:18 +00001737static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001738 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001739}
1740
1741/*
danielk1977e339d652008-06-28 11:23:00 +00001742** This function performs the parts of the "close file" operation
1743** common to all locking schemes. It closes the directory and file
1744** handles, if they are valid, and sets all fields of the unixFile
1745** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001746**
1747** It is *not* necessary to hold the mutex when this routine is called,
1748** even on VxWorks. A mutex will be acquired on VxWorks by the
1749** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001750*/
1751static int closeUnixFile(sqlite3_file *id){
1752 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001753 if( pFile->dirfd>=0 ){
1754 robust_close(pFile, pFile->dirfd, __LINE__);
1755 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001756 }
dan661d71a2011-03-30 19:08:03 +00001757 if( pFile->h>=0 ){
1758 robust_close(pFile, pFile->h, __LINE__);
1759 pFile->h = -1;
1760 }
1761#if OS_VXWORKS
1762 if( pFile->pId ){
1763 if( pFile->isDelete ){
1764 unlink(pFile->pId->zCanonicalName);
1765 }
1766 vxworksReleaseFileId(pFile->pId);
1767 pFile->pId = 0;
1768 }
1769#endif
1770 OSTRACE(("CLOSE %-3d\n", pFile->h));
1771 OpenCounter(-1);
1772 sqlite3_free(pFile->pUnused);
1773 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001774 return SQLITE_OK;
1775}
1776
1777/*
danielk1977e3026632004-06-22 11:29:02 +00001778** Close a file.
1779*/
danielk197762079062007-08-15 17:08:46 +00001780static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001781 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001782 unixFile *pFile = (unixFile *)id;
1783 unixUnlock(id, NO_LOCK);
1784 unixEnterMutex();
1785
1786 /* unixFile.pInode is always valid here. Otherwise, a different close
1787 ** routine (e.g. nolockClose()) would be called instead.
1788 */
1789 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1790 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1791 /* If there are outstanding locks, do not actually close the file just
1792 ** yet because that would clear those locks. Instead, add the file
1793 ** descriptor to pInode->pUnused list. It will be automatically closed
1794 ** when the last lock is cleared.
1795 */
1796 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001797 }
dan661d71a2011-03-30 19:08:03 +00001798 releaseInodeInfo(pFile);
1799 rc = closeUnixFile(id);
1800 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001801 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001802}
1803
drh734c9862008-11-28 15:37:20 +00001804/************** End of the posix advisory lock implementation *****************
1805******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001806
drh734c9862008-11-28 15:37:20 +00001807/******************************************************************************
1808****************************** No-op Locking **********************************
1809**
1810** Of the various locking implementations available, this is by far the
1811** simplest: locking is ignored. No attempt is made to lock the database
1812** file for reading or writing.
1813**
1814** This locking mode is appropriate for use on read-only databases
1815** (ex: databases that are burned into CD-ROM, for example.) It can
1816** also be used if the application employs some external mechanism to
1817** prevent simultaneous access of the same database by two or more
1818** database connections. But there is a serious risk of database
1819** corruption if this locking mode is used in situations where multiple
1820** database connections are accessing the same database file at the same
1821** time and one or more of those connections are writing.
1822*/
drhbfe66312006-10-03 17:40:40 +00001823
drh734c9862008-11-28 15:37:20 +00001824static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1825 UNUSED_PARAMETER(NotUsed);
1826 *pResOut = 0;
1827 return SQLITE_OK;
1828}
drh734c9862008-11-28 15:37:20 +00001829static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1830 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1831 return SQLITE_OK;
1832}
drh734c9862008-11-28 15:37:20 +00001833static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1834 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1835 return SQLITE_OK;
1836}
1837
1838/*
drh9b35ea62008-11-29 02:20:26 +00001839** Close the file.
drh734c9862008-11-28 15:37:20 +00001840*/
1841static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001842 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001843}
1844
1845/******************* End of the no-op lock implementation *********************
1846******************************************************************************/
1847
1848/******************************************************************************
1849************************* Begin dot-file Locking ******************************
1850**
drh0c2694b2009-09-03 16:23:44 +00001851** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001852** files in order to control access to the database. This works on just
1853** about every filesystem imaginable. But there are serious downsides:
1854**
1855** (1) There is zero concurrency. A single reader blocks all other
1856** connections from reading or writing the database.
1857**
1858** (2) An application crash or power loss can leave stale lock files
1859** sitting around that need to be cleared manually.
1860**
1861** Nevertheless, a dotlock is an appropriate locking mode for use if no
1862** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001863**
1864** Dotfile locking works by creating a file in the same directory as the
1865** database and with the same name but with a ".lock" extension added.
1866** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1867** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001868*/
1869
1870/*
1871** The file suffix added to the data base filename in order to create the
1872** lock file.
1873*/
1874#define DOTLOCK_SUFFIX ".lock"
1875
drh7708e972008-11-29 00:56:52 +00001876/*
1877** This routine checks if there is a RESERVED lock held on the specified
1878** file by this or any other process. If such a lock is held, set *pResOut
1879** to a non-zero value otherwise *pResOut is set to zero. The return value
1880** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1881**
1882** In dotfile locking, either a lock exists or it does not. So in this
1883** variation of CheckReservedLock(), *pResOut is set to true if any lock
1884** is held on the file and false if the file is unlocked.
1885*/
drh734c9862008-11-28 15:37:20 +00001886static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1887 int rc = SQLITE_OK;
1888 int reserved = 0;
1889 unixFile *pFile = (unixFile*)id;
1890
1891 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1892
1893 assert( pFile );
1894
1895 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001896 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001897 /* Either this connection or some other connection in the same process
1898 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001899 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001900 }else{
1901 /* The lock is held if and only if the lockfile exists */
1902 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001903 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001904 }
drh308c2a52010-05-14 11:30:18 +00001905 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001906 *pResOut = reserved;
1907 return rc;
1908}
1909
drh7708e972008-11-29 00:56:52 +00001910/*
drh308c2a52010-05-14 11:30:18 +00001911** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001912** of the following:
1913**
1914** (1) SHARED_LOCK
1915** (2) RESERVED_LOCK
1916** (3) PENDING_LOCK
1917** (4) EXCLUSIVE_LOCK
1918**
1919** Sometimes when requesting one lock state, additional lock states
1920** are inserted in between. The locking might fail on one of the later
1921** transitions leaving the lock state different from what it started but
1922** still short of its goal. The following chart shows the allowed
1923** transitions and the inserted intermediate states:
1924**
1925** UNLOCKED -> SHARED
1926** SHARED -> RESERVED
1927** SHARED -> (PENDING) -> EXCLUSIVE
1928** RESERVED -> (PENDING) -> EXCLUSIVE
1929** PENDING -> EXCLUSIVE
1930**
1931** This routine will only increase a lock. Use the sqlite3OsUnlock()
1932** routine to lower a locking level.
1933**
1934** With dotfile locking, we really only support state (4): EXCLUSIVE.
1935** But we track the other locking levels internally.
1936*/
drh308c2a52010-05-14 11:30:18 +00001937static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001938 unixFile *pFile = (unixFile*)id;
1939 int fd;
1940 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001941 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001942
drh7708e972008-11-29 00:56:52 +00001943
1944 /* If we have any lock, then the lock file already exists. All we have
1945 ** to do is adjust our internal record of the lock level.
1946 */
drh308c2a52010-05-14 11:30:18 +00001947 if( pFile->eFileLock > NO_LOCK ){
1948 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001949 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001950#ifdef HAVE_UTIME
1951 utime(zLockFile, NULL);
1952#else
drh734c9862008-11-28 15:37:20 +00001953 utimes(zLockFile, NULL);
1954#endif
drh7708e972008-11-29 00:56:52 +00001955 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001956 }
1957
1958 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001959 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001960 if( fd<0 ){
1961 /* failed to open/create the file, someone else may have stolen the lock */
1962 int tErrno = errno;
1963 if( EEXIST == tErrno ){
1964 rc = SQLITE_BUSY;
1965 } else {
1966 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1967 if( IS_LOCK_ERROR(rc) ){
1968 pFile->lastErrno = tErrno;
1969 }
1970 }
drh7708e972008-11-29 00:56:52 +00001971 return rc;
drh734c9862008-11-28 15:37:20 +00001972 }
drh0e9365c2011-03-02 02:08:13 +00001973 robust_close(pFile, fd, __LINE__);
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;
1992
1993 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001994 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1995 pFile->eFileLock, getpid()));
1996 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001997
1998 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001999 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002000 return SQLITE_OK;
2001 }
drh7708e972008-11-29 00:56:52 +00002002
2003 /* To downgrade to shared, simply update our internal notion of the
2004 ** lock state. No need to mess with the file on disk.
2005 */
drh308c2a52010-05-14 11:30:18 +00002006 if( eFileLock==SHARED_LOCK ){
2007 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002008 return SQLITE_OK;
2009 }
2010
drh7708e972008-11-29 00:56:52 +00002011 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002012 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00002013 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00002014 int rc = 0;
2015 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002016 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002017 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002018 }
2019 if( IS_LOCK_ERROR(rc) ){
2020 pFile->lastErrno = tErrno;
2021 }
2022 return rc;
2023 }
drh308c2a52010-05-14 11:30:18 +00002024 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002025 return SQLITE_OK;
2026}
2027
2028/*
drh9b35ea62008-11-29 02:20:26 +00002029** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002030*/
2031static int dotlockClose(sqlite3_file *id) {
2032 int rc;
2033 if( id ){
2034 unixFile *pFile = (unixFile*)id;
2035 dotlockUnlock(id, NO_LOCK);
2036 sqlite3_free(pFile->lockingContext);
2037 }
drh734c9862008-11-28 15:37:20 +00002038 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002039 return rc;
2040}
2041/****************** End of the dot-file lock implementation *******************
2042******************************************************************************/
2043
2044/******************************************************************************
2045************************** Begin flock Locking ********************************
2046**
2047** Use the flock() system call to do file locking.
2048**
drh6b9d6dd2008-12-03 19:34:47 +00002049** flock() locking is like dot-file locking in that the various
2050** fine-grain locking levels supported by SQLite are collapsed into
2051** a single exclusive lock. In other words, SHARED, RESERVED, and
2052** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2053** still works when you do this, but concurrency is reduced since
2054** only a single process can be reading the database at a time.
2055**
drh734c9862008-11-28 15:37:20 +00002056** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2057** compiling for VXWORKS.
2058*/
2059#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002060
drh6b9d6dd2008-12-03 19:34:47 +00002061/*
drhff812312011-02-23 13:33:46 +00002062** Retry flock() calls that fail with EINTR
2063*/
2064#ifdef EINTR
2065static int robust_flock(int fd, int op){
2066 int rc;
2067 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2068 return rc;
2069}
2070#else
drh5c819272011-02-23 14:00:12 +00002071# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002072#endif
2073
2074
2075/*
drh6b9d6dd2008-12-03 19:34:47 +00002076** This routine checks if there is a RESERVED lock held on the specified
2077** file by this or any other process. If such a lock is held, set *pResOut
2078** to a non-zero value otherwise *pResOut is set to zero. The return value
2079** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2080*/
drh734c9862008-11-28 15:37:20 +00002081static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2082 int rc = SQLITE_OK;
2083 int reserved = 0;
2084 unixFile *pFile = (unixFile*)id;
2085
2086 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2087
2088 assert( pFile );
2089
2090 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002091 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002092 reserved = 1;
2093 }
2094
2095 /* Otherwise see if some other process holds it. */
2096 if( !reserved ){
2097 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002098 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002099 if( !lrc ){
2100 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002101 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002102 if ( lrc ) {
2103 int tErrno = errno;
2104 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002105 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002106 if( IS_LOCK_ERROR(lrc) ){
2107 pFile->lastErrno = tErrno;
2108 rc = lrc;
2109 }
2110 }
2111 } else {
2112 int tErrno = errno;
2113 reserved = 1;
2114 /* someone else might have it reserved */
2115 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2116 if( IS_LOCK_ERROR(lrc) ){
2117 pFile->lastErrno = tErrno;
2118 rc = lrc;
2119 }
2120 }
2121 }
drh308c2a52010-05-14 11:30:18 +00002122 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002123
2124#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2125 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2126 rc = SQLITE_OK;
2127 reserved=1;
2128 }
2129#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2130 *pResOut = reserved;
2131 return rc;
2132}
2133
drh6b9d6dd2008-12-03 19:34:47 +00002134/*
drh308c2a52010-05-14 11:30:18 +00002135** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002136** of the following:
2137**
2138** (1) SHARED_LOCK
2139** (2) RESERVED_LOCK
2140** (3) PENDING_LOCK
2141** (4) EXCLUSIVE_LOCK
2142**
2143** Sometimes when requesting one lock state, additional lock states
2144** are inserted in between. The locking might fail on one of the later
2145** transitions leaving the lock state different from what it started but
2146** still short of its goal. The following chart shows the allowed
2147** transitions and the inserted intermediate states:
2148**
2149** UNLOCKED -> SHARED
2150** SHARED -> RESERVED
2151** SHARED -> (PENDING) -> EXCLUSIVE
2152** RESERVED -> (PENDING) -> EXCLUSIVE
2153** PENDING -> EXCLUSIVE
2154**
2155** flock() only really support EXCLUSIVE locks. We track intermediate
2156** lock states in the sqlite3_file structure, but all locks SHARED or
2157** above are really EXCLUSIVE locks and exclude all other processes from
2158** access the file.
2159**
2160** This routine will only increase a lock. Use the sqlite3OsUnlock()
2161** routine to lower a locking level.
2162*/
drh308c2a52010-05-14 11:30:18 +00002163static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002164 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002165 unixFile *pFile = (unixFile*)id;
2166
2167 assert( pFile );
2168
2169 /* if we already have a lock, it is exclusive.
2170 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002171 if (pFile->eFileLock > NO_LOCK) {
2172 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002173 return SQLITE_OK;
2174 }
2175
2176 /* grab an exclusive lock */
2177
drhff812312011-02-23 13:33:46 +00002178 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002179 int tErrno = errno;
2180 /* didn't get, must be busy */
2181 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2182 if( IS_LOCK_ERROR(rc) ){
2183 pFile->lastErrno = tErrno;
2184 }
2185 } else {
2186 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002187 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002188 }
drh308c2a52010-05-14 11:30:18 +00002189 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2190 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002191#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2192 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2193 rc = SQLITE_BUSY;
2194 }
2195#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2196 return rc;
2197}
2198
drh6b9d6dd2008-12-03 19:34:47 +00002199
2200/*
drh308c2a52010-05-14 11:30:18 +00002201** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002202** must be either NO_LOCK or SHARED_LOCK.
2203**
2204** If the locking level of the file descriptor is already at or below
2205** the requested locking level, this routine is a no-op.
2206*/
drh308c2a52010-05-14 11:30:18 +00002207static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002208 unixFile *pFile = (unixFile*)id;
2209
2210 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002211 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2212 pFile->eFileLock, getpid()));
2213 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002214
2215 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002216 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002217 return SQLITE_OK;
2218 }
2219
2220 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002221 if (eFileLock==SHARED_LOCK) {
2222 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002223 return SQLITE_OK;
2224 }
2225
2226 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002227 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002228#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002229 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002230#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002231 return SQLITE_IOERR_UNLOCK;
2232 }else{
drh308c2a52010-05-14 11:30:18 +00002233 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002234 return SQLITE_OK;
2235 }
2236}
2237
2238/*
2239** Close a file.
2240*/
2241static int flockClose(sqlite3_file *id) {
2242 if( id ){
2243 flockUnlock(id, NO_LOCK);
2244 }
2245 return closeUnixFile(id);
2246}
2247
2248#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2249
2250/******************* End of the flock lock implementation *********************
2251******************************************************************************/
2252
2253/******************************************************************************
2254************************ Begin Named Semaphore Locking ************************
2255**
2256** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002257**
2258** Semaphore locking is like dot-lock and flock in that it really only
2259** supports EXCLUSIVE locking. Only a single process can read or write
2260** the database file at a time. This reduces potential concurrency, but
2261** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002262*/
2263#if OS_VXWORKS
2264
drh6b9d6dd2008-12-03 19:34:47 +00002265/*
2266** This routine checks if there is a RESERVED lock held on the specified
2267** file by this or any other process. If such a lock is held, set *pResOut
2268** to a non-zero value otherwise *pResOut is set to zero. The return value
2269** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2270*/
drh734c9862008-11-28 15:37:20 +00002271static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2272 int rc = SQLITE_OK;
2273 int reserved = 0;
2274 unixFile *pFile = (unixFile*)id;
2275
2276 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2277
2278 assert( pFile );
2279
2280 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002281 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002282 reserved = 1;
2283 }
2284
2285 /* Otherwise see if some other process holds it. */
2286 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002287 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002288 struct stat statBuf;
2289
2290 if( sem_trywait(pSem)==-1 ){
2291 int tErrno = errno;
2292 if( EAGAIN != tErrno ){
2293 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2294 pFile->lastErrno = tErrno;
2295 } else {
2296 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002297 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002298 }
2299 }else{
2300 /* we could have it if we want it */
2301 sem_post(pSem);
2302 }
2303 }
drh308c2a52010-05-14 11:30:18 +00002304 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002305
2306 *pResOut = reserved;
2307 return rc;
2308}
2309
drh6b9d6dd2008-12-03 19:34:47 +00002310/*
drh308c2a52010-05-14 11:30:18 +00002311** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002312** of the following:
2313**
2314** (1) SHARED_LOCK
2315** (2) RESERVED_LOCK
2316** (3) PENDING_LOCK
2317** (4) EXCLUSIVE_LOCK
2318**
2319** Sometimes when requesting one lock state, additional lock states
2320** are inserted in between. The locking might fail on one of the later
2321** transitions leaving the lock state different from what it started but
2322** still short of its goal. The following chart shows the allowed
2323** transitions and the inserted intermediate states:
2324**
2325** UNLOCKED -> SHARED
2326** SHARED -> RESERVED
2327** SHARED -> (PENDING) -> EXCLUSIVE
2328** RESERVED -> (PENDING) -> EXCLUSIVE
2329** PENDING -> EXCLUSIVE
2330**
2331** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2332** lock states in the sqlite3_file structure, but all locks SHARED or
2333** above are really EXCLUSIVE locks and exclude all other processes from
2334** access the file.
2335**
2336** This routine will only increase a lock. Use the sqlite3OsUnlock()
2337** routine to lower a locking level.
2338*/
drh308c2a52010-05-14 11:30:18 +00002339static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002340 unixFile *pFile = (unixFile*)id;
2341 int fd;
drh8af6c222010-05-14 12:43:01 +00002342 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002343 int rc = SQLITE_OK;
2344
2345 /* if we already have a lock, it is exclusive.
2346 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002347 if (pFile->eFileLock > NO_LOCK) {
2348 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002349 rc = SQLITE_OK;
2350 goto sem_end_lock;
2351 }
2352
2353 /* lock semaphore now but bail out when already locked. */
2354 if( sem_trywait(pSem)==-1 ){
2355 rc = SQLITE_BUSY;
2356 goto sem_end_lock;
2357 }
2358
2359 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002360 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002361
2362 sem_end_lock:
2363 return rc;
2364}
2365
drh6b9d6dd2008-12-03 19:34:47 +00002366/*
drh308c2a52010-05-14 11:30:18 +00002367** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002368** must be either NO_LOCK or SHARED_LOCK.
2369**
2370** If the locking level of the file descriptor is already at or below
2371** the requested locking level, this routine is a no-op.
2372*/
drh308c2a52010-05-14 11:30:18 +00002373static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002374 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002375 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002376
2377 assert( pFile );
2378 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002379 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2380 pFile->eFileLock, getpid()));
2381 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002382
2383 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002384 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002385 return SQLITE_OK;
2386 }
2387
2388 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002389 if (eFileLock==SHARED_LOCK) {
2390 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002391 return SQLITE_OK;
2392 }
2393
2394 /* no, really unlock. */
2395 if ( sem_post(pSem)==-1 ) {
2396 int rc, tErrno = errno;
2397 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2398 if( IS_LOCK_ERROR(rc) ){
2399 pFile->lastErrno = tErrno;
2400 }
2401 return rc;
2402 }
drh308c2a52010-05-14 11:30:18 +00002403 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002404 return SQLITE_OK;
2405}
2406
2407/*
2408 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002409 */
drh734c9862008-11-28 15:37:20 +00002410static int semClose(sqlite3_file *id) {
2411 if( id ){
2412 unixFile *pFile = (unixFile*)id;
2413 semUnlock(id, NO_LOCK);
2414 assert( pFile );
2415 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002416 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002417 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002418 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002419 }
2420 return SQLITE_OK;
2421}
2422
2423#endif /* OS_VXWORKS */
2424/*
2425** Named semaphore locking is only available on VxWorks.
2426**
2427*************** End of the named semaphore lock implementation ****************
2428******************************************************************************/
2429
2430
2431/******************************************************************************
2432*************************** Begin AFP Locking *********************************
2433**
2434** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2435** on Apple Macintosh computers - both OS9 and OSX.
2436**
2437** Third-party implementations of AFP are available. But this code here
2438** only works on OSX.
2439*/
2440
drhd2cb50b2009-01-09 21:41:17 +00002441#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002442/*
2443** The afpLockingContext structure contains all afp lock specific state
2444*/
drhbfe66312006-10-03 17:40:40 +00002445typedef struct afpLockingContext afpLockingContext;
2446struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002447 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002448 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002449};
2450
2451struct ByteRangeLockPB2
2452{
2453 unsigned long long offset; /* offset to first byte to lock */
2454 unsigned long long length; /* nbr of bytes to lock */
2455 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2456 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2457 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2458 int fd; /* file desc to assoc this lock with */
2459};
2460
drhfd131da2007-08-07 17:13:03 +00002461#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002462
drh6b9d6dd2008-12-03 19:34:47 +00002463/*
2464** This is a utility for setting or clearing a bit-range lock on an
2465** AFP filesystem.
2466**
2467** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2468*/
2469static int afpSetLock(
2470 const char *path, /* Name of the file to be locked or unlocked */
2471 unixFile *pFile, /* Open file descriptor on path */
2472 unsigned long long offset, /* First byte to be locked */
2473 unsigned long long length, /* Number of bytes to lock */
2474 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002475){
drh6b9d6dd2008-12-03 19:34:47 +00002476 struct ByteRangeLockPB2 pb;
2477 int err;
drhbfe66312006-10-03 17:40:40 +00002478
2479 pb.unLockFlag = setLockFlag ? 0 : 1;
2480 pb.startEndFlag = 0;
2481 pb.offset = offset;
2482 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002483 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002484
drh308c2a52010-05-14 11:30:18 +00002485 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002486 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002487 offset, length));
drhbfe66312006-10-03 17:40:40 +00002488 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2489 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002490 int rc;
2491 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002492 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2493 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002494#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2495 rc = SQLITE_BUSY;
2496#else
drh734c9862008-11-28 15:37:20 +00002497 rc = sqliteErrorFromPosixError(tErrno,
2498 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002499#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002500 if( IS_LOCK_ERROR(rc) ){
2501 pFile->lastErrno = tErrno;
2502 }
2503 return rc;
drhbfe66312006-10-03 17:40:40 +00002504 } else {
aswift5b1a2562008-08-22 00:22:35 +00002505 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002506 }
2507}
2508
drh6b9d6dd2008-12-03 19:34:47 +00002509/*
2510** This routine checks if there is a RESERVED lock held on the specified
2511** file by this or any other process. If such a lock is held, set *pResOut
2512** to a non-zero value otherwise *pResOut is set to zero. The return value
2513** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2514*/
danielk1977e339d652008-06-28 11:23:00 +00002515static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002516 int rc = SQLITE_OK;
2517 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002518 unixFile *pFile = (unixFile*)id;
2519
aswift5b1a2562008-08-22 00:22:35 +00002520 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2521
2522 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002523 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002524 if( context->reserved ){
2525 *pResOut = 1;
2526 return SQLITE_OK;
2527 }
drh8af6c222010-05-14 12:43:01 +00002528 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002529
2530 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002531 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002532 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002533 }
2534
2535 /* Otherwise see if some other process holds it.
2536 */
aswift5b1a2562008-08-22 00:22:35 +00002537 if( !reserved ){
2538 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002539 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002540 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002541 /* if we succeeded in taking the reserved lock, unlock it to restore
2542 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002543 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002544 } else {
2545 /* if we failed to get the lock then someone else must have it */
2546 reserved = 1;
2547 }
2548 if( IS_LOCK_ERROR(lrc) ){
2549 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002550 }
2551 }
drhbfe66312006-10-03 17:40:40 +00002552
drh7ed97b92010-01-20 13:07:21 +00002553 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002554 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002555
2556 *pResOut = reserved;
2557 return rc;
drhbfe66312006-10-03 17:40:40 +00002558}
2559
drh6b9d6dd2008-12-03 19:34:47 +00002560/*
drh308c2a52010-05-14 11:30:18 +00002561** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002562** of the following:
2563**
2564** (1) SHARED_LOCK
2565** (2) RESERVED_LOCK
2566** (3) PENDING_LOCK
2567** (4) EXCLUSIVE_LOCK
2568**
2569** Sometimes when requesting one lock state, additional lock states
2570** are inserted in between. The locking might fail on one of the later
2571** transitions leaving the lock state different from what it started but
2572** still short of its goal. The following chart shows the allowed
2573** transitions and the inserted intermediate states:
2574**
2575** UNLOCKED -> SHARED
2576** SHARED -> RESERVED
2577** SHARED -> (PENDING) -> EXCLUSIVE
2578** RESERVED -> (PENDING) -> EXCLUSIVE
2579** PENDING -> EXCLUSIVE
2580**
2581** This routine will only increase a lock. Use the sqlite3OsUnlock()
2582** routine to lower a locking level.
2583*/
drh308c2a52010-05-14 11:30:18 +00002584static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002585 int rc = SQLITE_OK;
2586 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002587 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002588 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002589
2590 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002591 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2592 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002593 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002594
drhbfe66312006-10-03 17:40:40 +00002595 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002596 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002597 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002598 */
drh308c2a52010-05-14 11:30:18 +00002599 if( pFile->eFileLock>=eFileLock ){
2600 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2601 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002602 return SQLITE_OK;
2603 }
2604
2605 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002606 ** (1) We never move from unlocked to anything higher than shared lock.
2607 ** (2) SQLite never explicitly requests a pendig lock.
2608 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002609 */
drh308c2a52010-05-14 11:30:18 +00002610 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2611 assert( eFileLock!=PENDING_LOCK );
2612 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002613
drh8af6c222010-05-14 12:43:01 +00002614 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002615 */
drh6c7d5c52008-11-21 20:32:33 +00002616 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002617 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002618
2619 /* If some thread using this PID has a lock via a different unixFile*
2620 ** handle that precludes the requested lock, return BUSY.
2621 */
drh8af6c222010-05-14 12:43:01 +00002622 if( (pFile->eFileLock!=pInode->eFileLock &&
2623 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002624 ){
2625 rc = SQLITE_BUSY;
2626 goto afp_end_lock;
2627 }
2628
2629 /* If a SHARED lock is requested, and some thread using this PID already
2630 ** has a SHARED or RESERVED lock, then increment reference counts and
2631 ** return SQLITE_OK.
2632 */
drh308c2a52010-05-14 11:30:18 +00002633 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002634 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002635 assert( eFileLock==SHARED_LOCK );
2636 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002637 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002638 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002639 pInode->nShared++;
2640 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002641 goto afp_end_lock;
2642 }
drhbfe66312006-10-03 17:40:40 +00002643
2644 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002645 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2646 ** be released.
2647 */
drh308c2a52010-05-14 11:30:18 +00002648 if( eFileLock==SHARED_LOCK
2649 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002650 ){
2651 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002652 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002653 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002654 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002655 goto afp_end_lock;
2656 }
2657 }
2658
2659 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002660 ** operating system calls for the specified lock.
2661 */
drh308c2a52010-05-14 11:30:18 +00002662 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002663 int lrc1, lrc2, lrc1Errno;
2664 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002665
drh8af6c222010-05-14 12:43:01 +00002666 assert( pInode->nShared==0 );
2667 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002668
2669 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002670 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002671 /* note that the quality of the randomness doesn't matter that much */
2672 lk = random();
drh8af6c222010-05-14 12:43:01 +00002673 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002674 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002675 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002676 if( IS_LOCK_ERROR(lrc1) ){
2677 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002678 }
aswift5b1a2562008-08-22 00:22:35 +00002679 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002680 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002681
aswift5b1a2562008-08-22 00:22:35 +00002682 if( IS_LOCK_ERROR(lrc1) ) {
2683 pFile->lastErrno = lrc1Errno;
2684 rc = lrc1;
2685 goto afp_end_lock;
2686 } else if( IS_LOCK_ERROR(lrc2) ){
2687 rc = lrc2;
2688 goto afp_end_lock;
2689 } else if( lrc1 != SQLITE_OK ) {
2690 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002691 } else {
drh308c2a52010-05-14 11:30:18 +00002692 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002693 pInode->nLock++;
2694 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002695 }
drh8af6c222010-05-14 12:43:01 +00002696 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002697 /* We are trying for an exclusive lock but another thread in this
2698 ** same process is still holding a shared lock. */
2699 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002700 }else{
2701 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2702 ** assumed that there is a SHARED or greater lock on the file
2703 ** already.
2704 */
2705 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002706 assert( 0!=pFile->eFileLock );
2707 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002708 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002709 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002710 if( !failed ){
2711 context->reserved = 1;
2712 }
drhbfe66312006-10-03 17:40:40 +00002713 }
drh308c2a52010-05-14 11:30:18 +00002714 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002715 /* Acquire an EXCLUSIVE lock */
2716
2717 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002718 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002719 */
drh6b9d6dd2008-12-03 19:34:47 +00002720 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002721 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002722 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002723 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002724 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002725 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002726 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002727 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002728 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2729 ** a critical I/O error
2730 */
2731 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2732 SQLITE_IOERR_LOCK;
2733 goto afp_end_lock;
2734 }
2735 }else{
aswift5b1a2562008-08-22 00:22:35 +00002736 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002737 }
2738 }
aswift5b1a2562008-08-22 00:22:35 +00002739 if( failed ){
2740 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002741 }
2742 }
2743
2744 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002745 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002746 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002747 }else if( eFileLock==EXCLUSIVE_LOCK ){
2748 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002749 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002750 }
2751
2752afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002753 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002754 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2755 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002756 return rc;
2757}
2758
2759/*
drh308c2a52010-05-14 11:30:18 +00002760** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002761** must be either NO_LOCK or SHARED_LOCK.
2762**
2763** If the locking level of the file descriptor is already at or below
2764** the requested locking level, this routine is a no-op.
2765*/
drh308c2a52010-05-14 11:30:18 +00002766static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002767 int rc = SQLITE_OK;
2768 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002769 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002770 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2771 int skipShared = 0;
2772#ifdef SQLITE_TEST
2773 int h = pFile->h;
2774#endif
drhbfe66312006-10-03 17:40:40 +00002775
2776 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002777 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002778 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002779 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002780
drh308c2a52010-05-14 11:30:18 +00002781 assert( eFileLock<=SHARED_LOCK );
2782 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002783 return SQLITE_OK;
2784 }
drh6c7d5c52008-11-21 20:32:33 +00002785 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002786 pInode = pFile->pInode;
2787 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002788 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002789 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002790 SimulateIOErrorBenign(1);
2791 SimulateIOError( h=(-1) )
2792 SimulateIOErrorBenign(0);
2793
2794#ifndef NDEBUG
2795 /* When reducing a lock such that other processes can start
2796 ** reading the database file again, make sure that the
2797 ** transaction counter was updated if any part of the database
2798 ** file changed. If the transaction counter is not updated,
2799 ** other connections to the same file might not realize that
2800 ** the file has changed and hence might not know to flush their
2801 ** cache. The use of a stale cache can lead to database corruption.
2802 */
2803 assert( pFile->inNormalWrite==0
2804 || pFile->dbUpdate==0
2805 || pFile->transCntrChng==1 );
2806 pFile->inNormalWrite = 0;
2807#endif
aswiftaebf4132008-11-21 00:10:35 +00002808
drh308c2a52010-05-14 11:30:18 +00002809 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002810 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002811 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002812 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002813 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002814 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2815 } else {
2816 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002817 }
2818 }
drh308c2a52010-05-14 11:30:18 +00002819 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002820 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002821 }
drh308c2a52010-05-14 11:30:18 +00002822 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002823 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2824 if( !rc ){
2825 context->reserved = 0;
2826 }
aswiftaebf4132008-11-21 00:10:35 +00002827 }
drh8af6c222010-05-14 12:43:01 +00002828 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2829 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002830 }
aswiftaebf4132008-11-21 00:10:35 +00002831 }
drh308c2a52010-05-14 11:30:18 +00002832 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002833
drh7ed97b92010-01-20 13:07:21 +00002834 /* Decrement the shared lock counter. Release the lock using an
2835 ** OS call only when all threads in this same process have released
2836 ** the lock.
2837 */
drh8af6c222010-05-14 12:43:01 +00002838 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2839 pInode->nShared--;
2840 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002841 SimulateIOErrorBenign(1);
2842 SimulateIOError( h=(-1) )
2843 SimulateIOErrorBenign(0);
2844 if( !skipShared ){
2845 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2846 }
2847 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002848 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002849 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002850 }
2851 }
2852 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002853 pInode->nLock--;
2854 assert( pInode->nLock>=0 );
2855 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002856 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002857 }
2858 }
drhbfe66312006-10-03 17:40:40 +00002859 }
drh7ed97b92010-01-20 13:07:21 +00002860
drh6c7d5c52008-11-21 20:32:33 +00002861 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002862 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002863 return rc;
2864}
2865
2866/*
drh339eb0b2008-03-07 15:34:11 +00002867** Close a file & cleanup AFP specific locking context
2868*/
danielk1977e339d652008-06-28 11:23:00 +00002869static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002870 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002871 if( id ){
2872 unixFile *pFile = (unixFile*)id;
2873 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002874 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002875 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002876 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002877 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002878 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002879 ** the last lock is cleared.
2880 */
dan08da86a2009-08-21 17:18:03 +00002881 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002882 }
danb0ac3e32010-06-16 10:55:42 +00002883 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002884 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002885 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002886 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002887 }
drh7ed97b92010-01-20 13:07:21 +00002888 return rc;
drhbfe66312006-10-03 17:40:40 +00002889}
2890
drhd2cb50b2009-01-09 21:41:17 +00002891#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002892/*
2893** The code above is the AFP lock implementation. The code is specific
2894** to MacOSX and does not work on other unix platforms. No alternative
2895** is available. If you don't compile for a mac, then the "unix-afp"
2896** VFS is not available.
2897**
2898********************* End of the AFP lock implementation **********************
2899******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002900
drh7ed97b92010-01-20 13:07:21 +00002901/******************************************************************************
2902*************************** Begin NFS Locking ********************************/
2903
2904#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2905/*
drh308c2a52010-05-14 11:30:18 +00002906 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002907 ** must be either NO_LOCK or SHARED_LOCK.
2908 **
2909 ** If the locking level of the file descriptor is already at or below
2910 ** the requested locking level, this routine is a no-op.
2911 */
drh308c2a52010-05-14 11:30:18 +00002912static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002913 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002914}
2915
2916#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2917/*
2918** The code above is the NFS lock implementation. The code is specific
2919** to MacOSX and does not work on other unix platforms. No alternative
2920** is available.
2921**
2922********************* End of the NFS lock implementation **********************
2923******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002924
2925/******************************************************************************
2926**************** Non-locking sqlite3_file methods *****************************
2927**
2928** The next division contains implementations for all methods of the
2929** sqlite3_file object other than the locking methods. The locking
2930** methods were defined in divisions above (one locking method per
2931** division). Those methods that are common to all locking modes
2932** are gather together into this division.
2933*/
drhbfe66312006-10-03 17:40:40 +00002934
2935/*
drh734c9862008-11-28 15:37:20 +00002936** Seek to the offset passed as the second argument, then read cnt
2937** bytes into pBuf. Return the number of bytes actually read.
2938**
2939** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2940** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2941** one system to another. Since SQLite does not define USE_PREAD
2942** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2943** See tickets #2741 and #2681.
2944**
2945** To avoid stomping the errno value on a failed read the lastErrno value
2946** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002947*/
drh734c9862008-11-28 15:37:20 +00002948static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2949 int got;
drh7ed97b92010-01-20 13:07:21 +00002950#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002951 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002952#endif
drh734c9862008-11-28 15:37:20 +00002953 TIMER_START;
2954#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002955 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002956 SimulateIOError( got = -1 );
2957#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002958 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002959 SimulateIOError( got = -1 );
2960#else
2961 newOffset = lseek(id->h, offset, SEEK_SET);
2962 SimulateIOError( newOffset-- );
2963 if( newOffset!=offset ){
2964 if( newOffset == -1 ){
2965 ((unixFile*)id)->lastErrno = errno;
2966 }else{
2967 ((unixFile*)id)->lastErrno = 0;
2968 }
2969 return -1;
2970 }
drhe562be52011-03-02 18:01:10 +00002971 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002972#endif
2973 TIMER_END;
2974 if( got<0 ){
2975 ((unixFile*)id)->lastErrno = errno;
2976 }
drh308c2a52010-05-14 11:30:18 +00002977 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002978 return got;
drhbfe66312006-10-03 17:40:40 +00002979}
2980
2981/*
drh734c9862008-11-28 15:37:20 +00002982** Read data from a file into a buffer. Return SQLITE_OK if all
2983** bytes were read successfully and SQLITE_IOERR if anything goes
2984** wrong.
drh339eb0b2008-03-07 15:34:11 +00002985*/
drh734c9862008-11-28 15:37:20 +00002986static int unixRead(
2987 sqlite3_file *id,
2988 void *pBuf,
2989 int amt,
2990 sqlite3_int64 offset
2991){
dan08da86a2009-08-21 17:18:03 +00002992 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002993 int got;
2994 assert( id );
drh08c6d442009-02-09 17:34:07 +00002995
dan08da86a2009-08-21 17:18:03 +00002996 /* If this is a database file (not a journal, master-journal or temp
2997 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002998#if 0
dane946c392009-08-22 11:39:46 +00002999 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003000 || offset>=PENDING_BYTE+512
3001 || offset+amt<=PENDING_BYTE
3002 );
dan7c246102010-04-12 19:00:29 +00003003#endif
drh08c6d442009-02-09 17:34:07 +00003004
dan08da86a2009-08-21 17:18:03 +00003005 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003006 if( got==amt ){
3007 return SQLITE_OK;
3008 }else if( got<0 ){
3009 /* lastErrno set by seekAndRead */
3010 return SQLITE_IOERR_READ;
3011 }else{
dan08da86a2009-08-21 17:18:03 +00003012 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003013 /* Unread parts of the buffer must be zero-filled */
3014 memset(&((char*)pBuf)[got], 0, amt-got);
3015 return SQLITE_IOERR_SHORT_READ;
3016 }
3017}
3018
3019/*
3020** Seek to the offset in id->offset then read cnt bytes into pBuf.
3021** Return the number of bytes actually read. Update the offset.
3022**
3023** To avoid stomping the errno value on a failed write the lastErrno value
3024** is set before returning.
3025*/
3026static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3027 int got;
drh7ed97b92010-01-20 13:07:21 +00003028#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003029 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003030#endif
drh734c9862008-11-28 15:37:20 +00003031 TIMER_START;
3032#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003033 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003034#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003035 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003036#else
3037 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003038 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003039 if( newOffset!=offset ){
3040 if( newOffset == -1 ){
3041 ((unixFile*)id)->lastErrno = errno;
3042 }else{
3043 ((unixFile*)id)->lastErrno = 0;
3044 }
3045 return -1;
3046 }
drhe562be52011-03-02 18:01:10 +00003047 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003048#endif
3049 TIMER_END;
3050 if( got<0 ){
3051 ((unixFile*)id)->lastErrno = errno;
3052 }
3053
drh308c2a52010-05-14 11:30:18 +00003054 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003055 return got;
3056}
3057
3058
3059/*
3060** Write data from a buffer into a file. Return SQLITE_OK on success
3061** or some other error code on failure.
3062*/
3063static int unixWrite(
3064 sqlite3_file *id,
3065 const void *pBuf,
3066 int amt,
3067 sqlite3_int64 offset
3068){
dan08da86a2009-08-21 17:18:03 +00003069 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003070 int wrote = 0;
3071 assert( id );
3072 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003073
dan08da86a2009-08-21 17:18:03 +00003074 /* If this is a database file (not a journal, master-journal or temp
3075 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003076#if 0
dane946c392009-08-22 11:39:46 +00003077 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003078 || offset>=PENDING_BYTE+512
3079 || offset+amt<=PENDING_BYTE
3080 );
dan7c246102010-04-12 19:00:29 +00003081#endif
drh08c6d442009-02-09 17:34:07 +00003082
drh8f941bc2009-01-14 23:03:40 +00003083#ifndef NDEBUG
3084 /* If we are doing a normal write to a database file (as opposed to
3085 ** doing a hot-journal rollback or a write to some file other than a
3086 ** normal database file) then record the fact that the database
3087 ** has changed. If the transaction counter is modified, record that
3088 ** fact too.
3089 */
dan08da86a2009-08-21 17:18:03 +00003090 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003091 pFile->dbUpdate = 1; /* The database has been modified */
3092 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003093 int rc;
drh8f941bc2009-01-14 23:03:40 +00003094 char oldCntr[4];
3095 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003096 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003097 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003098 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003099 pFile->transCntrChng = 1; /* The transaction counter has changed */
3100 }
3101 }
3102 }
3103#endif
3104
dan08da86a2009-08-21 17:18:03 +00003105 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003106 amt -= wrote;
3107 offset += wrote;
3108 pBuf = &((char*)pBuf)[wrote];
3109 }
3110 SimulateIOError(( wrote=(-1), amt=1 ));
3111 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003112
drh734c9862008-11-28 15:37:20 +00003113 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003114 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003115 /* lastErrno set by seekAndWrite */
3116 return SQLITE_IOERR_WRITE;
3117 }else{
dan08da86a2009-08-21 17:18:03 +00003118 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003119 return SQLITE_FULL;
3120 }
3121 }
dan6e09d692010-07-27 18:34:15 +00003122
drh734c9862008-11-28 15:37:20 +00003123 return SQLITE_OK;
3124}
3125
3126#ifdef SQLITE_TEST
3127/*
3128** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003129** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003130*/
3131int sqlite3_sync_count = 0;
3132int sqlite3_fullsync_count = 0;
3133#endif
3134
3135/*
drh89240432009-03-25 01:06:01 +00003136** We do not trust systems to provide a working fdatasync(). Some do.
3137** Others do no. To be safe, we will stick with the (slower) fsync().
3138** If you know that your system does support fdatasync() correctly,
3139** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003140*/
drh89240432009-03-25 01:06:01 +00003141#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003142# define fdatasync fsync
3143#endif
3144
3145/*
3146** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3147** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3148** only available on Mac OS X. But that could change.
3149*/
3150#ifdef F_FULLFSYNC
3151# define HAVE_FULLFSYNC 1
3152#else
3153# define HAVE_FULLFSYNC 0
3154#endif
3155
3156
3157/*
3158** The fsync() system call does not work as advertised on many
3159** unix systems. The following procedure is an attempt to make
3160** it work better.
3161**
3162** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3163** for testing when we want to run through the test suite quickly.
3164** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3165** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3166** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003167**
3168** SQLite sets the dataOnly flag if the size of the file is unchanged.
3169** The idea behind dataOnly is that it should only write the file content
3170** to disk, not the inode. We only set dataOnly if the file size is
3171** unchanged since the file size is part of the inode. However,
3172** Ted Ts'o tells us that fdatasync() will also write the inode if the
3173** file size has changed. The only real difference between fdatasync()
3174** and fsync(), Ted tells us, is that fdatasync() will not flush the
3175** inode if the mtime or owner or other inode attributes have changed.
3176** We only care about the file size, not the other file attributes, so
3177** as far as SQLite is concerned, an fdatasync() is always adequate.
3178** So, we always use fdatasync() if it is available, regardless of
3179** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003180*/
3181static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003182 int rc;
drh734c9862008-11-28 15:37:20 +00003183
3184 /* The following "ifdef/elif/else/" block has the same structure as
3185 ** the one below. It is replicated here solely to avoid cluttering
3186 ** up the real code with the UNUSED_PARAMETER() macros.
3187 */
3188#ifdef SQLITE_NO_SYNC
3189 UNUSED_PARAMETER(fd);
3190 UNUSED_PARAMETER(fullSync);
3191 UNUSED_PARAMETER(dataOnly);
3192#elif HAVE_FULLFSYNC
3193 UNUSED_PARAMETER(dataOnly);
3194#else
3195 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003196 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003197#endif
3198
3199 /* Record the number of times that we do a normal fsync() and
3200 ** FULLSYNC. This is used during testing to verify that this procedure
3201 ** gets called with the correct arguments.
3202 */
3203#ifdef SQLITE_TEST
3204 if( fullSync ) sqlite3_fullsync_count++;
3205 sqlite3_sync_count++;
3206#endif
3207
3208 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3209 ** no-op
3210 */
3211#ifdef SQLITE_NO_SYNC
3212 rc = SQLITE_OK;
3213#elif HAVE_FULLFSYNC
3214 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003215 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003216 }else{
3217 rc = 1;
3218 }
3219 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003220 ** It shouldn't be possible for fullfsync to fail on the local
3221 ** file system (on OSX), so failure indicates that FULLFSYNC
3222 ** isn't supported for this file system. So, attempt an fsync
3223 ** and (for now) ignore the overhead of a superfluous fcntl call.
3224 ** It'd be better to detect fullfsync support once and avoid
3225 ** the fcntl call every time sync is called.
3226 */
drh734c9862008-11-28 15:37:20 +00003227 if( rc ) rc = fsync(fd);
3228
drh7ed97b92010-01-20 13:07:21 +00003229#elif defined(__APPLE__)
3230 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3231 ** so currently we default to the macro that redefines fdatasync to fsync
3232 */
3233 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003234#else
drh0b647ff2009-03-21 14:41:04 +00003235 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003236#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003237 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003238 rc = fsync(fd);
3239 }
drh0b647ff2009-03-21 14:41:04 +00003240#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003241#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3242
3243 if( OS_VXWORKS && rc!= -1 ){
3244 rc = 0;
3245 }
chw97185482008-11-17 08:05:31 +00003246 return rc;
drhbfe66312006-10-03 17:40:40 +00003247}
3248
drh734c9862008-11-28 15:37:20 +00003249/*
3250** Make sure all writes to a particular file are committed to disk.
3251**
3252** If dataOnly==0 then both the file itself and its metadata (file
3253** size, access time, etc) are synced. If dataOnly!=0 then only the
3254** file data is synced.
3255**
3256** Under Unix, also make sure that the directory entry for the file
3257** has been created by fsync-ing the directory that contains the file.
3258** If we do not do this and we encounter a power failure, the directory
3259** entry for the journal might not exist after we reboot. The next
3260** SQLite to access the file will not know that the journal exists (because
3261** the directory entry for the journal was never created) and the transaction
3262** will not roll back - possibly leading to database corruption.
3263*/
3264static int unixSync(sqlite3_file *id, int flags){
3265 int rc;
3266 unixFile *pFile = (unixFile*)id;
3267
3268 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3269 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3270
3271 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3272 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3273 || (flags&0x0F)==SQLITE_SYNC_FULL
3274 );
3275
3276 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3277 ** line is to test that doing so does not cause any problems.
3278 */
3279 SimulateDiskfullError( return SQLITE_FULL );
3280
3281 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003282 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003283 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3284 SimulateIOError( rc=1 );
3285 if( rc ){
3286 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003287 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003288 }
3289 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003290 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3291 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003292#ifndef SQLITE_DISABLE_DIRSYNC
3293 /* The directory sync is only attempted if full_fsync is
3294 ** turned off or unavailable. If a full_fsync occurred above,
3295 ** then the directory sync is superfluous.
3296 */
3297 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3298 /*
3299 ** We have received multiple reports of fsync() returning
3300 ** errors when applied to directories on certain file systems.
3301 ** A failed directory sync is not a big deal. So it seems
3302 ** better to ignore the error. Ticket #1657
3303 */
3304 /* pFile->lastErrno = errno; */
3305 /* return SQLITE_IOERR; */
3306 }
3307#endif
drh0e9365c2011-03-02 02:08:13 +00003308 /* Only need to sync once, so close the directory when we are done */
3309 robust_close(pFile, pFile->dirfd, __LINE__);
3310 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003311 }
3312 return rc;
3313}
3314
3315/*
3316** Truncate an open file to a specified size
3317*/
3318static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003319 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003320 int rc;
dan6e09d692010-07-27 18:34:15 +00003321 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003322 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003323
3324 /* If the user has configured a chunk-size for this file, truncate the
3325 ** file so that it consists of an integer number of chunks (i.e. the
3326 ** actual file size after the operation may be larger than the requested
3327 ** size).
3328 */
3329 if( pFile->szChunk ){
3330 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3331 }
3332
drhff812312011-02-23 13:33:46 +00003333 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003334 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003335 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003336 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003337 }else{
drh3313b142009-11-06 04:13:18 +00003338#ifndef NDEBUG
3339 /* If we are doing a normal write to a database file (as opposed to
3340 ** doing a hot-journal rollback or a write to some file other than a
3341 ** normal database file) and we truncate the file to zero length,
3342 ** that effectively updates the change counter. This might happen
3343 ** when restoring a database using the backup API from a zero-length
3344 ** source.
3345 */
dan6e09d692010-07-27 18:34:15 +00003346 if( pFile->inNormalWrite && nByte==0 ){
3347 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003348 }
3349#endif
3350
drh734c9862008-11-28 15:37:20 +00003351 return SQLITE_OK;
3352 }
3353}
3354
3355/*
3356** Determine the current size of a file in bytes
3357*/
3358static int unixFileSize(sqlite3_file *id, i64 *pSize){
3359 int rc;
3360 struct stat buf;
3361 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003362 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003363 SimulateIOError( rc=1 );
3364 if( rc!=0 ){
3365 ((unixFile*)id)->lastErrno = errno;
3366 return SQLITE_IOERR_FSTAT;
3367 }
3368 *pSize = buf.st_size;
3369
drh8af6c222010-05-14 12:43:01 +00003370 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003371 ** writes a single byte into that file in order to work around a bug
3372 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3373 ** layers, we need to report this file size as zero even though it is
3374 ** really 1. Ticket #3260.
3375 */
3376 if( *pSize==1 ) *pSize = 0;
3377
3378
3379 return SQLITE_OK;
3380}
3381
drhd2cb50b2009-01-09 21:41:17 +00003382#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003383/*
3384** Handler for proxy-locking file-control verbs. Defined below in the
3385** proxying locking division.
3386*/
3387static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003388#endif
drh715ff302008-12-03 22:32:44 +00003389
dan502019c2010-07-28 14:26:17 +00003390/*
3391** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3392** file-control operation.
3393**
3394** If the user has configured a chunk-size for this file, it could be
3395** that the file needs to be extended at this point. Otherwise, the
3396** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3397*/
3398static int fcntlSizeHint(unixFile *pFile, i64 nByte){
drh7d2dc712011-07-25 23:25:47 +00003399 { /* preserve indentation of removed "if" */
dan502019c2010-07-28 14:26:17 +00003400 i64 nSize; /* Required file size */
drh7d2dc712011-07-25 23:25:47 +00003401 i64 szChunk; /* Chunk size */
dan502019c2010-07-28 14:26:17 +00003402 struct stat buf; /* Used to hold return values of fstat() */
3403
drh99ab3b12011-03-02 15:09:07 +00003404 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003405
drh7d2dc712011-07-25 23:25:47 +00003406 szChunk = pFile->szChunk;
3407 if( szChunk==0 ){
3408 nSize = nByte;
3409 }else{
3410 nSize = ((nByte+szChunk-1) / szChunk) * szChunk;
3411 }
dan502019c2010-07-28 14:26:17 +00003412 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003413
dan502019c2010-07-28 14:26:17 +00003414#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003415 /* The code below is handling the return value of osFallocate()
3416 ** correctly. posix_fallocate() is defined to "returns zero on success,
3417 ** or an error number on failure". See the manpage for details. */
3418 int err;
drhff812312011-02-23 13:33:46 +00003419 do{
dan661d71a2011-03-30 19:08:03 +00003420 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3421 }while( err==EINTR );
3422 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003423#else
3424 /* If the OS does not have posix_fallocate(), fake it. First use
3425 ** ftruncate() to set the file size, then write a single byte to
3426 ** the last byte in each block within the extended region. This
3427 ** is the same technique used by glibc to implement posix_fallocate()
3428 ** on systems that do not have a real fallocate() system call.
3429 */
3430 int nBlk = buf.st_blksize; /* File-system block size */
3431 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003432
drhff812312011-02-23 13:33:46 +00003433 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003434 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003435 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003436 }
3437 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003438 while( iWrite<nSize ){
3439 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3440 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003441 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003442 }
dan502019c2010-07-28 14:26:17 +00003443#endif
3444 }
3445 }
3446
3447 return SQLITE_OK;
3448}
danielk1977ad94b582007-08-20 06:44:22 +00003449
danielk1977e3026632004-06-22 11:29:02 +00003450/*
drh9e33c2c2007-08-31 18:34:59 +00003451** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003452*/
drhcc6bb3e2007-08-31 16:11:35 +00003453static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003454 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003455 switch( op ){
3456 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003457 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003458 return SQLITE_OK;
3459 }
drh7708e972008-11-29 00:56:52 +00003460 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003461 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003462 return SQLITE_OK;
3463 }
dan6e09d692010-07-27 18:34:15 +00003464 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003465 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003466 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003467 }
drh9ff27ec2010-05-19 19:26:05 +00003468 case SQLITE_FCNTL_SIZE_HINT: {
drhf0b190d2011-07-26 16:03:07 +00003469 return fcntlSizeHint(pFile, *(i64 *)pArg);
3470 }
3471 case SQLITE_FCNTL_PERSIST_WAL: {
3472 int bPersist = *(int*)pArg;
3473 if( bPersist<0 ){
drh253cea52011-07-26 16:23:25 +00003474 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
drhf0b190d2011-07-26 16:03:07 +00003475 }else if( bPersist==0 ){
3476 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
3477 }else{
3478 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
3479 }
3480 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003481 }
drh8f941bc2009-01-14 23:03:40 +00003482#ifndef NDEBUG
3483 /* The pager calls this method to signal that it has done
3484 ** a rollback and that the database is therefore unchanged and
3485 ** it hence it is OK for the transaction change counter to be
3486 ** unchanged.
3487 */
3488 case SQLITE_FCNTL_DB_UNCHANGED: {
3489 ((unixFile*)id)->dbUpdate = 0;
3490 return SQLITE_OK;
3491 }
3492#endif
drhd2cb50b2009-01-09 21:41:17 +00003493#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003494 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003495 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003496 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003497 }
drhd2cb50b2009-01-09 21:41:17 +00003498#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003499 case SQLITE_FCNTL_SYNC_OMITTED: {
3500 return SQLITE_OK; /* A no-op */
3501 }
drh9e33c2c2007-08-31 18:34:59 +00003502 }
drh0b52b7d2011-01-26 19:46:22 +00003503 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003504}
3505
3506/*
danielk1977a3d4c882007-03-23 10:08:38 +00003507** Return the sector size in bytes of the underlying block device for
3508** the specified file. This is almost always 512 bytes, but may be
3509** larger for some devices.
3510**
3511** SQLite code assumes this function cannot fail. It also assumes that
3512** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003513** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003514** same for both.
3515*/
danielk1977397d65f2008-11-19 11:35:39 +00003516static int unixSectorSize(sqlite3_file *NotUsed){
3517 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003518 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003519}
3520
danielk197790949c22007-08-17 16:50:38 +00003521/*
danielk1977397d65f2008-11-19 11:35:39 +00003522** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003523*/
danielk1977397d65f2008-11-19 11:35:39 +00003524static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3525 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003526 return 0;
3527}
3528
drhd9e5c4f2010-05-12 18:01:39 +00003529#ifndef SQLITE_OMIT_WAL
3530
3531
3532/*
drhd91c68f2010-05-14 14:52:25 +00003533** Object used to represent an shared memory buffer.
3534**
3535** When multiple threads all reference the same wal-index, each thread
3536** has its own unixShm object, but they all point to a single instance
3537** of this unixShmNode object. In other words, each wal-index is opened
3538** only once per process.
3539**
3540** Each unixShmNode object is connected to a single unixInodeInfo object.
3541** We could coalesce this object into unixInodeInfo, but that would mean
3542** every open file that does not use shared memory (in other words, most
3543** open files) would have to carry around this extra information. So
3544** the unixInodeInfo object contains a pointer to this unixShmNode object
3545** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003546**
3547** unixMutexHeld() must be true when creating or destroying
3548** this object or while reading or writing the following fields:
3549**
3550** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003551**
3552** The following fields are read-only after the object is created:
3553**
3554** fid
3555** zFilename
3556**
drhd91c68f2010-05-14 14:52:25 +00003557** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003558** unixMutexHeld() is true when reading or writing any other field
3559** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003560*/
drhd91c68f2010-05-14 14:52:25 +00003561struct unixShmNode {
3562 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003563 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003564 char *zFilename; /* Name of the mmapped file */
3565 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003566 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003567 u16 nRegion; /* Size of array apRegion */
3568 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003569 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003570 int nRef; /* Number of unixShm objects pointing to this */
3571 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003572#ifdef SQLITE_DEBUG
3573 u8 exclMask; /* Mask of exclusive locks held */
3574 u8 sharedMask; /* Mask of shared locks held */
3575 u8 nextShmId; /* Next available unixShm.id value */
3576#endif
3577};
3578
3579/*
drhd9e5c4f2010-05-12 18:01:39 +00003580** Structure used internally by this VFS to record the state of an
3581** open shared memory connection.
3582**
drhd91c68f2010-05-14 14:52:25 +00003583** The following fields are initialized when this object is created and
3584** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003585**
drhd91c68f2010-05-14 14:52:25 +00003586** unixShm.pFile
3587** unixShm.id
3588**
3589** All other fields are read/write. The unixShm.pFile->mutex must be held
3590** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003591*/
3592struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003593 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3594 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003595 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003596 u16 sharedMask; /* Mask of shared locks held */
3597 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003598#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003599 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003600#endif
3601};
3602
3603/*
drhd9e5c4f2010-05-12 18:01:39 +00003604** Constants used for locking
3605*/
drhbd9676c2010-06-23 17:58:38 +00003606#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003607#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003608
drhd9e5c4f2010-05-12 18:01:39 +00003609/*
drh73b64e42010-05-30 19:55:15 +00003610** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003611**
3612** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3613** otherwise.
3614*/
3615static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003616 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3617 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003618 int ofst, /* First byte of the locking range */
3619 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003620){
3621 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003622 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003623
drhd91c68f2010-05-14 14:52:25 +00003624 /* Access to the unixShmNode object is serialized by the caller */
3625 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003626
drh73b64e42010-05-30 19:55:15 +00003627 /* Shared locks never span more than one byte */
3628 assert( n==1 || lockType!=F_RDLCK );
3629
3630 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003631 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003632
drh3cb93392011-03-12 18:10:44 +00003633 if( pShmNode->h>=0 ){
3634 /* Initialize the locking parameters */
3635 memset(&f, 0, sizeof(f));
3636 f.l_type = lockType;
3637 f.l_whence = SEEK_SET;
3638 f.l_start = ofst;
3639 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003640
drh3cb93392011-03-12 18:10:44 +00003641 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3642 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3643 }
drhd9e5c4f2010-05-12 18:01:39 +00003644
3645 /* Update the global lock state and do debug tracing */
3646#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003647 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003648 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003649 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003650 if( rc==SQLITE_OK ){
3651 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003652 OSTRACE(("unlock %d ok", ofst));
3653 pShmNode->exclMask &= ~mask;
3654 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003655 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003656 OSTRACE(("read-lock %d ok", ofst));
3657 pShmNode->exclMask &= ~mask;
3658 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003659 }else{
3660 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003661 OSTRACE(("write-lock %d ok", ofst));
3662 pShmNode->exclMask |= mask;
3663 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003664 }
3665 }else{
3666 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003667 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003668 }else if( lockType==F_RDLCK ){
3669 OSTRACE(("read-lock failed"));
3670 }else{
3671 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003672 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003673 }
3674 }
drh20e1f082010-05-31 16:10:12 +00003675 OSTRACE((" - afterwards %03x,%03x\n",
3676 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003677 }
drhd9e5c4f2010-05-12 18:01:39 +00003678#endif
3679
3680 return rc;
3681}
3682
drhd9e5c4f2010-05-12 18:01:39 +00003683
3684/*
drhd91c68f2010-05-14 14:52:25 +00003685** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003686**
3687** This is not a VFS shared-memory method; it is a utility function called
3688** by VFS shared-memory methods.
3689*/
drhd91c68f2010-05-14 14:52:25 +00003690static void unixShmPurge(unixFile *pFd){
3691 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003692 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003693 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003694 int i;
drhd91c68f2010-05-14 14:52:25 +00003695 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003696 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003697 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003698 if( p->h>=0 ){
3699 munmap(p->apRegion[i], p->szRegion);
3700 }else{
3701 sqlite3_free(p->apRegion[i]);
3702 }
dan13a3cb82010-06-11 19:04:21 +00003703 }
dan18801912010-06-14 14:07:50 +00003704 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003705 if( p->h>=0 ){
3706 robust_close(pFd, p->h, __LINE__);
3707 p->h = -1;
3708 }
drhd91c68f2010-05-14 14:52:25 +00003709 p->pInode->pShmNode = 0;
3710 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003711 }
3712}
3713
3714/*
danda9fe0c2010-07-13 18:44:03 +00003715** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003716** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003717**
drh7234c6d2010-06-19 15:10:09 +00003718** The file used to implement shared-memory is in the same directory
3719** as the open database file and has the same name as the open database
3720** file with the "-shm" suffix added. For example, if the database file
3721** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003722** for shared memory will be called "/home/user1/config.db-shm".
3723**
3724** Another approach to is to use files in /dev/shm or /dev/tmp or an
3725** some other tmpfs mount. But if a file in a different directory
3726** from the database file is used, then differing access permissions
3727** or a chroot() might cause two different processes on the same
3728** database to end up using different files for shared memory -
3729** meaning that their memory would not really be shared - resulting
3730** in database corruption. Nevertheless, this tmpfs file usage
3731** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3732** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3733** option results in an incompatible build of SQLite; builds of SQLite
3734** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3735** same database file at the same time, database corruption will likely
3736** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3737** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003738**
3739** When opening a new shared-memory file, if no other instances of that
3740** file are currently open, in this process or in other processes, then
3741** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003742**
3743** If the original database file (pDbFd) is using the "unix-excl" VFS
3744** that means that an exclusive lock is held on the database file and
3745** that no other processes are able to read or write the database. In
3746** that case, we do not really need shared memory. No shared memory
3747** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003748*/
danda9fe0c2010-07-13 18:44:03 +00003749static int unixOpenSharedMemory(unixFile *pDbFd){
3750 struct unixShm *p = 0; /* The connection to be opened */
3751 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3752 int rc; /* Result code */
3753 unixInodeInfo *pInode; /* The inode of fd */
3754 char *zShmFilename; /* Name of the file used for SHM */
3755 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003756
danda9fe0c2010-07-13 18:44:03 +00003757 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003758 p = sqlite3_malloc( sizeof(*p) );
3759 if( p==0 ) return SQLITE_NOMEM;
3760 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003761 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003762
danda9fe0c2010-07-13 18:44:03 +00003763 /* Check to see if a unixShmNode object already exists. Reuse an existing
3764 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003765 */
3766 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003767 pInode = pDbFd->pInode;
3768 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003769 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003770 struct stat sStat; /* fstat() info for database file */
3771
3772 /* Call fstat() to figure out the permissions on the database file. If
3773 ** a new *-shm file is created, an attempt will be made to create it
3774 ** with the same permissions. The actual permissions the file is created
3775 ** with are subject to the current umask setting.
3776 */
drh3cb93392011-03-12 18:10:44 +00003777 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003778 rc = SQLITE_IOERR_FSTAT;
3779 goto shm_open_err;
3780 }
3781
drha4ced192010-07-15 18:32:40 +00003782#ifdef SQLITE_SHM_DIRECTORY
3783 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3784#else
drh7234c6d2010-06-19 15:10:09 +00003785 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003786#endif
drh7234c6d2010-06-19 15:10:09 +00003787 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003788 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003789 rc = SQLITE_NOMEM;
3790 goto shm_open_err;
3791 }
drhd91c68f2010-05-14 14:52:25 +00003792 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003793 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003794#ifdef SQLITE_SHM_DIRECTORY
3795 sqlite3_snprintf(nShmFilename, zShmFilename,
3796 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3797 (u32)sStat.st_ino, (u32)sStat.st_dev);
3798#else
drh7234c6d2010-06-19 15:10:09 +00003799 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003800 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003801#endif
drhd91c68f2010-05-14 14:52:25 +00003802 pShmNode->h = -1;
3803 pDbFd->pInode->pShmNode = pShmNode;
3804 pShmNode->pInode = pDbFd->pInode;
3805 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3806 if( pShmNode->mutex==0 ){
3807 rc = SQLITE_NOMEM;
3808 goto shm_open_err;
3809 }
drhd9e5c4f2010-05-12 18:01:39 +00003810
drh3cb93392011-03-12 18:10:44 +00003811 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003812 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3813 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003814 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003815 const char *zRO;
3816 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003817 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003818 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3819 (sStat.st_mode & 0777));
3820 pShmNode->isReadonly = 1;
3821 }
3822 if( pShmNode->h<0 ){
3823 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3824 goto shm_open_err;
3825 }
drhd9e5c4f2010-05-12 18:01:39 +00003826 }
drh3cb93392011-03-12 18:10:44 +00003827
3828 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003829 ** If not, truncate the file to zero length.
3830 */
3831 rc = SQLITE_OK;
3832 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3833 if( robust_ftruncate(pShmNode->h, 0) ){
3834 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003835 }
3836 }
drh66dfec8b2011-06-01 20:01:49 +00003837 if( rc==SQLITE_OK ){
3838 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3839 }
3840 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003841 }
drhd9e5c4f2010-05-12 18:01:39 +00003842 }
3843
drhd91c68f2010-05-14 14:52:25 +00003844 /* Make the new connection a child of the unixShmNode */
3845 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003846#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003847 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003848#endif
drhd91c68f2010-05-14 14:52:25 +00003849 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003850 pDbFd->pShm = p;
3851 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003852
3853 /* The reference count on pShmNode has already been incremented under
3854 ** the cover of the unixEnterMutex() mutex and the pointer from the
3855 ** new (struct unixShm) object to the pShmNode has been set. All that is
3856 ** left to do is to link the new object into the linked list starting
3857 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3858 ** mutex.
3859 */
3860 sqlite3_mutex_enter(pShmNode->mutex);
3861 p->pNext = pShmNode->pFirst;
3862 pShmNode->pFirst = p;
3863 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003864 return SQLITE_OK;
3865
3866 /* Jump here on any error */
3867shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003868 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003869 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003870 unixLeaveMutex();
3871 return rc;
3872}
3873
3874/*
danda9fe0c2010-07-13 18:44:03 +00003875** This function is called to obtain a pointer to region iRegion of the
3876** shared-memory associated with the database file fd. Shared-memory regions
3877** are numbered starting from zero. Each shared-memory region is szRegion
3878** bytes in size.
3879**
3880** If an error occurs, an error code is returned and *pp is set to NULL.
3881**
3882** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3883** region has not been allocated (by any client, including one running in a
3884** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3885** bExtend is non-zero and the requested shared-memory region has not yet
3886** been allocated, it is allocated by this function.
3887**
3888** If the shared-memory region has already been allocated or is allocated by
3889** this call as described above, then it is mapped into this processes
3890** address space (if it is not already), *pp is set to point to the mapped
3891** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003892*/
danda9fe0c2010-07-13 18:44:03 +00003893static int unixShmMap(
3894 sqlite3_file *fd, /* Handle open on database file */
3895 int iRegion, /* Region to retrieve */
3896 int szRegion, /* Size of regions */
3897 int bExtend, /* True to extend file if necessary */
3898 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003899){
danda9fe0c2010-07-13 18:44:03 +00003900 unixFile *pDbFd = (unixFile*)fd;
3901 unixShm *p;
3902 unixShmNode *pShmNode;
3903 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003904
danda9fe0c2010-07-13 18:44:03 +00003905 /* If the shared-memory file has not yet been opened, open it now. */
3906 if( pDbFd->pShm==0 ){
3907 rc = unixOpenSharedMemory(pDbFd);
3908 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003909 }
drhd9e5c4f2010-05-12 18:01:39 +00003910
danda9fe0c2010-07-13 18:44:03 +00003911 p = pDbFd->pShm;
3912 pShmNode = p->pShmNode;
3913 sqlite3_mutex_enter(pShmNode->mutex);
3914 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003915 assert( pShmNode->pInode==pDbFd->pInode );
3916 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3917 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003918
3919 if( pShmNode->nRegion<=iRegion ){
3920 char **apNew; /* New apRegion[] array */
3921 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3922 struct stat sStat; /* Used by fstat() */
3923
3924 pShmNode->szRegion = szRegion;
3925
drh3cb93392011-03-12 18:10:44 +00003926 if( pShmNode->h>=0 ){
3927 /* The requested region is not mapped into this processes address space.
3928 ** Check to see if it has been allocated (i.e. if the wal-index file is
3929 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003930 */
drh3cb93392011-03-12 18:10:44 +00003931 if( osFstat(pShmNode->h, &sStat) ){
3932 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003933 goto shmpage_out;
3934 }
drh3cb93392011-03-12 18:10:44 +00003935
3936 if( sStat.st_size<nByte ){
3937 /* The requested memory region does not exist. If bExtend is set to
3938 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3939 **
3940 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3941 ** the requested memory region.
3942 */
3943 if( !bExtend ) goto shmpage_out;
3944 if( robust_ftruncate(pShmNode->h, nByte) ){
3945 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3946 pShmNode->zFilename);
3947 goto shmpage_out;
3948 }
3949 }
danda9fe0c2010-07-13 18:44:03 +00003950 }
3951
3952 /* Map the requested memory region into this processes address space. */
3953 apNew = (char **)sqlite3_realloc(
3954 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3955 );
3956 if( !apNew ){
3957 rc = SQLITE_IOERR_NOMEM;
3958 goto shmpage_out;
3959 }
3960 pShmNode->apRegion = apNew;
3961 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003962 void *pMem;
3963 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00003964 pMem = mmap(0, szRegion,
3965 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00003966 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3967 );
3968 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00003969 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00003970 goto shmpage_out;
3971 }
3972 }else{
3973 pMem = sqlite3_malloc(szRegion);
3974 if( pMem==0 ){
3975 rc = SQLITE_NOMEM;
3976 goto shmpage_out;
3977 }
3978 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003979 }
3980 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3981 pShmNode->nRegion++;
3982 }
3983 }
3984
3985shmpage_out:
3986 if( pShmNode->nRegion>iRegion ){
3987 *pp = pShmNode->apRegion[iRegion];
3988 }else{
3989 *pp = 0;
3990 }
drh66dfec8b2011-06-01 20:01:49 +00003991 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00003992 sqlite3_mutex_leave(pShmNode->mutex);
3993 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003994}
3995
3996/*
drhd9e5c4f2010-05-12 18:01:39 +00003997** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003998**
3999** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4000** different here than in posix. In xShmLock(), one can go from unlocked
4001** to shared and back or from unlocked to exclusive and back. But one may
4002** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004003*/
4004static int unixShmLock(
4005 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004006 int ofst, /* First lock to acquire or release */
4007 int n, /* Number of locks to acquire or release */
4008 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004009){
drh73b64e42010-05-30 19:55:15 +00004010 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4011 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4012 unixShm *pX; /* For looping over all siblings */
4013 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4014 int rc = SQLITE_OK; /* Result code */
4015 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004016
drhd91c68f2010-05-14 14:52:25 +00004017 assert( pShmNode==pDbFd->pInode->pShmNode );
4018 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004019 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004020 assert( n>=1 );
4021 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4022 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4023 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4024 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4025 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004026 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4027 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004028
drhc99597c2010-05-31 01:41:15 +00004029 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004030 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004031 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004032 if( flags & SQLITE_SHM_UNLOCK ){
4033 u16 allMask = 0; /* Mask of locks held by siblings */
4034
4035 /* See if any siblings hold this same lock */
4036 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4037 if( pX==p ) continue;
4038 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4039 allMask |= pX->sharedMask;
4040 }
4041
4042 /* Unlock the system-level locks */
4043 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004044 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004045 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004046 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004047 }
drh73b64e42010-05-30 19:55:15 +00004048
4049 /* Undo the local locks */
4050 if( rc==SQLITE_OK ){
4051 p->exclMask &= ~mask;
4052 p->sharedMask &= ~mask;
4053 }
4054 }else if( flags & SQLITE_SHM_SHARED ){
4055 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4056
4057 /* Find out which shared locks are already held by sibling connections.
4058 ** If any sibling already holds an exclusive lock, go ahead and return
4059 ** SQLITE_BUSY.
4060 */
4061 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004062 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004063 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004064 break;
4065 }
4066 allShared |= pX->sharedMask;
4067 }
4068
4069 /* Get shared locks at the system level, if necessary */
4070 if( rc==SQLITE_OK ){
4071 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004072 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004073 }else{
drh73b64e42010-05-30 19:55:15 +00004074 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004075 }
drhd9e5c4f2010-05-12 18:01:39 +00004076 }
drh73b64e42010-05-30 19:55:15 +00004077
4078 /* Get the local shared locks */
4079 if( rc==SQLITE_OK ){
4080 p->sharedMask |= mask;
4081 }
4082 }else{
4083 /* Make sure no sibling connections hold locks that will block this
4084 ** lock. If any do, return SQLITE_BUSY right away.
4085 */
4086 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004087 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4088 rc = SQLITE_BUSY;
4089 break;
4090 }
4091 }
4092
4093 /* Get the exclusive locks at the system level. Then if successful
4094 ** also mark the local connection as being locked.
4095 */
4096 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004097 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004098 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004099 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004100 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004101 }
drhd9e5c4f2010-05-12 18:01:39 +00004102 }
4103 }
drhd91c68f2010-05-14 14:52:25 +00004104 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004105 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4106 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004107 return rc;
4108}
4109
drh286a2882010-05-20 23:51:06 +00004110/*
4111** Implement a memory barrier or memory fence on shared memory.
4112**
4113** All loads and stores begun before the barrier must complete before
4114** any load or store begun after the barrier.
4115*/
4116static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004117 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004118){
drhff828942010-06-26 21:34:06 +00004119 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004120 unixEnterMutex();
4121 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004122}
4123
dan18801912010-06-14 14:07:50 +00004124/*
danda9fe0c2010-07-13 18:44:03 +00004125** Close a connection to shared-memory. Delete the underlying
4126** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004127**
4128** If there is no shared memory associated with the connection then this
4129** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004130*/
danda9fe0c2010-07-13 18:44:03 +00004131static int unixShmUnmap(
4132 sqlite3_file *fd, /* The underlying database file */
4133 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004134){
danda9fe0c2010-07-13 18:44:03 +00004135 unixShm *p; /* The connection to be closed */
4136 unixShmNode *pShmNode; /* The underlying shared-memory file */
4137 unixShm **pp; /* For looping over sibling connections */
4138 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004139
danda9fe0c2010-07-13 18:44:03 +00004140 pDbFd = (unixFile*)fd;
4141 p = pDbFd->pShm;
4142 if( p==0 ) return SQLITE_OK;
4143 pShmNode = p->pShmNode;
4144
4145 assert( pShmNode==pDbFd->pInode->pShmNode );
4146 assert( pShmNode->pInode==pDbFd->pInode );
4147
4148 /* Remove connection p from the set of connections associated
4149 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004150 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004151 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4152 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004153
danda9fe0c2010-07-13 18:44:03 +00004154 /* Free the connection p */
4155 sqlite3_free(p);
4156 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004157 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004158
4159 /* If pShmNode->nRef has reached 0, then close the underlying
4160 ** shared-memory file, too */
4161 unixEnterMutex();
4162 assert( pShmNode->nRef>0 );
4163 pShmNode->nRef--;
4164 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004165 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004166 unixShmPurge(pDbFd);
4167 }
4168 unixLeaveMutex();
4169
4170 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004171}
drh286a2882010-05-20 23:51:06 +00004172
danda9fe0c2010-07-13 18:44:03 +00004173
drhd9e5c4f2010-05-12 18:01:39 +00004174#else
drh6b017cc2010-06-14 18:01:46 +00004175# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004176# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004177# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004178# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004179#endif /* #ifndef SQLITE_OMIT_WAL */
4180
drh734c9862008-11-28 15:37:20 +00004181/*
4182** Here ends the implementation of all sqlite3_file methods.
4183**
4184********************** End sqlite3_file Methods *******************************
4185******************************************************************************/
4186
4187/*
drh6b9d6dd2008-12-03 19:34:47 +00004188** This division contains definitions of sqlite3_io_methods objects that
4189** implement various file locking strategies. It also contains definitions
4190** of "finder" functions. A finder-function is used to locate the appropriate
4191** sqlite3_io_methods object for a particular database file. The pAppData
4192** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4193** the correct finder-function for that VFS.
4194**
4195** Most finder functions return a pointer to a fixed sqlite3_io_methods
4196** object. The only interesting finder-function is autolockIoFinder, which
4197** looks at the filesystem type and tries to guess the best locking
4198** strategy from that.
4199**
drh1875f7a2008-12-08 18:19:17 +00004200** For finder-funtion F, two objects are created:
4201**
4202** (1) The real finder-function named "FImpt()".
4203**
dane946c392009-08-22 11:39:46 +00004204** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004205**
4206**
4207** A pointer to the F pointer is used as the pAppData value for VFS
4208** objects. We have to do this instead of letting pAppData point
4209** directly at the finder-function since C90 rules prevent a void*
4210** from be cast into a function pointer.
4211**
drh6b9d6dd2008-12-03 19:34:47 +00004212**
drh7708e972008-11-29 00:56:52 +00004213** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004214**
drh7708e972008-11-29 00:56:52 +00004215** * A constant sqlite3_io_methods object call METHOD that has locking
4216** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4217**
4218** * An I/O method finder function called FINDER that returns a pointer
4219** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004220*/
drhd9e5c4f2010-05-12 18:01:39 +00004221#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004222static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004223 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004224 CLOSE, /* xClose */ \
4225 unixRead, /* xRead */ \
4226 unixWrite, /* xWrite */ \
4227 unixTruncate, /* xTruncate */ \
4228 unixSync, /* xSync */ \
4229 unixFileSize, /* xFileSize */ \
4230 LOCK, /* xLock */ \
4231 UNLOCK, /* xUnlock */ \
4232 CKLOCK, /* xCheckReservedLock */ \
4233 unixFileControl, /* xFileControl */ \
4234 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004235 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004236 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004237 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004238 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004239 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004240}; \
drh0c2694b2009-09-03 16:23:44 +00004241static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4242 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004243 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004244} \
drh0c2694b2009-09-03 16:23:44 +00004245static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004246 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004247
4248/*
4249** Here are all of the sqlite3_io_methods objects for each of the
4250** locking strategies. Functions that return pointers to these methods
4251** are also created.
4252*/
4253IOMETHODS(
4254 posixIoFinder, /* Finder function name */
4255 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004256 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004257 unixClose, /* xClose method */
4258 unixLock, /* xLock method */
4259 unixUnlock, /* xUnlock method */
4260 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004261)
drh7708e972008-11-29 00:56:52 +00004262IOMETHODS(
4263 nolockIoFinder, /* Finder function name */
4264 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004265 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004266 nolockClose, /* xClose method */
4267 nolockLock, /* xLock method */
4268 nolockUnlock, /* xUnlock method */
4269 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004270)
drh7708e972008-11-29 00:56:52 +00004271IOMETHODS(
4272 dotlockIoFinder, /* Finder function name */
4273 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004274 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004275 dotlockClose, /* xClose method */
4276 dotlockLock, /* xLock method */
4277 dotlockUnlock, /* xUnlock method */
4278 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004279)
drh7708e972008-11-29 00:56:52 +00004280
chw78a13182009-04-07 05:35:03 +00004281#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004282IOMETHODS(
4283 flockIoFinder, /* Finder function name */
4284 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004285 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004286 flockClose, /* xClose method */
4287 flockLock, /* xLock method */
4288 flockUnlock, /* xUnlock method */
4289 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004290)
drh7708e972008-11-29 00:56:52 +00004291#endif
4292
drh6c7d5c52008-11-21 20:32:33 +00004293#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004294IOMETHODS(
4295 semIoFinder, /* Finder function name */
4296 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004297 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004298 semClose, /* xClose method */
4299 semLock, /* xLock method */
4300 semUnlock, /* xUnlock method */
4301 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004302)
aswiftaebf4132008-11-21 00:10:35 +00004303#endif
drh7708e972008-11-29 00:56:52 +00004304
drhd2cb50b2009-01-09 21:41:17 +00004305#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004306IOMETHODS(
4307 afpIoFinder, /* Finder function name */
4308 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004309 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004310 afpClose, /* xClose method */
4311 afpLock, /* xLock method */
4312 afpUnlock, /* xUnlock method */
4313 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004314)
drh715ff302008-12-03 22:32:44 +00004315#endif
4316
4317/*
4318** The proxy locking method is a "super-method" in the sense that it
4319** opens secondary file descriptors for the conch and lock files and
4320** it uses proxy, dot-file, AFP, and flock() locking methods on those
4321** secondary files. For this reason, the division that implements
4322** proxy locking is located much further down in the file. But we need
4323** to go ahead and define the sqlite3_io_methods and finder function
4324** for proxy locking here. So we forward declare the I/O methods.
4325*/
drhd2cb50b2009-01-09 21:41:17 +00004326#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004327static int proxyClose(sqlite3_file*);
4328static int proxyLock(sqlite3_file*, int);
4329static int proxyUnlock(sqlite3_file*, int);
4330static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004331IOMETHODS(
4332 proxyIoFinder, /* Finder function name */
4333 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004334 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004335 proxyClose, /* xClose method */
4336 proxyLock, /* xLock method */
4337 proxyUnlock, /* xUnlock method */
4338 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004339)
aswiftaebf4132008-11-21 00:10:35 +00004340#endif
drh7708e972008-11-29 00:56:52 +00004341
drh7ed97b92010-01-20 13:07:21 +00004342/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4343#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4344IOMETHODS(
4345 nfsIoFinder, /* Finder function name */
4346 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004347 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004348 unixClose, /* xClose method */
4349 unixLock, /* xLock method */
4350 nfsUnlock, /* xUnlock method */
4351 unixCheckReservedLock /* xCheckReservedLock method */
4352)
4353#endif
drh7708e972008-11-29 00:56:52 +00004354
drhd2cb50b2009-01-09 21:41:17 +00004355#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004356/*
drh6b9d6dd2008-12-03 19:34:47 +00004357** This "finder" function attempts to determine the best locking strategy
4358** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004359** object that implements that strategy.
4360**
4361** This is for MacOSX only.
4362*/
drh1875f7a2008-12-08 18:19:17 +00004363static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004364 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004365 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004366){
4367 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004368 const char *zFilesystem; /* Filesystem type name */
4369 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004370 } aMap[] = {
4371 { "hfs", &posixIoMethods },
4372 { "ufs", &posixIoMethods },
4373 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004374 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004375 { "webdav", &nolockIoMethods },
4376 { 0, 0 }
4377 };
4378 int i;
4379 struct statfs fsInfo;
4380 struct flock lockInfo;
4381
4382 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004383 /* If filePath==NULL that means we are dealing with a transient file
4384 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004385 return &nolockIoMethods;
4386 }
4387 if( statfs(filePath, &fsInfo) != -1 ){
4388 if( fsInfo.f_flags & MNT_RDONLY ){
4389 return &nolockIoMethods;
4390 }
4391 for(i=0; aMap[i].zFilesystem; i++){
4392 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4393 return aMap[i].pMethods;
4394 }
4395 }
4396 }
4397
4398 /* Default case. Handles, amongst others, "nfs".
4399 ** Test byte-range lock using fcntl(). If the call succeeds,
4400 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004401 */
drh7708e972008-11-29 00:56:52 +00004402 lockInfo.l_len = 1;
4403 lockInfo.l_start = 0;
4404 lockInfo.l_whence = SEEK_SET;
4405 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004406 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004407 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4408 return &nfsIoMethods;
4409 } else {
4410 return &posixIoMethods;
4411 }
drh7708e972008-11-29 00:56:52 +00004412 }else{
4413 return &dotlockIoMethods;
4414 }
4415}
drh0c2694b2009-09-03 16:23:44 +00004416static const sqlite3_io_methods
4417 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004418
drhd2cb50b2009-01-09 21:41:17 +00004419#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004420
chw78a13182009-04-07 05:35:03 +00004421#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4422/*
4423** This "finder" function attempts to determine the best locking strategy
4424** for the database file "filePath". It then returns the sqlite3_io_methods
4425** object that implements that strategy.
4426**
4427** This is for VXWorks only.
4428*/
4429static const sqlite3_io_methods *autolockIoFinderImpl(
4430 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004431 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004432){
4433 struct flock lockInfo;
4434
4435 if( !filePath ){
4436 /* If filePath==NULL that means we are dealing with a transient file
4437 ** that does not need to be locked. */
4438 return &nolockIoMethods;
4439 }
4440
4441 /* Test if fcntl() is supported and use POSIX style locks.
4442 ** Otherwise fall back to the named semaphore method.
4443 */
4444 lockInfo.l_len = 1;
4445 lockInfo.l_start = 0;
4446 lockInfo.l_whence = SEEK_SET;
4447 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004448 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004449 return &posixIoMethods;
4450 }else{
4451 return &semIoMethods;
4452 }
4453}
drh0c2694b2009-09-03 16:23:44 +00004454static const sqlite3_io_methods
4455 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004456
4457#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4458
drh7708e972008-11-29 00:56:52 +00004459/*
4460** An abstract type for a pointer to a IO method finder function:
4461*/
drh0c2694b2009-09-03 16:23:44 +00004462typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004463
aswiftaebf4132008-11-21 00:10:35 +00004464
drh734c9862008-11-28 15:37:20 +00004465/****************************************************************************
4466**************************** sqlite3_vfs methods ****************************
4467**
4468** This division contains the implementation of methods on the
4469** sqlite3_vfs object.
4470*/
4471
danielk1977a3d4c882007-03-23 10:08:38 +00004472/*
danielk1977e339d652008-06-28 11:23:00 +00004473** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004474*/
4475static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004476 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004477 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004478 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004479 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004480 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004481 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004482 int isDelete, /* Delete on close if true */
4483 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004484){
drh7708e972008-11-29 00:56:52 +00004485 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004486 unixFile *pNew = (unixFile *)pId;
4487 int rc = SQLITE_OK;
4488
drh8af6c222010-05-14 12:43:01 +00004489 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004490
dane946c392009-08-22 11:39:46 +00004491 /* Parameter isDelete is only used on vxworks. Express this explicitly
4492 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004493 */
drh7708e972008-11-29 00:56:52 +00004494 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004495
dan00157392010-10-05 11:33:15 +00004496 /* Usually the path zFilename should not be a relative pathname. The
4497 ** exception is when opening the proxy "conch" file in builds that
4498 ** include the special Apple locking styles.
4499 */
dan00157392010-10-05 11:33:15 +00004500#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004501 assert( zFilename==0 || zFilename[0]=='/'
4502 || pVfs->pAppData==(void*)&autolockIoFinder );
4503#else
4504 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004505#endif
dan00157392010-10-05 11:33:15 +00004506
drh308c2a52010-05-14 11:30:18 +00004507 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004508 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004509 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004510 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004511 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4512 pNew->ctrlFlags = UNIXFILE_EXCL;
4513 }else{
4514 pNew->ctrlFlags = 0;
4515 }
drh77197112011-03-15 19:08:48 +00004516 if( isReadOnly ){
4517 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4518 }
drh339eb0b2008-03-07 15:34:11 +00004519
drh6c7d5c52008-11-21 20:32:33 +00004520#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004521 pNew->pId = vxworksFindFileId(zFilename);
4522 if( pNew->pId==0 ){
4523 noLock = 1;
4524 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004525 }
4526#endif
4527
drhda0e7682008-07-30 15:27:54 +00004528 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004529 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004530 }else{
drh0c2694b2009-09-03 16:23:44 +00004531 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004532#if SQLITE_ENABLE_LOCKING_STYLE
4533 /* Cache zFilename in the locking context (AFP and dotlock override) for
4534 ** proxyLock activation is possible (remote proxy is based on db name)
4535 ** zFilename remains valid until file is closed, to support */
4536 pNew->lockingContext = (void*)zFilename;
4537#endif
drhda0e7682008-07-30 15:27:54 +00004538 }
danielk1977e339d652008-06-28 11:23:00 +00004539
drh7ed97b92010-01-20 13:07:21 +00004540 if( pLockingStyle == &posixIoMethods
4541#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4542 || pLockingStyle == &nfsIoMethods
4543#endif
4544 ){
drh7708e972008-11-29 00:56:52 +00004545 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004546 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004547 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004548 /* If an error occured in findInodeInfo(), close the file descriptor
4549 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004550 ** in two scenarios:
4551 **
4552 ** (a) A call to fstat() failed.
4553 ** (b) A malloc failed.
4554 **
4555 ** Scenario (b) may only occur if the process is holding no other
4556 ** file descriptors open on the same file. If there were other file
4557 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004558 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004559 ** handle h - as it is guaranteed that no posix locks will be released
4560 ** by doing so.
4561 **
4562 ** If scenario (a) caused the error then things are not so safe. The
4563 ** implicit assumption here is that if fstat() fails, things are in
4564 ** such bad shape that dropping a lock or two doesn't matter much.
4565 */
drh0e9365c2011-03-02 02:08:13 +00004566 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004567 h = -1;
4568 }
drh7708e972008-11-29 00:56:52 +00004569 unixLeaveMutex();
4570 }
danielk1977e339d652008-06-28 11:23:00 +00004571
drhd2cb50b2009-01-09 21:41:17 +00004572#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004573 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004574 /* AFP locking uses the file path so it needs to be included in
4575 ** the afpLockingContext.
4576 */
4577 afpLockingContext *pCtx;
4578 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4579 if( pCtx==0 ){
4580 rc = SQLITE_NOMEM;
4581 }else{
4582 /* NB: zFilename exists and remains valid until the file is closed
4583 ** according to requirement F11141. So we do not need to make a
4584 ** copy of the filename. */
4585 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004586 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004587 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004588 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004589 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004590 if( rc!=SQLITE_OK ){
4591 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004592 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004593 h = -1;
4594 }
drh7708e972008-11-29 00:56:52 +00004595 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004596 }
drh7708e972008-11-29 00:56:52 +00004597 }
4598#endif
danielk1977e339d652008-06-28 11:23:00 +00004599
drh7708e972008-11-29 00:56:52 +00004600 else if( pLockingStyle == &dotlockIoMethods ){
4601 /* Dotfile locking uses the file path so it needs to be included in
4602 ** the dotlockLockingContext
4603 */
4604 char *zLockFile;
4605 int nFilename;
drhea678832008-12-10 19:26:22 +00004606 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004607 zLockFile = (char *)sqlite3_malloc(nFilename);
4608 if( zLockFile==0 ){
4609 rc = SQLITE_NOMEM;
4610 }else{
4611 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004612 }
drh7708e972008-11-29 00:56:52 +00004613 pNew->lockingContext = zLockFile;
4614 }
danielk1977e339d652008-06-28 11:23:00 +00004615
drh6c7d5c52008-11-21 20:32:33 +00004616#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004617 else if( pLockingStyle == &semIoMethods ){
4618 /* Named semaphore locking uses the file path so it needs to be
4619 ** included in the semLockingContext
4620 */
4621 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004622 rc = findInodeInfo(pNew, &pNew->pInode);
4623 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4624 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004625 int n;
drh2238dcc2009-08-27 17:56:20 +00004626 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004627 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004628 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004629 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004630 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4631 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004632 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004633 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004634 }
chw97185482008-11-17 08:05:31 +00004635 }
drh7708e972008-11-29 00:56:52 +00004636 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004637 }
drh7708e972008-11-29 00:56:52 +00004638#endif
aswift5b1a2562008-08-22 00:22:35 +00004639
4640 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004641#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004642 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004643 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004644 h = -1;
chw97185482008-11-17 08:05:31 +00004645 unlink(zFilename);
4646 isDelete = 0;
4647 }
4648 pNew->isDelete = isDelete;
4649#endif
danielk1977e339d652008-06-28 11:23:00 +00004650 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004651 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4652 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004653 }else{
drh7708e972008-11-29 00:56:52 +00004654 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004655 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004656 }
danielk1977e339d652008-06-28 11:23:00 +00004657 return rc;
drh054889e2005-11-30 03:20:31 +00004658}
drh9c06c952005-11-26 00:25:00 +00004659
danielk1977ad94b582007-08-20 06:44:22 +00004660/*
4661** Open a file descriptor to the directory containing file zFilename.
4662** If successful, *pFd is set to the opened file descriptor and
4663** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4664** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4665** value.
4666**
4667** If SQLITE_OK is returned, the caller is responsible for closing
4668** the file descriptor *pFd using close().
4669*/
danielk1977fee2d252007-08-18 10:59:19 +00004670static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004671 int ii;
drh777b17a2007-09-20 10:02:54 +00004672 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004673 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004674
drh153c62c2007-08-24 03:51:33 +00004675 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004676 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004677 if( ii>0 ){
4678 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004679 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004680 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004681#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004682 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004683#endif
drh308c2a52010-05-14 11:30:18 +00004684 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004685 }
4686 }
danielk1977fee2d252007-08-18 10:59:19 +00004687 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004688 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004689}
4690
danielk1977b4b47412007-08-17 15:53:36 +00004691/*
drh8b3cf822010-06-01 21:02:51 +00004692** Return the name of a directory in which to put temporary files.
4693** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004694*/
drh7234c6d2010-06-19 15:10:09 +00004695static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004696 static const char *azDirs[] = {
4697 0,
aswiftaebf4132008-11-21 00:10:35 +00004698 0,
danielk197717b90b52008-06-06 11:11:25 +00004699 "/var/tmp",
4700 "/usr/tmp",
4701 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004702 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004703 };
drh8b3cf822010-06-01 21:02:51 +00004704 unsigned int i;
4705 struct stat buf;
4706 const char *zDir = 0;
4707
4708 azDirs[0] = sqlite3_temp_directory;
4709 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004710 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004711 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004712 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004713 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004714 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004715 break;
4716 }
4717 return zDir;
4718}
4719
4720/*
4721** Create a temporary file name in zBuf. zBuf must be allocated
4722** by the calling process and must be big enough to hold at least
4723** pVfs->mxPathname bytes.
4724*/
4725static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004726 static const unsigned char zChars[] =
4727 "abcdefghijklmnopqrstuvwxyz"
4728 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4729 "0123456789";
drh41022642008-11-21 00:24:42 +00004730 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004731 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004732
4733 /* It's odd to simulate an io-error here, but really this is just
4734 ** using the io-error infrastructure to test that SQLite handles this
4735 ** function failing.
4736 */
4737 SimulateIOError( return SQLITE_IOERR );
4738
drh7234c6d2010-06-19 15:10:09 +00004739 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004740 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004741
4742 /* Check that the output buffer is large enough for the temporary file
4743 ** name. If it is not, return SQLITE_ERROR.
4744 */
danielk197700e13612008-11-17 19:18:54 +00004745 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004746 return SQLITE_ERROR;
4747 }
4748
4749 do{
4750 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004751 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004752 sqlite3_randomness(15, &zBuf[j]);
4753 for(i=0; i<15; i++, j++){
4754 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4755 }
4756 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004757 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004758 return SQLITE_OK;
4759}
4760
drhd2cb50b2009-01-09 21:41:17 +00004761#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004762/*
4763** Routine to transform a unixFile into a proxy-locking unixFile.
4764** Implementation in the proxy-lock division, but used by unixOpen()
4765** if SQLITE_PREFER_PROXY_LOCKING is defined.
4766*/
4767static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004768#endif
drhc66d5b62008-12-03 22:48:32 +00004769
dan08da86a2009-08-21 17:18:03 +00004770/*
4771** Search for an unused file descriptor that was opened on the database
4772** file (not a journal or master-journal file) identified by pathname
4773** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4774** argument to this function.
4775**
4776** Such a file descriptor may exist if a database connection was closed
4777** but the associated file descriptor could not be closed because some
4778** other file descriptor open on the same file is holding a file-lock.
4779** Refer to comments in the unixClose() function and the lengthy comment
4780** describing "Posix Advisory Locking" at the start of this file for
4781** further details. Also, ticket #4018.
4782**
4783** If a suitable file descriptor is found, then it is returned. If no
4784** such file descriptor is located, -1 is returned.
4785*/
dane946c392009-08-22 11:39:46 +00004786static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4787 UnixUnusedFd *pUnused = 0;
4788
4789 /* Do not search for an unused file descriptor on vxworks. Not because
4790 ** vxworks would not benefit from the change (it might, we're not sure),
4791 ** but because no way to test it is currently available. It is better
4792 ** not to risk breaking vxworks support for the sake of such an obscure
4793 ** feature. */
4794#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004795 struct stat sStat; /* Results of stat() call */
4796
4797 /* A stat() call may fail for various reasons. If this happens, it is
4798 ** almost certain that an open() call on the same path will also fail.
4799 ** For this reason, if an error occurs in the stat() call here, it is
4800 ** ignored and -1 is returned. The caller will try to open a new file
4801 ** descriptor on the same path, fail, and return an error to SQLite.
4802 **
4803 ** Even if a subsequent open() call does succeed, the consequences of
4804 ** not searching for a resusable file descriptor are not dire. */
4805 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004806 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004807
4808 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004809 pInode = inodeList;
4810 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4811 || pInode->fileId.ino!=sStat.st_ino) ){
4812 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004813 }
drh8af6c222010-05-14 12:43:01 +00004814 if( pInode ){
dane946c392009-08-22 11:39:46 +00004815 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004816 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004817 pUnused = *pp;
4818 if( pUnused ){
4819 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004820 }
4821 }
4822 unixLeaveMutex();
4823 }
dane946c392009-08-22 11:39:46 +00004824#endif /* if !OS_VXWORKS */
4825 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004826}
danielk197717b90b52008-06-06 11:11:25 +00004827
4828/*
danddb0ac42010-07-14 14:48:58 +00004829** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004830** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004831** and a value suitable for passing as the third argument to open(2) is
4832** written to *pMode. If an IO error occurs, an SQLite error code is
4833** returned and the value of *pMode is not modified.
4834**
4835** If the file being opened is a temporary file, it is always created with
4836** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004837** is a database or master journal file, it is created with the permissions
4838** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004839**
drh8ab58662010-07-15 18:38:39 +00004840** Finally, if the file being opened is a WAL or regular journal file, then
4841** this function queries the file-system for the permissions on the
4842** corresponding database file and sets *pMode to this value. Whenever
4843** possible, WAL and journal files are created using the same permissions
4844** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004845**
4846** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4847** original filename is unavailable. But 8_3_NAMES is only used for
4848** FAT filesystems and permissions do not matter there, so just use
4849** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004850*/
4851static int findCreateFileMode(
4852 const char *zPath, /* Path of file (possibly) being created */
4853 int flags, /* Flags passed as 4th argument to xOpen() */
4854 mode_t *pMode /* OUT: Permissions to open file with */
4855){
4856 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004857 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004858 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004859 char zDb[MAX_PATHNAME+1]; /* Database file path */
4860 int nDb; /* Number of valid bytes in zDb */
4861 struct stat sStat; /* Output of stat() on database file */
4862
dana0c989d2010-11-05 18:07:37 +00004863 /* zPath is a path to a WAL or journal file. The following block derives
4864 ** the path to the associated database file from zPath. This block handles
4865 ** the following naming conventions:
4866 **
4867 ** "<path to db>-journal"
4868 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004869 ** "<path to db>-journalNN"
4870 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004871 **
drh81cc5162011-05-17 20:36:21 +00004872 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004873 ** used by the test_multiplex.c module.
4874 */
4875 nDb = sqlite3Strlen30(zPath) - 1;
drh81cc5162011-05-17 20:36:21 +00004876 while( nDb>0 && zPath[nDb]!='-' ) nDb--;
4877 if( nDb==0 ) return SQLITE_OK;
danddb0ac42010-07-14 14:48:58 +00004878 memcpy(zDb, zPath, nDb);
4879 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004880
danddb0ac42010-07-14 14:48:58 +00004881 if( 0==stat(zDb, &sStat) ){
4882 *pMode = sStat.st_mode & 0777;
4883 }else{
4884 rc = SQLITE_IOERR_FSTAT;
4885 }
4886 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4887 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004888 }
4889 return rc;
4890}
4891
4892/*
danielk1977ad94b582007-08-20 06:44:22 +00004893** Open the file zPath.
4894**
danielk1977b4b47412007-08-17 15:53:36 +00004895** Previously, the SQLite OS layer used three functions in place of this
4896** one:
4897**
4898** sqlite3OsOpenReadWrite();
4899** sqlite3OsOpenReadOnly();
4900** sqlite3OsOpenExclusive();
4901**
4902** These calls correspond to the following combinations of flags:
4903**
4904** ReadWrite() -> (READWRITE | CREATE)
4905** ReadOnly() -> (READONLY)
4906** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4907**
4908** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4909** true, the file was configured to be automatically deleted when the
4910** file handle closed. To achieve the same effect using this new
4911** interface, add the DELETEONCLOSE flag to those specified above for
4912** OpenExclusive().
4913*/
4914static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004915 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4916 const char *zPath, /* Pathname of file to be opened */
4917 sqlite3_file *pFile, /* The file descriptor to be filled in */
4918 int flags, /* Input flags to control the opening */
4919 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004920){
dan08da86a2009-08-21 17:18:03 +00004921 unixFile *p = (unixFile *)pFile;
4922 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004923 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004924 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004925 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004926 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004927 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004928
4929 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4930 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4931 int isCreate = (flags & SQLITE_OPEN_CREATE);
4932 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4933 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004934#if SQLITE_ENABLE_LOCKING_STYLE
4935 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4936#endif
danielk1977b4b47412007-08-17 15:53:36 +00004937
danielk1977fee2d252007-08-18 10:59:19 +00004938 /* If creating a master or main-file journal, this function will open
4939 ** a file-descriptor on the directory too. The first time unixSync()
4940 ** is called the directory file descriptor will be fsync()ed and close()d.
4941 */
danddb0ac42010-07-14 14:48:58 +00004942 int isOpenDirectory = (isCreate && (
4943 eType==SQLITE_OPEN_MASTER_JOURNAL
4944 || eType==SQLITE_OPEN_MAIN_JOURNAL
4945 || eType==SQLITE_OPEN_WAL
4946 ));
danielk1977fee2d252007-08-18 10:59:19 +00004947
danielk197717b90b52008-06-06 11:11:25 +00004948 /* If argument zPath is a NULL pointer, this function is required to open
4949 ** a temporary file. Use this buffer to store the file name in.
4950 */
4951 char zTmpname[MAX_PATHNAME+1];
4952 const char *zName = zPath;
4953
danielk1977fee2d252007-08-18 10:59:19 +00004954 /* Check the following statements are true:
4955 **
4956 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4957 ** (b) if CREATE is set, then READWRITE must also be set, and
4958 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004959 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004960 */
danielk1977b4b47412007-08-17 15:53:36 +00004961 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004962 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004963 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004964 assert(isDelete==0 || isCreate);
4965
danddb0ac42010-07-14 14:48:58 +00004966 /* The main DB, main journal, WAL file and master journal are never
4967 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004968 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4969 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4970 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004971 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004972
danielk1977fee2d252007-08-18 10:59:19 +00004973 /* Assert that the upper layer has set one of the "file-type" flags. */
4974 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4975 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4976 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004977 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004978 );
4979
dan08da86a2009-08-21 17:18:03 +00004980 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004981
dan08da86a2009-08-21 17:18:03 +00004982 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004983 UnixUnusedFd *pUnused;
4984 pUnused = findReusableFd(zName, flags);
4985 if( pUnused ){
4986 fd = pUnused->fd;
4987 }else{
dan6aa657f2009-08-24 18:57:58 +00004988 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004989 if( !pUnused ){
4990 return SQLITE_NOMEM;
4991 }
4992 }
4993 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004994 }else if( !zName ){
4995 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004996 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004997 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004998 if( rc!=SQLITE_OK ){
4999 return rc;
5000 }
5001 zName = zTmpname;
5002 }
5003
dan08da86a2009-08-21 17:18:03 +00005004 /* Determine the value of the flags parameter passed to POSIX function
5005 ** open(). These must be calculated even if open() is not called, as
5006 ** they may be stored as part of the file handle and used by the
5007 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005008 if( isReadonly ) openFlags |= O_RDONLY;
5009 if( isReadWrite ) openFlags |= O_RDWR;
5010 if( isCreate ) openFlags |= O_CREAT;
5011 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5012 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005013
danielk1977b4b47412007-08-17 15:53:36 +00005014 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005015 mode_t openMode; /* Permissions to create file with */
5016 rc = findCreateFileMode(zName, flags, &openMode);
5017 if( rc!=SQLITE_OK ){
5018 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005019 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005020 return rc;
5021 }
drhad4f1e52011-03-04 15:43:57 +00005022 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005023 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005024 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5025 /* Failed to open the file for read/write access. Try read-only. */
5026 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005027 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005028 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005029 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005030 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005031 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005032 }
5033 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005034 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005035 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005036 }
danielk1977b4b47412007-08-17 15:53:36 +00005037 }
dan08da86a2009-08-21 17:18:03 +00005038 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005039 if( pOutFlags ){
5040 *pOutFlags = flags;
5041 }
5042
dane946c392009-08-22 11:39:46 +00005043 if( p->pUnused ){
5044 p->pUnused->fd = fd;
5045 p->pUnused->flags = flags;
5046 }
5047
danielk1977b4b47412007-08-17 15:53:36 +00005048 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005049#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005050 zPath = zName;
5051#else
danielk197717b90b52008-06-06 11:11:25 +00005052 unlink(zName);
chw97185482008-11-17 08:05:31 +00005053#endif
danielk1977b4b47412007-08-17 15:53:36 +00005054 }
drh41022642008-11-21 00:24:42 +00005055#if SQLITE_ENABLE_LOCKING_STYLE
5056 else{
dan08da86a2009-08-21 17:18:03 +00005057 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005058 }
5059#endif
5060
danielk1977fee2d252007-08-18 10:59:19 +00005061 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005062 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005063 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005064 /* It is safe to close fd at this point, because it is guaranteed not
5065 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005066 ** it would not be safe to close as this would release any locks held
5067 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005068 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005069 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005070 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005071 }
5072 }
danielk1977e339d652008-06-28 11:23:00 +00005073
5074#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005075 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005076#endif
5077
drhda0e7682008-07-30 15:27:54 +00005078 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005079
drh7ed97b92010-01-20 13:07:21 +00005080
5081#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5082 struct statfs fsInfo;
5083 if( fstatfs(fd, &fsInfo) == -1 ){
5084 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005085 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5086 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005087 return SQLITE_IOERR_ACCESS;
5088 }
5089 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5090 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5091 }
5092#endif
5093
5094#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005095#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005096 isAutoProxy = 1;
5097#endif
5098 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005099 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5100 int useProxy = 0;
5101
dan08da86a2009-08-21 17:18:03 +00005102 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5103 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005104 if( envforce!=NULL ){
5105 useProxy = atoi(envforce)>0;
5106 }else{
5107 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005108 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005109 /* In theory, the close(fd) call is sub-optimal. If the file opened
5110 ** with fd is a database file, and there are other connections open
5111 ** on that file that are currently holding advisory locks on it,
5112 ** then the call to close() will cancel those locks. In practice,
5113 ** we're assuming that statfs() doesn't fail very often. At least
5114 ** not while other file descriptors opened by the same process on
5115 ** the same file are working. */
5116 p->lastErrno = errno;
5117 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005118 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005119 }
drh0e9365c2011-03-02 02:08:13 +00005120 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005121 rc = SQLITE_IOERR_ACCESS;
5122 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005123 }
5124 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5125 }
5126 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005127 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5128 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005129 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005130 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005131 if( rc!=SQLITE_OK ){
5132 /* Use unixClose to clean up the resources added in fillInUnixFile
5133 ** and clear all the structure's references. Specifically,
5134 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5135 */
5136 unixClose(pFile);
5137 return rc;
5138 }
aswiftaebf4132008-11-21 00:10:35 +00005139 }
dane946c392009-08-22 11:39:46 +00005140 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005141 }
5142 }
5143#endif
5144
drh77197112011-03-15 19:08:48 +00005145 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5146 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005147open_finished:
5148 if( rc!=SQLITE_OK ){
5149 sqlite3_free(p->pUnused);
5150 }
5151 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005152}
5153
dane946c392009-08-22 11:39:46 +00005154
danielk1977b4b47412007-08-17 15:53:36 +00005155/*
danielk1977fee2d252007-08-18 10:59:19 +00005156** Delete the file at zPath. If the dirSync argument is true, fsync()
5157** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005158*/
drh6b9d6dd2008-12-03 19:34:47 +00005159static int unixDelete(
5160 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5161 const char *zPath, /* Name of file to be deleted */
5162 int dirSync /* If true, fsync() directory after deleting file */
5163){
danielk1977fee2d252007-08-18 10:59:19 +00005164 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005165 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005166 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005167 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005168 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005169 }
danielk1977d39fa702008-10-16 13:27:40 +00005170#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005171 if( dirSync ){
5172 int fd;
5173 rc = openDirectory(zPath, &fd);
5174 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005175#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005176 if( fsync(fd)==-1 )
5177#else
5178 if( fsync(fd) )
5179#endif
5180 {
dane18d4952011-02-21 11:46:24 +00005181 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005182 }
drh0e9365c2011-03-02 02:08:13 +00005183 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005184 }
5185 }
danielk1977d138dd82008-10-15 16:02:48 +00005186#endif
danielk1977fee2d252007-08-18 10:59:19 +00005187 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005188}
5189
danielk197790949c22007-08-17 16:50:38 +00005190/*
5191** Test the existance of or access permissions of file zPath. The
5192** test performed depends on the value of flags:
5193**
5194** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5195** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5196** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5197**
5198** Otherwise return 0.
5199*/
danielk1977861f7452008-06-05 11:39:11 +00005200static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005201 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5202 const char *zPath, /* Path of the file to examine */
5203 int flags, /* What do we want to learn about the zPath file? */
5204 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005205){
rse25c0d1a2007-09-20 08:38:14 +00005206 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005207 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005208 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005209 switch( flags ){
5210 case SQLITE_ACCESS_EXISTS:
5211 amode = F_OK;
5212 break;
5213 case SQLITE_ACCESS_READWRITE:
5214 amode = W_OK|R_OK;
5215 break;
drh50d3f902007-08-27 21:10:36 +00005216 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005217 amode = R_OK;
5218 break;
5219
5220 default:
5221 assert(!"Invalid flags argument");
5222 }
drh99ab3b12011-03-02 15:09:07 +00005223 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005224 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5225 struct stat buf;
5226 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5227 *pResOut = 0;
5228 }
5229 }
danielk1977861f7452008-06-05 11:39:11 +00005230 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005231}
5232
danielk1977b4b47412007-08-17 15:53:36 +00005233
5234/*
5235** Turn a relative pathname into a full pathname. The relative path
5236** is stored as a nul-terminated string in the buffer pointed to by
5237** zPath.
5238**
5239** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5240** (in this case, MAX_PATHNAME bytes). The full-path is written to
5241** this buffer before returning.
5242*/
danielk1977adfb9b02007-09-17 07:02:56 +00005243static int unixFullPathname(
5244 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5245 const char *zPath, /* Possibly relative input path */
5246 int nOut, /* Size of output buffer in bytes */
5247 char *zOut /* Output buffer */
5248){
danielk1977843e65f2007-09-01 16:16:15 +00005249
5250 /* It's odd to simulate an io-error here, but really this is just
5251 ** using the io-error infrastructure to test that SQLite handles this
5252 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005253 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005254 */
5255 SimulateIOError( return SQLITE_ERROR );
5256
drh153c62c2007-08-24 03:51:33 +00005257 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005258 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005259
drh3c7f2dc2007-12-06 13:26:20 +00005260 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005261 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005262 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005263 }else{
5264 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005265 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005266 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005267 }
drhea678832008-12-10 19:26:22 +00005268 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005269 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005270 }
5271 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005272}
5273
drh0ccebe72005-06-07 22:22:50 +00005274
drh761df872006-12-21 01:29:22 +00005275#ifndef SQLITE_OMIT_LOAD_EXTENSION
5276/*
5277** Interfaces for opening a shared library, finding entry points
5278** within the shared library, and closing the shared library.
5279*/
5280#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005281static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5282 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005283 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5284}
danielk197795c8a542007-09-01 06:51:27 +00005285
5286/*
5287** SQLite calls this function immediately after a call to unixDlSym() or
5288** unixDlOpen() fails (returns a null pointer). If a more detailed error
5289** message is available, it is written to zBufOut. If no error message
5290** is available, zBufOut is left unmodified and SQLite uses a default
5291** error message.
5292*/
danielk1977397d65f2008-11-19 11:35:39 +00005293static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005294 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005295 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005296 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005297 zErr = dlerror();
5298 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005299 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005300 }
drh6c7d5c52008-11-21 20:32:33 +00005301 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005302}
drh1875f7a2008-12-08 18:19:17 +00005303static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5304 /*
5305 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5306 ** cast into a pointer to a function. And yet the library dlsym() routine
5307 ** returns a void* which is really a pointer to a function. So how do we
5308 ** use dlsym() with -pedantic-errors?
5309 **
5310 ** Variable x below is defined to be a pointer to a function taking
5311 ** parameters void* and const char* and returning a pointer to a function.
5312 ** We initialize x by assigning it a pointer to the dlsym() function.
5313 ** (That assignment requires a cast.) Then we call the function that
5314 ** x points to.
5315 **
5316 ** This work-around is unlikely to work correctly on any system where
5317 ** you really cannot cast a function pointer into void*. But then, on the
5318 ** other hand, dlsym() will not work on such a system either, so we have
5319 ** not really lost anything.
5320 */
5321 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005322 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005323 x = (void(*(*)(void*,const char*))(void))dlsym;
5324 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005325}
danielk1977397d65f2008-11-19 11:35:39 +00005326static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5327 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005328 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005329}
danielk1977b4b47412007-08-17 15:53:36 +00005330#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5331 #define unixDlOpen 0
5332 #define unixDlError 0
5333 #define unixDlSym 0
5334 #define unixDlClose 0
5335#endif
5336
5337/*
danielk197790949c22007-08-17 16:50:38 +00005338** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005339*/
danielk1977397d65f2008-11-19 11:35:39 +00005340static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5341 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005342 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005343
drhbbd42a62004-05-22 17:41:58 +00005344 /* We have to initialize zBuf to prevent valgrind from reporting
5345 ** errors. The reports issued by valgrind are incorrect - we would
5346 ** prefer that the randomness be increased by making use of the
5347 ** uninitialized space in zBuf - but valgrind errors tend to worry
5348 ** some users. Rather than argue, it seems easier just to initialize
5349 ** the whole array and silence valgrind, even if that means less randomness
5350 ** in the random seed.
5351 **
5352 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005353 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005354 ** tests repeatable.
5355 */
danielk1977b4b47412007-08-17 15:53:36 +00005356 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005357#if !defined(SQLITE_TEST)
5358 {
drh842b8642005-01-21 17:53:17 +00005359 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005360 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005361 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005362 time_t t;
5363 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005364 memcpy(zBuf, &t, sizeof(t));
5365 pid = getpid();
5366 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005367 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005368 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005369 }else{
drhe562be52011-03-02 18:01:10 +00005370 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005371 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005372 }
drhbbd42a62004-05-22 17:41:58 +00005373 }
5374#endif
drh72cbd072008-10-14 17:58:38 +00005375 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005376}
5377
danielk1977b4b47412007-08-17 15:53:36 +00005378
drhbbd42a62004-05-22 17:41:58 +00005379/*
5380** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005381** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005382** The return value is the number of microseconds of sleep actually
5383** requested from the underlying operating system, a number which
5384** might be greater than or equal to the argument, but not less
5385** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005386*/
danielk1977397d65f2008-11-19 11:35:39 +00005387static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005388#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005389 struct timespec sp;
5390
5391 sp.tv_sec = microseconds / 1000000;
5392 sp.tv_nsec = (microseconds % 1000000) * 1000;
5393 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005394 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005395 return microseconds;
5396#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005397 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005398 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005399 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005400#else
danielk1977b4b47412007-08-17 15:53:36 +00005401 int seconds = (microseconds+999999)/1000000;
5402 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005403 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005404 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005405#endif
drh88f474a2006-01-02 20:00:12 +00005406}
5407
5408/*
drh6b9d6dd2008-12-03 19:34:47 +00005409** The following variable, if set to a non-zero value, is interpreted as
5410** the number of seconds since 1970 and is used to set the result of
5411** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005412*/
5413#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005414int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005415#endif
5416
5417/*
drhb7e8ea22010-05-03 14:32:30 +00005418** Find the current time (in Universal Coordinated Time). Write into *piNow
5419** the current time and date as a Julian Day number times 86_400_000. In
5420** other words, write into *piNow the number of milliseconds since the Julian
5421** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5422** proleptic Gregorian calendar.
5423**
5424** On success, return 0. Return 1 if the time and date cannot be found.
5425*/
5426static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5427 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5428#if defined(NO_GETTOD)
5429 time_t t;
5430 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005431 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005432#elif OS_VXWORKS
5433 struct timespec sNow;
5434 clock_gettime(CLOCK_REALTIME, &sNow);
5435 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5436#else
5437 struct timeval sNow;
5438 gettimeofday(&sNow, 0);
5439 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5440#endif
5441
5442#ifdef SQLITE_TEST
5443 if( sqlite3_current_time ){
5444 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5445 }
5446#endif
5447 UNUSED_PARAMETER(NotUsed);
5448 return 0;
5449}
5450
5451/*
drhbbd42a62004-05-22 17:41:58 +00005452** Find the current time (in Universal Coordinated Time). Write the
5453** current time and date as a Julian Day number into *prNow and
5454** return 0. Return 1 if the time and date cannot be found.
5455*/
danielk1977397d65f2008-11-19 11:35:39 +00005456static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005457 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005458 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005459 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005460 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005461 return 0;
5462}
danielk1977b4b47412007-08-17 15:53:36 +00005463
drh6b9d6dd2008-12-03 19:34:47 +00005464/*
5465** We added the xGetLastError() method with the intention of providing
5466** better low-level error messages when operating-system problems come up
5467** during SQLite operation. But so far, none of that has been implemented
5468** in the core. So this routine is never called. For now, it is merely
5469** a place-holder.
5470*/
danielk1977397d65f2008-11-19 11:35:39 +00005471static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5472 UNUSED_PARAMETER(NotUsed);
5473 UNUSED_PARAMETER(NotUsed2);
5474 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005475 return 0;
5476}
5477
drhf2424c52010-04-26 00:04:55 +00005478
5479/*
drh734c9862008-11-28 15:37:20 +00005480************************ End of sqlite3_vfs methods ***************************
5481******************************************************************************/
5482
drh715ff302008-12-03 22:32:44 +00005483/******************************************************************************
5484************************** Begin Proxy Locking ********************************
5485**
5486** Proxy locking is a "uber-locking-method" in this sense: It uses the
5487** other locking methods on secondary lock files. Proxy locking is a
5488** meta-layer over top of the primitive locking implemented above. For
5489** this reason, the division that implements of proxy locking is deferred
5490** until late in the file (here) after all of the other I/O methods have
5491** been defined - so that the primitive locking methods are available
5492** as services to help with the implementation of proxy locking.
5493**
5494****
5495**
5496** The default locking schemes in SQLite use byte-range locks on the
5497** database file to coordinate safe, concurrent access by multiple readers
5498** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5499** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5500** as POSIX read & write locks over fixed set of locations (via fsctl),
5501** on AFP and SMB only exclusive byte-range locks are available via fsctl
5502** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5503** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5504** address in the shared range is taken for a SHARED lock, the entire
5505** shared range is taken for an EXCLUSIVE lock):
5506**
5507** PENDING_BYTE 0x40000000
5508** RESERVED_BYTE 0x40000001
5509** SHARED_RANGE 0x40000002 -> 0x40000200
5510**
5511** This works well on the local file system, but shows a nearly 100x
5512** slowdown in read performance on AFP because the AFP client disables
5513** the read cache when byte-range locks are present. Enabling the read
5514** cache exposes a cache coherency problem that is present on all OS X
5515** supported network file systems. NFS and AFP both observe the
5516** close-to-open semantics for ensuring cache coherency
5517** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5518** address the requirements for concurrent database access by multiple
5519** readers and writers
5520** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5521**
5522** To address the performance and cache coherency issues, proxy file locking
5523** changes the way database access is controlled by limiting access to a
5524** single host at a time and moving file locks off of the database file
5525** and onto a proxy file on the local file system.
5526**
5527**
5528** Using proxy locks
5529** -----------------
5530**
5531** C APIs
5532**
5533** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5534** <proxy_path> | ":auto:");
5535** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5536**
5537**
5538** SQL pragmas
5539**
5540** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5541** PRAGMA [database.]lock_proxy_file
5542**
5543** Specifying ":auto:" means that if there is a conch file with a matching
5544** host ID in it, the proxy path in the conch file will be used, otherwise
5545** a proxy path based on the user's temp dir
5546** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5547** actual proxy file name is generated from the name and path of the
5548** database file. For example:
5549**
5550** For database path "/Users/me/foo.db"
5551** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5552**
5553** Once a lock proxy is configured for a database connection, it can not
5554** be removed, however it may be switched to a different proxy path via
5555** the above APIs (assuming the conch file is not being held by another
5556** connection or process).
5557**
5558**
5559** How proxy locking works
5560** -----------------------
5561**
5562** Proxy file locking relies primarily on two new supporting files:
5563**
5564** * conch file to limit access to the database file to a single host
5565** at a time
5566**
5567** * proxy file to act as a proxy for the advisory locks normally
5568** taken on the database
5569**
5570** The conch file - to use a proxy file, sqlite must first "hold the conch"
5571** by taking an sqlite-style shared lock on the conch file, reading the
5572** contents and comparing the host's unique host ID (see below) and lock
5573** proxy path against the values stored in the conch. The conch file is
5574** stored in the same directory as the database file and the file name
5575** is patterned after the database file name as ".<databasename>-conch".
5576** If the conch file does not exist, or it's contents do not match the
5577** host ID and/or proxy path, then the lock is escalated to an exclusive
5578** lock and the conch file contents is updated with the host ID and proxy
5579** path and the lock is downgraded to a shared lock again. If the conch
5580** is held by another process (with a shared lock), the exclusive lock
5581** will fail and SQLITE_BUSY is returned.
5582**
5583** The proxy file - a single-byte file used for all advisory file locks
5584** normally taken on the database file. This allows for safe sharing
5585** of the database file for multiple readers and writers on the same
5586** host (the conch ensures that they all use the same local lock file).
5587**
drh715ff302008-12-03 22:32:44 +00005588** Requesting the lock proxy does not immediately take the conch, it is
5589** only taken when the first request to lock database file is made.
5590** This matches the semantics of the traditional locking behavior, where
5591** opening a connection to a database file does not take a lock on it.
5592** The shared lock and an open file descriptor are maintained until
5593** the connection to the database is closed.
5594**
5595** The proxy file and the lock file are never deleted so they only need
5596** to be created the first time they are used.
5597**
5598** Configuration options
5599** ---------------------
5600**
5601** SQLITE_PREFER_PROXY_LOCKING
5602**
5603** Database files accessed on non-local file systems are
5604** automatically configured for proxy locking, lock files are
5605** named automatically using the same logic as
5606** PRAGMA lock_proxy_file=":auto:"
5607**
5608** SQLITE_PROXY_DEBUG
5609**
5610** Enables the logging of error messages during host id file
5611** retrieval and creation
5612**
drh715ff302008-12-03 22:32:44 +00005613** LOCKPROXYDIR
5614**
5615** Overrides the default directory used for lock proxy files that
5616** are named automatically via the ":auto:" setting
5617**
5618** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5619**
5620** Permissions to use when creating a directory for storing the
5621** lock proxy files, only used when LOCKPROXYDIR is not set.
5622**
5623**
5624** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5625** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5626** force proxy locking to be used for every database file opened, and 0
5627** will force automatic proxy locking to be disabled for all database
5628** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5629** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5630*/
5631
5632/*
5633** Proxy locking is only available on MacOSX
5634*/
drhd2cb50b2009-01-09 21:41:17 +00005635#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005636
drh715ff302008-12-03 22:32:44 +00005637/*
5638** The proxyLockingContext has the path and file structures for the remote
5639** and local proxy files in it
5640*/
5641typedef struct proxyLockingContext proxyLockingContext;
5642struct proxyLockingContext {
5643 unixFile *conchFile; /* Open conch file */
5644 char *conchFilePath; /* Name of the conch file */
5645 unixFile *lockProxy; /* Open proxy lock file */
5646 char *lockProxyPath; /* Name of the proxy lock file */
5647 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005648 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005649 void *oldLockingContext; /* Original lockingcontext to restore on close */
5650 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5651};
5652
drh7ed97b92010-01-20 13:07:21 +00005653/*
5654** The proxy lock file path for the database at dbPath is written into lPath,
5655** which must point to valid, writable memory large enough for a maxLen length
5656** file path.
drh715ff302008-12-03 22:32:44 +00005657*/
drh715ff302008-12-03 22:32:44 +00005658static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5659 int len;
5660 int dbLen;
5661 int i;
5662
5663#ifdef LOCKPROXYDIR
5664 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5665#else
5666# ifdef _CS_DARWIN_USER_TEMP_DIR
5667 {
drh7ed97b92010-01-20 13:07:21 +00005668 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005669 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5670 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005671 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005672 }
drh7ed97b92010-01-20 13:07:21 +00005673 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005674 }
5675# else
5676 len = strlcpy(lPath, "/tmp/", maxLen);
5677# endif
5678#endif
5679
5680 if( lPath[len-1]!='/' ){
5681 len = strlcat(lPath, "/", maxLen);
5682 }
5683
5684 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005685 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005686 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005687 char c = dbPath[i];
5688 lPath[i+len] = (c=='/')?'_':c;
5689 }
5690 lPath[i+len]='\0';
5691 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005692 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005693 return SQLITE_OK;
5694}
5695
drh7ed97b92010-01-20 13:07:21 +00005696/*
5697 ** Creates the lock file and any missing directories in lockPath
5698 */
5699static int proxyCreateLockPath(const char *lockPath){
5700 int i, len;
5701 char buf[MAXPATHLEN];
5702 int start = 0;
5703
5704 assert(lockPath!=NULL);
5705 /* try to create all the intermediate directories */
5706 len = (int)strlen(lockPath);
5707 buf[0] = lockPath[0];
5708 for( i=1; i<len; i++ ){
5709 if( lockPath[i] == '/' && (i - start > 0) ){
5710 /* only mkdir if leaf dir != "." or "/" or ".." */
5711 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5712 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5713 buf[i]='\0';
5714 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5715 int err=errno;
5716 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005717 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005718 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005719 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005720 return err;
5721 }
5722 }
5723 }
5724 start=i+1;
5725 }
5726 buf[i] = lockPath[i];
5727 }
drh308c2a52010-05-14 11:30:18 +00005728 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005729 return 0;
5730}
5731
drh715ff302008-12-03 22:32:44 +00005732/*
5733** Create a new VFS file descriptor (stored in memory obtained from
5734** sqlite3_malloc) and open the file named "path" in the file descriptor.
5735**
5736** The caller is responsible not only for closing the file descriptor
5737** but also for freeing the memory associated with the file descriptor.
5738*/
drh7ed97b92010-01-20 13:07:21 +00005739static int proxyCreateUnixFile(
5740 const char *path, /* path for the new unixFile */
5741 unixFile **ppFile, /* unixFile created and returned by ref */
5742 int islockfile /* if non zero missing dirs will be created */
5743) {
5744 int fd = -1;
5745 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005746 unixFile *pNew;
5747 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005748 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005749 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005750 int terrno = 0;
5751 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005752
drh7ed97b92010-01-20 13:07:21 +00005753 /* 1. first try to open/create the file
5754 ** 2. if that fails, and this is a lock file (not-conch), try creating
5755 ** the parent directories and then try again.
5756 ** 3. if that fails, try to open the file read-only
5757 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5758 */
5759 pUnused = findReusableFd(path, openFlags);
5760 if( pUnused ){
5761 fd = pUnused->fd;
5762 }else{
5763 pUnused = sqlite3_malloc(sizeof(*pUnused));
5764 if( !pUnused ){
5765 return SQLITE_NOMEM;
5766 }
5767 }
5768 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005769 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005770 terrno = errno;
5771 if( fd<0 && errno==ENOENT && islockfile ){
5772 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005773 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005774 }
5775 }
5776 }
5777 if( fd<0 ){
5778 openFlags = O_RDONLY;
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 }
5782 if( fd<0 ){
5783 if( islockfile ){
5784 return SQLITE_BUSY;
5785 }
5786 switch (terrno) {
5787 case EACCES:
5788 return SQLITE_PERM;
5789 case EIO:
5790 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5791 default:
drh9978c972010-02-23 17:36:32 +00005792 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005793 }
5794 }
5795
5796 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5797 if( pNew==NULL ){
5798 rc = SQLITE_NOMEM;
5799 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005800 }
5801 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005802 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005803 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005804 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005805 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005806 pUnused->fd = fd;
5807 pUnused->flags = openFlags;
5808 pNew->pUnused = pUnused;
5809
drh77197112011-03-15 19:08:48 +00005810 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005811 if( rc==SQLITE_OK ){
5812 *ppFile = pNew;
5813 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005814 }
drh7ed97b92010-01-20 13:07:21 +00005815end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005816 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005817 sqlite3_free(pNew);
5818 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005819 return rc;
5820}
5821
drh7ed97b92010-01-20 13:07:21 +00005822#ifdef SQLITE_TEST
5823/* simulate multiple hosts by creating unique hostid file paths */
5824int sqlite3_hostid_num = 0;
5825#endif
5826
5827#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5828
drh0ab216a2010-07-02 17:10:40 +00005829/* Not always defined in the headers as it ought to be */
5830extern int gethostuuid(uuid_t id, const struct timespec *wait);
5831
drh7ed97b92010-01-20 13:07:21 +00005832/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5833** bytes of writable memory.
5834*/
5835static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005836 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5837 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005838#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5839 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005840 {
5841 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5842 if( gethostuuid(pHostID, &timeout) ){
5843 int err = errno;
5844 if( pError ){
5845 *pError = err;
5846 }
5847 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005848 }
drh7ed97b92010-01-20 13:07:21 +00005849 }
drhe8b0c9b2010-09-25 14:13:17 +00005850#endif
drh7ed97b92010-01-20 13:07:21 +00005851#ifdef SQLITE_TEST
5852 /* simulate multiple hosts by creating unique hostid file paths */
5853 if( sqlite3_hostid_num != 0){
5854 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5855 }
5856#endif
5857
5858 return SQLITE_OK;
5859}
5860
5861/* The conch file contains the header, host id and lock file path
5862 */
5863#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5864#define PROXY_HEADERLEN 1 /* conch file header length */
5865#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5866#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5867
5868/*
5869** Takes an open conch file, copies the contents to a new path and then moves
5870** it back. The newly created file's file descriptor is assigned to the
5871** conch file structure and finally the original conch file descriptor is
5872** closed. Returns zero if successful.
5873*/
5874static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5875 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5876 unixFile *conchFile = pCtx->conchFile;
5877 char tPath[MAXPATHLEN];
5878 char buf[PROXY_MAXCONCHLEN];
5879 char *cPath = pCtx->conchFilePath;
5880 size_t readLen = 0;
5881 size_t pathLen = 0;
5882 char errmsg[64] = "";
5883 int fd = -1;
5884 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005885 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005886
5887 /* create a new path by replace the trailing '-conch' with '-break' */
5888 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5889 if( pathLen>MAXPATHLEN || pathLen<6 ||
5890 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005891 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005892 goto end_breaklock;
5893 }
5894 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005895 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005896 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005897 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005898 goto end_breaklock;
5899 }
5900 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005901 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5902 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005903 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005904 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005905 goto end_breaklock;
5906 }
drhe562be52011-03-02 18:01:10 +00005907 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005908 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005909 goto end_breaklock;
5910 }
5911 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005912 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005913 goto end_breaklock;
5914 }
5915 rc = 0;
5916 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005917 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005918 conchFile->h = fd;
5919 conchFile->openFlags = O_RDWR | O_CREAT;
5920
5921end_breaklock:
5922 if( rc ){
5923 if( fd>=0 ){
5924 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005925 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005926 }
5927 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5928 }
5929 return rc;
5930}
5931
5932/* Take the requested lock on the conch file and break a stale lock if the
5933** host id matches.
5934*/
5935static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5936 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5937 unixFile *conchFile = pCtx->conchFile;
5938 int rc = SQLITE_OK;
5939 int nTries = 0;
5940 struct timespec conchModTime;
5941
5942 do {
5943 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5944 nTries ++;
5945 if( rc==SQLITE_BUSY ){
5946 /* If the lock failed (busy):
5947 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5948 * 2nd try: fail if the mod time changed or host id is different, wait
5949 * 10 sec and try again
5950 * 3rd try: break the lock unless the mod time has changed.
5951 */
5952 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005953 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005954 pFile->lastErrno = errno;
5955 return SQLITE_IOERR_LOCK;
5956 }
5957
5958 if( nTries==1 ){
5959 conchModTime = buf.st_mtimespec;
5960 usleep(500000); /* wait 0.5 sec and try the lock again*/
5961 continue;
5962 }
5963
5964 assert( nTries>1 );
5965 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5966 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5967 return SQLITE_BUSY;
5968 }
5969
5970 if( nTries==2 ){
5971 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005972 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005973 if( len<0 ){
5974 pFile->lastErrno = errno;
5975 return SQLITE_IOERR_LOCK;
5976 }
5977 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5978 /* don't break the lock if the host id doesn't match */
5979 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5980 return SQLITE_BUSY;
5981 }
5982 }else{
5983 /* don't break the lock on short read or a version mismatch */
5984 return SQLITE_BUSY;
5985 }
5986 usleep(10000000); /* wait 10 sec and try the lock again */
5987 continue;
5988 }
5989
5990 assert( nTries==3 );
5991 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5992 rc = SQLITE_OK;
5993 if( lockType==EXCLUSIVE_LOCK ){
5994 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5995 }
5996 if( !rc ){
5997 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5998 }
5999 }
6000 }
6001 } while( rc==SQLITE_BUSY && nTries<3 );
6002
6003 return rc;
6004}
6005
6006/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006007** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6008** lockPath means that the lockPath in the conch file will be used if the
6009** host IDs match, or a new lock path will be generated automatically
6010** and written to the conch file.
6011*/
6012static int proxyTakeConch(unixFile *pFile){
6013 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6014
drh7ed97b92010-01-20 13:07:21 +00006015 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006016 return SQLITE_OK;
6017 }else{
6018 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006019 uuid_t myHostID;
6020 int pError = 0;
6021 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006022 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006023 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006024 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006025 int createConch = 0;
6026 int hostIdMatch = 0;
6027 int readLen = 0;
6028 int tryOldLockPath = 0;
6029 int forceNewLockPath = 0;
6030
drh308c2a52010-05-14 11:30:18 +00006031 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6032 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006033
drh7ed97b92010-01-20 13:07:21 +00006034 rc = proxyGetHostID(myHostID, &pError);
6035 if( (rc&0xff)==SQLITE_IOERR ){
6036 pFile->lastErrno = pError;
6037 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006038 }
drh7ed97b92010-01-20 13:07:21 +00006039 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006040 if( rc!=SQLITE_OK ){
6041 goto end_takeconch;
6042 }
drh7ed97b92010-01-20 13:07:21 +00006043 /* read the existing conch file */
6044 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6045 if( readLen<0 ){
6046 /* I/O error: lastErrno set by seekAndRead */
6047 pFile->lastErrno = conchFile->lastErrno;
6048 rc = SQLITE_IOERR_READ;
6049 goto end_takeconch;
6050 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6051 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6052 /* a short read or version format mismatch means we need to create a new
6053 ** conch file.
6054 */
6055 createConch = 1;
6056 }
6057 /* if the host id matches and the lock path already exists in the conch
6058 ** we'll try to use the path there, if we can't open that path, we'll
6059 ** retry with a new auto-generated path
6060 */
6061 do { /* in case we need to try again for an :auto: named lock file */
6062
6063 if( !createConch && !forceNewLockPath ){
6064 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6065 PROXY_HOSTIDLEN);
6066 /* if the conch has data compare the contents */
6067 if( !pCtx->lockProxyPath ){
6068 /* for auto-named local lock file, just check the host ID and we'll
6069 ** use the local lock file path that's already in there
6070 */
6071 if( hostIdMatch ){
6072 size_t pathLen = (readLen - PROXY_PATHINDEX);
6073
6074 if( pathLen>=MAXPATHLEN ){
6075 pathLen=MAXPATHLEN-1;
6076 }
6077 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6078 lockPath[pathLen] = 0;
6079 tempLockPath = lockPath;
6080 tryOldLockPath = 1;
6081 /* create a copy of the lock path if the conch is taken */
6082 goto end_takeconch;
6083 }
6084 }else if( hostIdMatch
6085 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6086 readLen-PROXY_PATHINDEX)
6087 ){
6088 /* conch host and lock path match */
6089 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006090 }
drh7ed97b92010-01-20 13:07:21 +00006091 }
6092
6093 /* if the conch isn't writable and doesn't match, we can't take it */
6094 if( (conchFile->openFlags&O_RDWR) == 0 ){
6095 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006096 goto end_takeconch;
6097 }
drh7ed97b92010-01-20 13:07:21 +00006098
6099 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006100 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006101 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6102 tempLockPath = lockPath;
6103 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006104 }
drh7ed97b92010-01-20 13:07:21 +00006105
6106 /* update conch with host and path (this will fail if other process
6107 ** has a shared lock already), if the host id matches, use the big
6108 ** stick.
drh715ff302008-12-03 22:32:44 +00006109 */
drh7ed97b92010-01-20 13:07:21 +00006110 futimes(conchFile->h, NULL);
6111 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006112 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006113 /* We are trying for an exclusive lock but another thread in this
6114 ** same process is still holding a shared lock. */
6115 rc = SQLITE_BUSY;
6116 } else {
6117 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006118 }
drh715ff302008-12-03 22:32:44 +00006119 }else{
drh7ed97b92010-01-20 13:07:21 +00006120 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006121 }
drh7ed97b92010-01-20 13:07:21 +00006122 if( rc==SQLITE_OK ){
6123 char writeBuffer[PROXY_MAXCONCHLEN];
6124 int writeSize = 0;
6125
6126 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6127 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6128 if( pCtx->lockProxyPath!=NULL ){
6129 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6130 }else{
6131 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6132 }
6133 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006134 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006135 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6136 fsync(conchFile->h);
6137 /* If we created a new conch file (not just updated the contents of a
6138 ** valid conch file), try to match the permissions of the database
6139 */
6140 if( rc==SQLITE_OK && createConch ){
6141 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006142 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006143 if( err==0 ){
6144 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6145 S_IROTH|S_IWOTH);
6146 /* try to match the database file R/W permissions, ignore failure */
6147#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006148 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006149#else
drhff812312011-02-23 13:33:46 +00006150 do{
drhe562be52011-03-02 18:01:10 +00006151 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006152 }while( rc==(-1) && errno==EINTR );
6153 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006154 int code = errno;
6155 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6156 cmode, code, strerror(code));
6157 } else {
6158 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6159 }
6160 }else{
6161 int code = errno;
6162 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6163 err, code, strerror(code));
6164#endif
6165 }
drh715ff302008-12-03 22:32:44 +00006166 }
6167 }
drh7ed97b92010-01-20 13:07:21 +00006168 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6169
6170 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006171 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006172 if( rc==SQLITE_OK && pFile->openFlags ){
6173 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006174 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006175 }
6176 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006177 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006178 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006179 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006180 if( fd>=0 ){
6181 pFile->h = fd;
6182 }else{
drh9978c972010-02-23 17:36:32 +00006183 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006184 during locking */
6185 }
6186 }
6187 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6188 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6189 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6190 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6191 /* we couldn't create the proxy lock file with the old lock file path
6192 ** so try again via auto-naming
6193 */
6194 forceNewLockPath = 1;
6195 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006196 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006197 }
6198 }
6199 if( rc==SQLITE_OK ){
6200 /* Need to make a copy of path if we extracted the value
6201 ** from the conch file or the path was allocated on the stack
6202 */
6203 if( tempLockPath ){
6204 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6205 if( !pCtx->lockProxyPath ){
6206 rc = SQLITE_NOMEM;
6207 }
6208 }
6209 }
6210 if( rc==SQLITE_OK ){
6211 pCtx->conchHeld = 1;
6212
6213 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6214 afpLockingContext *afpCtx;
6215 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6216 afpCtx->dbPath = pCtx->lockProxyPath;
6217 }
6218 } else {
6219 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6220 }
drh308c2a52010-05-14 11:30:18 +00006221 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6222 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006223 return rc;
drh308c2a52010-05-14 11:30:18 +00006224 } while (1); /* in case we need to retry the :auto: lock file -
6225 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006226 }
6227}
6228
6229/*
6230** If pFile holds a lock on a conch file, then release that lock.
6231*/
6232static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006233 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006234 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6235 unixFile *conchFile; /* Name of the conch file */
6236
6237 pCtx = (proxyLockingContext *)pFile->lockingContext;
6238 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006239 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006240 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006241 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006242 if( pCtx->conchHeld>0 ){
6243 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6244 }
drh715ff302008-12-03 22:32:44 +00006245 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006246 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6247 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006248 return rc;
6249}
6250
6251/*
6252** Given the name of a database file, compute the name of its conch file.
6253** Store the conch filename in memory obtained from sqlite3_malloc().
6254** Make *pConchPath point to the new name. Return SQLITE_OK on success
6255** or SQLITE_NOMEM if unable to obtain memory.
6256**
6257** The caller is responsible for ensuring that the allocated memory
6258** space is eventually freed.
6259**
6260** *pConchPath is set to NULL if a memory allocation error occurs.
6261*/
6262static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6263 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006264 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006265 char *conchPath; /* buffer in which to construct conch name */
6266
6267 /* Allocate space for the conch filename and initialize the name to
6268 ** the name of the original database file. */
6269 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6270 if( conchPath==0 ){
6271 return SQLITE_NOMEM;
6272 }
6273 memcpy(conchPath, dbPath, len+1);
6274
6275 /* now insert a "." before the last / character */
6276 for( i=(len-1); i>=0; i-- ){
6277 if( conchPath[i]=='/' ){
6278 i++;
6279 break;
6280 }
6281 }
6282 conchPath[i]='.';
6283 while ( i<len ){
6284 conchPath[i+1]=dbPath[i];
6285 i++;
6286 }
6287
6288 /* append the "-conch" suffix to the file */
6289 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006290 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006291
6292 return SQLITE_OK;
6293}
6294
6295
6296/* Takes a fully configured proxy locking-style unix file and switches
6297** the local lock file path
6298*/
6299static int switchLockProxyPath(unixFile *pFile, const char *path) {
6300 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6301 char *oldPath = pCtx->lockProxyPath;
6302 int rc = SQLITE_OK;
6303
drh308c2a52010-05-14 11:30:18 +00006304 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006305 return SQLITE_BUSY;
6306 }
6307
6308 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6309 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6310 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6311 return SQLITE_OK;
6312 }else{
6313 unixFile *lockProxy = pCtx->lockProxy;
6314 pCtx->lockProxy=NULL;
6315 pCtx->conchHeld = 0;
6316 if( lockProxy!=NULL ){
6317 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6318 if( rc ) return rc;
6319 sqlite3_free(lockProxy);
6320 }
6321 sqlite3_free(oldPath);
6322 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6323 }
6324
6325 return rc;
6326}
6327
6328/*
6329** pFile is a file that has been opened by a prior xOpen call. dbPath
6330** is a string buffer at least MAXPATHLEN+1 characters in size.
6331**
6332** This routine find the filename associated with pFile and writes it
6333** int dbPath.
6334*/
6335static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006336#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006337 if( pFile->pMethod == &afpIoMethods ){
6338 /* afp style keeps a reference to the db path in the filePath field
6339 ** of the struct */
drhea678832008-12-10 19:26:22 +00006340 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006341 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6342 } else
drh715ff302008-12-03 22:32:44 +00006343#endif
6344 if( pFile->pMethod == &dotlockIoMethods ){
6345 /* dot lock style uses the locking context to store the dot lock
6346 ** file path */
6347 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6348 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6349 }else{
6350 /* all other styles use the locking context to store the db file path */
6351 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006352 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006353 }
6354 return SQLITE_OK;
6355}
6356
6357/*
6358** Takes an already filled in unix file and alters it so all file locking
6359** will be performed on the local proxy lock file. The following fields
6360** are preserved in the locking context so that they can be restored and
6361** the unix structure properly cleaned up at close time:
6362** ->lockingContext
6363** ->pMethod
6364*/
6365static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6366 proxyLockingContext *pCtx;
6367 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6368 char *lockPath=NULL;
6369 int rc = SQLITE_OK;
6370
drh308c2a52010-05-14 11:30:18 +00006371 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006372 return SQLITE_BUSY;
6373 }
6374 proxyGetDbPathForUnixFile(pFile, dbPath);
6375 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6376 lockPath=NULL;
6377 }else{
6378 lockPath=(char *)path;
6379 }
6380
drh308c2a52010-05-14 11:30:18 +00006381 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6382 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006383
6384 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6385 if( pCtx==0 ){
6386 return SQLITE_NOMEM;
6387 }
6388 memset(pCtx, 0, sizeof(*pCtx));
6389
6390 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6391 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006392 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6393 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6394 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6395 ** (c) the file system is read-only, then enable no-locking access.
6396 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6397 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6398 */
6399 struct statfs fsInfo;
6400 struct stat conchInfo;
6401 int goLockless = 0;
6402
drh99ab3b12011-03-02 15:09:07 +00006403 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006404 int err = errno;
6405 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6406 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6407 }
6408 }
6409 if( goLockless ){
6410 pCtx->conchHeld = -1; /* read only FS/ lockless */
6411 rc = SQLITE_OK;
6412 }
6413 }
drh715ff302008-12-03 22:32:44 +00006414 }
6415 if( rc==SQLITE_OK && lockPath ){
6416 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6417 }
6418
6419 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006420 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6421 if( pCtx->dbPath==NULL ){
6422 rc = SQLITE_NOMEM;
6423 }
6424 }
6425 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006426 /* all memory is allocated, proxys are created and assigned,
6427 ** switch the locking context and pMethod then return.
6428 */
drh715ff302008-12-03 22:32:44 +00006429 pCtx->oldLockingContext = pFile->lockingContext;
6430 pFile->lockingContext = pCtx;
6431 pCtx->pOldMethod = pFile->pMethod;
6432 pFile->pMethod = &proxyIoMethods;
6433 }else{
6434 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006435 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006436 sqlite3_free(pCtx->conchFile);
6437 }
drhd56b1212010-08-11 06:14:15 +00006438 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006439 sqlite3_free(pCtx->conchFilePath);
6440 sqlite3_free(pCtx);
6441 }
drh308c2a52010-05-14 11:30:18 +00006442 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6443 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006444 return rc;
6445}
6446
6447
6448/*
6449** This routine handles sqlite3_file_control() calls that are specific
6450** to proxy locking.
6451*/
6452static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6453 switch( op ){
6454 case SQLITE_GET_LOCKPROXYFILE: {
6455 unixFile *pFile = (unixFile*)id;
6456 if( pFile->pMethod == &proxyIoMethods ){
6457 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6458 proxyTakeConch(pFile);
6459 if( pCtx->lockProxyPath ){
6460 *(const char **)pArg = pCtx->lockProxyPath;
6461 }else{
6462 *(const char **)pArg = ":auto: (not held)";
6463 }
6464 } else {
6465 *(const char **)pArg = NULL;
6466 }
6467 return SQLITE_OK;
6468 }
6469 case SQLITE_SET_LOCKPROXYFILE: {
6470 unixFile *pFile = (unixFile*)id;
6471 int rc = SQLITE_OK;
6472 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6473 if( pArg==NULL || (const char *)pArg==0 ){
6474 if( isProxyStyle ){
6475 /* turn off proxy locking - not supported */
6476 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6477 }else{
6478 /* turn off proxy locking - already off - NOOP */
6479 rc = SQLITE_OK;
6480 }
6481 }else{
6482 const char *proxyPath = (const char *)pArg;
6483 if( isProxyStyle ){
6484 proxyLockingContext *pCtx =
6485 (proxyLockingContext*)pFile->lockingContext;
6486 if( !strcmp(pArg, ":auto:")
6487 || (pCtx->lockProxyPath &&
6488 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6489 ){
6490 rc = SQLITE_OK;
6491 }else{
6492 rc = switchLockProxyPath(pFile, proxyPath);
6493 }
6494 }else{
6495 /* turn on proxy file locking */
6496 rc = proxyTransformUnixFile(pFile, proxyPath);
6497 }
6498 }
6499 return rc;
6500 }
6501 default: {
6502 assert( 0 ); /* The call assures that only valid opcodes are sent */
6503 }
6504 }
6505 /*NOTREACHED*/
6506 return SQLITE_ERROR;
6507}
6508
6509/*
6510** Within this division (the proxying locking implementation) the procedures
6511** above this point are all utilities. The lock-related methods of the
6512** proxy-locking sqlite3_io_method object follow.
6513*/
6514
6515
6516/*
6517** This routine checks if there is a RESERVED lock held on the specified
6518** file by this or any other process. If such a lock is held, set *pResOut
6519** to a non-zero value otherwise *pResOut is set to zero. The return value
6520** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6521*/
6522static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6523 unixFile *pFile = (unixFile*)id;
6524 int rc = proxyTakeConch(pFile);
6525 if( rc==SQLITE_OK ){
6526 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006527 if( pCtx->conchHeld>0 ){
6528 unixFile *proxy = pCtx->lockProxy;
6529 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6530 }else{ /* conchHeld < 0 is lockless */
6531 pResOut=0;
6532 }
drh715ff302008-12-03 22:32:44 +00006533 }
6534 return rc;
6535}
6536
6537/*
drh308c2a52010-05-14 11:30:18 +00006538** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006539** of the following:
6540**
6541** (1) SHARED_LOCK
6542** (2) RESERVED_LOCK
6543** (3) PENDING_LOCK
6544** (4) EXCLUSIVE_LOCK
6545**
6546** Sometimes when requesting one lock state, additional lock states
6547** are inserted in between. The locking might fail on one of the later
6548** transitions leaving the lock state different from what it started but
6549** still short of its goal. The following chart shows the allowed
6550** transitions and the inserted intermediate states:
6551**
6552** UNLOCKED -> SHARED
6553** SHARED -> RESERVED
6554** SHARED -> (PENDING) -> EXCLUSIVE
6555** RESERVED -> (PENDING) -> EXCLUSIVE
6556** PENDING -> EXCLUSIVE
6557**
6558** This routine will only increase a lock. Use the sqlite3OsUnlock()
6559** routine to lower a locking level.
6560*/
drh308c2a52010-05-14 11:30:18 +00006561static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006562 unixFile *pFile = (unixFile*)id;
6563 int rc = proxyTakeConch(pFile);
6564 if( rc==SQLITE_OK ){
6565 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006566 if( pCtx->conchHeld>0 ){
6567 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006568 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6569 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006570 }else{
6571 /* conchHeld < 0 is lockless */
6572 }
drh715ff302008-12-03 22:32:44 +00006573 }
6574 return rc;
6575}
6576
6577
6578/*
drh308c2a52010-05-14 11:30:18 +00006579** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006580** must be either NO_LOCK or SHARED_LOCK.
6581**
6582** If the locking level of the file descriptor is already at or below
6583** the requested locking level, this routine is a no-op.
6584*/
drh308c2a52010-05-14 11:30:18 +00006585static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006586 unixFile *pFile = (unixFile*)id;
6587 int rc = proxyTakeConch(pFile);
6588 if( rc==SQLITE_OK ){
6589 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006590 if( pCtx->conchHeld>0 ){
6591 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006592 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6593 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006594 }else{
6595 /* conchHeld < 0 is lockless */
6596 }
drh715ff302008-12-03 22:32:44 +00006597 }
6598 return rc;
6599}
6600
6601/*
6602** Close a file that uses proxy locks.
6603*/
6604static int proxyClose(sqlite3_file *id) {
6605 if( id ){
6606 unixFile *pFile = (unixFile*)id;
6607 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6608 unixFile *lockProxy = pCtx->lockProxy;
6609 unixFile *conchFile = pCtx->conchFile;
6610 int rc = SQLITE_OK;
6611
6612 if( lockProxy ){
6613 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6614 if( rc ) return rc;
6615 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6616 if( rc ) return rc;
6617 sqlite3_free(lockProxy);
6618 pCtx->lockProxy = 0;
6619 }
6620 if( conchFile ){
6621 if( pCtx->conchHeld ){
6622 rc = proxyReleaseConch(pFile);
6623 if( rc ) return rc;
6624 }
6625 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6626 if( rc ) return rc;
6627 sqlite3_free(conchFile);
6628 }
drhd56b1212010-08-11 06:14:15 +00006629 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006630 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006631 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006632 /* restore the original locking context and pMethod then close it */
6633 pFile->lockingContext = pCtx->oldLockingContext;
6634 pFile->pMethod = pCtx->pOldMethod;
6635 sqlite3_free(pCtx);
6636 return pFile->pMethod->xClose(id);
6637 }
6638 return SQLITE_OK;
6639}
6640
6641
6642
drhd2cb50b2009-01-09 21:41:17 +00006643#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006644/*
6645** The proxy locking style is intended for use with AFP filesystems.
6646** And since AFP is only supported on MacOSX, the proxy locking is also
6647** restricted to MacOSX.
6648**
6649**
6650******************* End of the proxy lock implementation **********************
6651******************************************************************************/
6652
drh734c9862008-11-28 15:37:20 +00006653/*
danielk1977e339d652008-06-28 11:23:00 +00006654** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006655**
6656** This routine registers all VFS implementations for unix-like operating
6657** systems. This routine, and the sqlite3_os_end() routine that follows,
6658** should be the only routines in this file that are visible from other
6659** files.
drh6b9d6dd2008-12-03 19:34:47 +00006660**
6661** This routine is called once during SQLite initialization and by a
6662** single thread. The memory allocation and mutex subsystems have not
6663** necessarily been initialized when this routine is called, and so they
6664** should not be used.
drh153c62c2007-08-24 03:51:33 +00006665*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006666int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006667 /*
6668 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006669 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6670 ** to the "finder" function. (pAppData is a pointer to a pointer because
6671 ** silly C90 rules prohibit a void* from being cast to a function pointer
6672 ** and so we have to go through the intermediate pointer to avoid problems
6673 ** when compiling with -pedantic-errors on GCC.)
6674 **
6675 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006676 ** finder-function. The finder-function returns a pointer to the
6677 ** sqlite_io_methods object that implements the desired locking
6678 ** behaviors. See the division above that contains the IOMETHODS
6679 ** macro for addition information on finder-functions.
6680 **
6681 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6682 ** object. But the "autolockIoFinder" available on MacOSX does a little
6683 ** more than that; it looks at the filesystem type that hosts the
6684 ** database file and tries to choose an locking method appropriate for
6685 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006686 */
drh7708e972008-11-29 00:56:52 +00006687 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006688 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006689 sizeof(unixFile), /* szOsFile */ \
6690 MAX_PATHNAME, /* mxPathname */ \
6691 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006692 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006693 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006694 unixOpen, /* xOpen */ \
6695 unixDelete, /* xDelete */ \
6696 unixAccess, /* xAccess */ \
6697 unixFullPathname, /* xFullPathname */ \
6698 unixDlOpen, /* xDlOpen */ \
6699 unixDlError, /* xDlError */ \
6700 unixDlSym, /* xDlSym */ \
6701 unixDlClose, /* xDlClose */ \
6702 unixRandomness, /* xRandomness */ \
6703 unixSleep, /* xSleep */ \
6704 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006705 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006706 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006707 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006708 unixGetSystemCall, /* xGetSystemCall */ \
6709 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006710 }
6711
drh6b9d6dd2008-12-03 19:34:47 +00006712 /*
6713 ** All default VFSes for unix are contained in the following array.
6714 **
6715 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6716 ** by the SQLite core when the VFS is registered. So the following
6717 ** array cannot be const.
6718 */
danielk1977e339d652008-06-28 11:23:00 +00006719 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006720#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006721 UNIXVFS("unix", autolockIoFinder ),
6722#else
6723 UNIXVFS("unix", posixIoFinder ),
6724#endif
6725 UNIXVFS("unix-none", nolockIoFinder ),
6726 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006727 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006728#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006729 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006730#endif
6731#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006732 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006733#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006734 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006735#endif
chw78a13182009-04-07 05:35:03 +00006736#endif
drhd2cb50b2009-01-09 21:41:17 +00006737#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006738 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006739 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006740 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006741#endif
drh153c62c2007-08-24 03:51:33 +00006742 };
drh6b9d6dd2008-12-03 19:34:47 +00006743 unsigned int i; /* Loop counter */
6744
drh2aa5a002011-04-13 13:42:25 +00006745 /* Double-check that the aSyscall[] array has been constructed
6746 ** correctly. See ticket [bb3a86e890c8e96ab] */
6747 assert( ArraySize(aSyscall)==16 );
6748
drh6b9d6dd2008-12-03 19:34:47 +00006749 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006750 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006751 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006752 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006753 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006754}
danielk1977e339d652008-06-28 11:23:00 +00006755
6756/*
drh6b9d6dd2008-12-03 19:34:47 +00006757** Shutdown the operating system interface.
6758**
6759** Some operating systems might need to do some cleanup in this routine,
6760** to release dynamically allocated objects. But not on unix.
6761** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006762*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006763int sqlite3_os_end(void){
6764 return SQLITE_OK;
6765}
drhdce8bdb2007-08-16 13:01:44 +00006766
danielk197729bafea2008-06-26 10:41:19 +00006767#endif /* SQLITE_OS_UNIX */