blob: 2f068dc58a49c79cf314794b530d8e9b4ee690a7 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drhdbe4b882011-06-20 18:00:17 +0000141#ifdef HAVE_UTIME
142# include <utime.h>
143#endif
144
drh9cbe6352005-11-29 03:13:21 +0000145/*
drh7ed97b92010-01-20 13:07:21 +0000146** Allowed values of unixFile.fsFlags
147*/
148#define SQLITE_FSFLAGS_IS_MSDOS 0x1
149
150/*
drhf1a221e2006-01-15 17:27:17 +0000151** If we are to be thread-safe, include the pthreads header and define
152** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000153*/
drhd677b3d2007-08-20 22:48:41 +0000154#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000155# include <pthread.h>
156# define SQLITE_UNIX_THREADS 1
157#endif
158
159/*
160** Default permissions when creating a new file
161*/
162#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
163# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
164#endif
165
danielk1977b4b47412007-08-17 15:53:36 +0000166/*
aswiftaebf4132008-11-21 00:10:35 +0000167 ** Default permissions when creating auto proxy dir
168 */
169#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
170# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
171#endif
172
173/*
danielk1977b4b47412007-08-17 15:53:36 +0000174** Maximum supported path-length.
175*/
176#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000177
drh734c9862008-11-28 15:37:20 +0000178/*
drh734c9862008-11-28 15:37:20 +0000179** Only set the lastErrno if the error code is a real error and not
180** a normal expected return code of SQLITE_BUSY or SQLITE_OK
181*/
182#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
183
drhd91c68f2010-05-14 14:52:25 +0000184/* Forward references */
185typedef struct unixShm unixShm; /* Connection shared memory */
186typedef struct unixShmNode unixShmNode; /* Shared memory instance */
187typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
188typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000189
190/*
dane946c392009-08-22 11:39:46 +0000191** Sometimes, after a file handle is closed by SQLite, the file descriptor
192** cannot be closed immediately. In these cases, instances of the following
193** structure are used to store the file descriptor while waiting for an
194** opportunity to either close or reuse it.
195*/
dane946c392009-08-22 11:39:46 +0000196struct UnixUnusedFd {
197 int fd; /* File descriptor to close */
198 int flags; /* Flags this file descriptor was opened with */
199 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
200};
201
202/*
drh9b35ea62008-11-29 02:20:26 +0000203** The unixFile structure is subclass of sqlite3_file specific to the unix
204** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000205*/
drh054889e2005-11-30 03:20:31 +0000206typedef struct unixFile unixFile;
207struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000208 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000209 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000210 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000211 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000212 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000213 int lastErrno; /* The unix errno from last I/O error */
214 void *lockingContext; /* Locking style specific state */
215 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000216 const char *zPath; /* Name of the file */
217 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000218 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000219#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000220 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000221#endif
drh7ed97b92010-01-20 13:07:21 +0000222#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000223 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000224#endif
225#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000226 int isDelete; /* Delete on close if true */
227 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000228#endif
drh8f941bc2009-01-14 23:03:40 +0000229#ifndef NDEBUG
230 /* The next group of variables are used to track whether or not the
231 ** transaction counter in bytes 24-27 of database files are updated
232 ** whenever any part of the database changes. An assertion fault will
233 ** occur if a file is updated without also updating the transaction
234 ** counter. This test is made to avoid new problems similar to the
235 ** one described by ticket #3584.
236 */
237 unsigned char transCntrChng; /* True if the transaction counter changed */
238 unsigned char dbUpdate; /* True if any part of database file changed */
239 unsigned char inNormalWrite; /* True if in a normal write operation */
240#endif
danielk1977967a4a12007-08-20 14:23:44 +0000241#ifdef SQLITE_TEST
242 /* In test mode, increase the size of this structure a bit so that
243 ** it is larger than the struct CrashFile defined in test6.c.
244 */
245 char aPadding[32];
246#endif
drh9cbe6352005-11-29 03:13:21 +0000247};
248
drh0ccebe72005-06-07 22:22:50 +0000249/*
drha7e61d82011-03-12 17:02:57 +0000250** Allowed values for the unixFile.ctrlFlags bitmask:
251*/
drhf0b190d2011-07-26 16:03:07 +0000252#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
253#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
254#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
drh0059eae2011-08-08 23:48:40 +0000255#define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
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
drh90315a22011-08-10 01:52:12 +0000301/* Forward reference */
302static int openDirectory(const char*, int*);
303
drh9a3baf12011-04-25 18:01:27 +0000304/*
drh99ab3b12011-03-02 15:09:07 +0000305** Many system calls are accessed through pointer-to-functions so that
306** they may be overridden at runtime to facilitate fault injection during
307** testing and sandboxing. The following array holds the names and pointers
308** to all overrideable system calls.
309*/
310static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000311 const char *zName; /* Name of the sytem call */
312 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
313 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000314} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000315 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
316#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000317
drh58ad5802011-03-23 22:02:23 +0000318 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000319#define osClose ((int(*)(int))aSyscall[1].pCurrent)
320
drh58ad5802011-03-23 22:02:23 +0000321 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000322#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
323
drh58ad5802011-03-23 22:02:23 +0000324 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000325#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
326
drh58ad5802011-03-23 22:02:23 +0000327 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000328#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
329
330/*
331** The DJGPP compiler environment looks mostly like Unix, but it
332** lacks the fcntl() system call. So redefine fcntl() to be something
333** that always succeeds. This means that locking does not occur under
334** DJGPP. But it is DOS - what did you expect?
335*/
336#ifdef __DJGPP__
337 { "fstat", 0, 0 },
338#define osFstat(a,b,c) 0
339#else
drh58ad5802011-03-23 22:02:23 +0000340 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000341#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
342#endif
343
drh58ad5802011-03-23 22:02:23 +0000344 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
346
drh58ad5802011-03-23 22:02:23 +0000347 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000349
drh58ad5802011-03-23 22:02:23 +0000350 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000351#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
352
drhd4a80312011-04-15 14:33:20 +0000353#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000354 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000355#else
drh58ad5802011-03-23 22:02:23 +0000356 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000357#endif
358#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
359
360#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000361 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000362#else
drh58ad5802011-03-23 22:02:23 +0000363 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000364#endif
365#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
366
drh58ad5802011-03-23 22:02:23 +0000367 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000368#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
369
drhd4a80312011-04-15 14:33:20 +0000370#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000371 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000372#else
drh58ad5802011-03-23 22:02:23 +0000373 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000374#endif
375#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
376 aSyscall[12].pCurrent)
377
378#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000379 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000380#else
drh58ad5802011-03-23 22:02:23 +0000381 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000382#endif
383#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
384 aSyscall[13].pCurrent)
385
drha6c47492011-04-11 18:35:09 +0000386#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000387 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000388#else
389 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000390#endif
drh2aa5a002011-04-13 13:42:25 +0000391#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000392
393#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000394 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000395#else
drh58ad5802011-03-23 22:02:23 +0000396 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000397#endif
dan0fd7d862011-03-29 10:04:23 +0000398#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000399
drh036ac7f2011-08-08 23:18:05 +0000400 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
401#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
402
drh90315a22011-08-10 01:52:12 +0000403 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
404#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
405
drhe562be52011-03-02 18:01:10 +0000406}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000407
408/*
409** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000410** "unix" VFSes. Return SQLITE_OK opon successfully updating the
411** system call pointer, or SQLITE_NOTFOUND if there is no configurable
412** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000413*/
414static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000415 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
416 const char *zName, /* Name of system call to override */
417 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000418){
drh58ad5802011-03-23 22:02:23 +0000419 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000420 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000421
422 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000423 if( zName==0 ){
424 /* If no zName is given, restore all system calls to their default
425 ** settings and return NULL
426 */
dan51438a72011-04-02 17:00:47 +0000427 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000428 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
429 if( aSyscall[i].pDefault ){
430 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000431 }
432 }
433 }else{
434 /* If zName is specified, operate on only the one system call
435 ** specified.
436 */
437 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
438 if( strcmp(zName, aSyscall[i].zName)==0 ){
439 if( aSyscall[i].pDefault==0 ){
440 aSyscall[i].pDefault = aSyscall[i].pCurrent;
441 }
drh1df30962011-03-02 19:06:42 +0000442 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000443 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
444 aSyscall[i].pCurrent = pNewFunc;
445 break;
446 }
447 }
448 }
449 return rc;
450}
451
drh1df30962011-03-02 19:06:42 +0000452/*
453** Return the value of a system call. Return NULL if zName is not a
454** recognized system call name. NULL is also returned if the system call
455** is currently undefined.
456*/
drh58ad5802011-03-23 22:02:23 +0000457static sqlite3_syscall_ptr unixGetSystemCall(
458 sqlite3_vfs *pNotUsed,
459 const char *zName
460){
461 unsigned int i;
462
463 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000464 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
465 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
466 }
467 return 0;
468}
469
470/*
471** Return the name of the first system call after zName. If zName==NULL
472** then return the name of the first system call. Return NULL if zName
473** is the last system call or if zName is not the name of a valid
474** system call.
475*/
476static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000477 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000478
479 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000480 if( zName ){
481 for(i=0; i<ArraySize(aSyscall)-1; i++){
482 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000483 }
484 }
dan0fd7d862011-03-29 10:04:23 +0000485 for(i++; i<ArraySize(aSyscall); i++){
486 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000487 }
488 return 0;
489}
490
drhad4f1e52011-03-04 15:43:57 +0000491/*
492** Retry open() calls that fail due to EINTR
493*/
494static int robust_open(const char *z, int f, int m){
495 int rc;
496 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
497 return rc;
498}
danielk197713adf8a2004-06-03 16:08:41 +0000499
drh107886a2008-11-21 22:21:50 +0000500/*
dan9359c7b2009-08-21 08:29:10 +0000501** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000502** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000503** vxworksFileId objects used by this file, all of which may be
504** shared by multiple threads.
505**
506** Function unixMutexHeld() is used to assert() that the global mutex
507** is held when required. This function is only used as part of assert()
508** statements. e.g.
509**
510** unixEnterMutex()
511** assert( unixMutexHeld() );
512** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000513*/
514static void unixEnterMutex(void){
515 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
516}
517static void unixLeaveMutex(void){
518 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
519}
dan9359c7b2009-08-21 08:29:10 +0000520#ifdef SQLITE_DEBUG
521static int unixMutexHeld(void) {
522 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
523}
524#endif
drh107886a2008-11-21 22:21:50 +0000525
drh734c9862008-11-28 15:37:20 +0000526
527#ifdef SQLITE_DEBUG
528/*
529** Helper function for printing out trace information from debugging
530** binaries. This returns the string represetation of the supplied
531** integer lock-type.
532*/
drh308c2a52010-05-14 11:30:18 +0000533static const char *azFileLock(int eFileLock){
534 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000535 case NO_LOCK: return "NONE";
536 case SHARED_LOCK: return "SHARED";
537 case RESERVED_LOCK: return "RESERVED";
538 case PENDING_LOCK: return "PENDING";
539 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000540 }
541 return "ERROR";
542}
543#endif
544
545#ifdef SQLITE_LOCK_TRACE
546/*
547** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000548**
drh734c9862008-11-28 15:37:20 +0000549** This routine is used for troubleshooting locks on multithreaded
550** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
551** command-line option on the compiler. This code is normally
552** turned off.
553*/
554static int lockTrace(int fd, int op, struct flock *p){
555 char *zOpName, *zType;
556 int s;
557 int savedErrno;
558 if( op==F_GETLK ){
559 zOpName = "GETLK";
560 }else if( op==F_SETLK ){
561 zOpName = "SETLK";
562 }else{
drh99ab3b12011-03-02 15:09:07 +0000563 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000564 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
565 return s;
566 }
567 if( p->l_type==F_RDLCK ){
568 zType = "RDLCK";
569 }else if( p->l_type==F_WRLCK ){
570 zType = "WRLCK";
571 }else if( p->l_type==F_UNLCK ){
572 zType = "UNLCK";
573 }else{
574 assert( 0 );
575 }
576 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000577 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000578 savedErrno = errno;
579 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
580 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
581 (int)p->l_pid, s);
582 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
583 struct flock l2;
584 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000585 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000586 if( l2.l_type==F_RDLCK ){
587 zType = "RDLCK";
588 }else if( l2.l_type==F_WRLCK ){
589 zType = "WRLCK";
590 }else if( l2.l_type==F_UNLCK ){
591 zType = "UNLCK";
592 }else{
593 assert( 0 );
594 }
595 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
596 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
597 }
598 errno = savedErrno;
599 return s;
600}
drh99ab3b12011-03-02 15:09:07 +0000601#undef osFcntl
602#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000603#endif /* SQLITE_LOCK_TRACE */
604
drhff812312011-02-23 13:33:46 +0000605/*
606** Retry ftruncate() calls that fail due to EINTR
607*/
drhff812312011-02-23 13:33:46 +0000608static int robust_ftruncate(int h, sqlite3_int64 sz){
609 int rc;
drh99ab3b12011-03-02 15:09:07 +0000610 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000611 return rc;
612}
drh734c9862008-11-28 15:37:20 +0000613
614/*
615** This routine translates a standard POSIX errno code into something
616** useful to the clients of the sqlite3 functions. Specifically, it is
617** intended to translate a variety of "try again" errors into SQLITE_BUSY
618** and a variety of "please close the file descriptor NOW" errors into
619** SQLITE_IOERR
620**
621** Errors during initialization of locks, or file system support for locks,
622** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
623*/
624static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
625 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000626#if 0
627 /* At one point this code was not commented out. In theory, this branch
628 ** should never be hit, as this function should only be called after
629 ** a locking-related function (i.e. fcntl()) has returned non-zero with
630 ** the value of errno as the first argument. Since a system call has failed,
631 ** errno should be non-zero.
632 **
633 ** Despite this, if errno really is zero, we still don't want to return
634 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
635 ** propagated back to the caller. Commenting this branch out means errno==0
636 ** will be handled by the "default:" case below.
637 */
drh734c9862008-11-28 15:37:20 +0000638 case 0:
639 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000640#endif
641
drh734c9862008-11-28 15:37:20 +0000642 case EAGAIN:
643 case ETIMEDOUT:
644 case EBUSY:
645 case EINTR:
646 case ENOLCK:
647 /* random NFS retry error, unless during file system support
648 * introspection, in which it actually means what it says */
649 return SQLITE_BUSY;
650
651 case EACCES:
652 /* EACCES is like EAGAIN during locking operations, but not any other time*/
653 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
654 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
655 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
656 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
657 return SQLITE_BUSY;
658 }
659 /* else fall through */
660 case EPERM:
661 return SQLITE_PERM;
662
danea83bc62011-04-01 11:56:32 +0000663 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
664 ** this module never makes such a call. And the code in SQLite itself
665 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
666 ** this case is also commented out. If the system does set errno to EDEADLK,
667 ** the default SQLITE_IOERR_XXX code will be returned. */
668#if 0
drh734c9862008-11-28 15:37:20 +0000669 case EDEADLK:
670 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000671#endif
drh734c9862008-11-28 15:37:20 +0000672
673#if EOPNOTSUPP!=ENOTSUP
674 case EOPNOTSUPP:
675 /* something went terribly awry, unless during file system support
676 * introspection, in which it actually means what it says */
677#endif
678#ifdef ENOTSUP
679 case ENOTSUP:
680 /* invalid fd, unless during file system support introspection, in which
681 * it actually means what it says */
682#endif
683 case EIO:
684 case EBADF:
685 case EINVAL:
686 case ENOTCONN:
687 case ENODEV:
688 case ENXIO:
689 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000690#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000691 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000692#endif
drh734c9862008-11-28 15:37:20 +0000693 case ENOSYS:
694 /* these should force the client to close the file and reconnect */
695
696 default:
697 return sqliteIOErr;
698 }
699}
700
701
702
703/******************************************************************************
704****************** Begin Unique File ID Utility Used By VxWorks ***************
705**
706** On most versions of unix, we can get a unique ID for a file by concatenating
707** the device number and the inode number. But this does not work on VxWorks.
708** On VxWorks, a unique file id must be based on the canonical filename.
709**
710** A pointer to an instance of the following structure can be used as a
711** unique file ID in VxWorks. Each instance of this structure contains
712** a copy of the canonical filename. There is also a reference count.
713** The structure is reclaimed when the number of pointers to it drops to
714** zero.
715**
716** There are never very many files open at one time and lookups are not
717** a performance-critical path, so it is sufficient to put these
718** structures on a linked list.
719*/
720struct vxworksFileId {
721 struct vxworksFileId *pNext; /* Next in a list of them all */
722 int nRef; /* Number of references to this one */
723 int nName; /* Length of the zCanonicalName[] string */
724 char *zCanonicalName; /* Canonical filename */
725};
726
727#if OS_VXWORKS
728/*
drh9b35ea62008-11-29 02:20:26 +0000729** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000730** variable:
731*/
732static struct vxworksFileId *vxworksFileList = 0;
733
734/*
735** Simplify a filename into its canonical form
736** by making the following changes:
737**
738** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000739** * convert /./ into just /
740** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000741**
742** Changes are made in-place. Return the new name length.
743**
744** The original filename is in z[0..n-1]. Return the number of
745** characters in the simplified name.
746*/
747static int vxworksSimplifyName(char *z, int n){
748 int i, j;
749 while( n>1 && z[n-1]=='/' ){ n--; }
750 for(i=j=0; i<n; i++){
751 if( z[i]=='/' ){
752 if( z[i+1]=='/' ) continue;
753 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
754 i += 1;
755 continue;
756 }
757 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
758 while( j>0 && z[j-1]!='/' ){ j--; }
759 if( j>0 ){ j--; }
760 i += 2;
761 continue;
762 }
763 }
764 z[j++] = z[i];
765 }
766 z[j] = 0;
767 return j;
768}
769
770/*
771** Find a unique file ID for the given absolute pathname. Return
772** a pointer to the vxworksFileId object. This pointer is the unique
773** file ID.
774**
775** The nRef field of the vxworksFileId object is incremented before
776** the object is returned. A new vxworksFileId object is created
777** and added to the global list if necessary.
778**
779** If a memory allocation error occurs, return NULL.
780*/
781static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
782 struct vxworksFileId *pNew; /* search key and new file ID */
783 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
784 int n; /* Length of zAbsoluteName string */
785
786 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000787 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000788 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
789 if( pNew==0 ) return 0;
790 pNew->zCanonicalName = (char*)&pNew[1];
791 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
792 n = vxworksSimplifyName(pNew->zCanonicalName, n);
793
794 /* Search for an existing entry that matching the canonical name.
795 ** If found, increment the reference count and return a pointer to
796 ** the existing file ID.
797 */
798 unixEnterMutex();
799 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
800 if( pCandidate->nName==n
801 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
802 ){
803 sqlite3_free(pNew);
804 pCandidate->nRef++;
805 unixLeaveMutex();
806 return pCandidate;
807 }
808 }
809
810 /* No match was found. We will make a new file ID */
811 pNew->nRef = 1;
812 pNew->nName = n;
813 pNew->pNext = vxworksFileList;
814 vxworksFileList = pNew;
815 unixLeaveMutex();
816 return pNew;
817}
818
819/*
820** Decrement the reference count on a vxworksFileId object. Free
821** the object when the reference count reaches zero.
822*/
823static void vxworksReleaseFileId(struct vxworksFileId *pId){
824 unixEnterMutex();
825 assert( pId->nRef>0 );
826 pId->nRef--;
827 if( pId->nRef==0 ){
828 struct vxworksFileId **pp;
829 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
830 assert( *pp==pId );
831 *pp = pId->pNext;
832 sqlite3_free(pId);
833 }
834 unixLeaveMutex();
835}
836#endif /* OS_VXWORKS */
837/*************** End of Unique File ID Utility Used By VxWorks ****************
838******************************************************************************/
839
840
841/******************************************************************************
842*************************** Posix Advisory Locking ****************************
843**
drh9b35ea62008-11-29 02:20:26 +0000844** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000845** section 6.5.2.2 lines 483 through 490 specify that when a process
846** sets or clears a lock, that operation overrides any prior locks set
847** by the same process. It does not explicitly say so, but this implies
848** that it overrides locks set by the same process using a different
849** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000850**
851** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000852** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
853**
854** Suppose ./file1 and ./file2 are really the same file (because
855** one is a hard or symbolic link to the other) then if you set
856** an exclusive lock on fd1, then try to get an exclusive lock
857** on fd2, it works. I would have expected the second lock to
858** fail since there was already a lock on the file due to fd1.
859** But not so. Since both locks came from the same process, the
860** second overrides the first, even though they were on different
861** file descriptors opened on different file names.
862**
drh734c9862008-11-28 15:37:20 +0000863** This means that we cannot use POSIX locks to synchronize file access
864** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000865** to synchronize access for threads in separate processes, but not
866** threads within the same process.
867**
868** To work around the problem, SQLite has to manage file locks internally
869** on its own. Whenever a new database is opened, we have to find the
870** specific inode of the database file (the inode is determined by the
871** st_dev and st_ino fields of the stat structure that fstat() fills in)
872** and check for locks already existing on that inode. When locks are
873** created or removed, we have to look at our own internal record of the
874** locks to see if another thread has previously set a lock on that same
875** inode.
876**
drh9b35ea62008-11-29 02:20:26 +0000877** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
878** For VxWorks, we have to use the alternative unique ID system based on
879** canonical filename and implemented in the previous division.)
880**
danielk1977ad94b582007-08-20 06:44:22 +0000881** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000882** descriptor. It is now a structure that holds the integer file
883** descriptor and a pointer to a structure that describes the internal
884** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000885** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000886** point to the same locking structure. The locking structure keeps
887** a reference count (so we will know when to delete it) and a "cnt"
888** field that tells us its internal lock status. cnt==0 means the
889** file is unlocked. cnt==-1 means the file has an exclusive lock.
890** cnt>0 means there are cnt shared locks on the file.
891**
892** Any attempt to lock or unlock a file first checks the locking
893** structure. The fcntl() system call is only invoked to set a
894** POSIX lock if the internal lock structure transitions between
895** a locked and an unlocked state.
896**
drh734c9862008-11-28 15:37:20 +0000897** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000898**
899** If you close a file descriptor that points to a file that has locks,
900** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000901** released. To work around this problem, each unixInodeInfo object
902** maintains a count of the number of pending locks on tha inode.
903** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000904** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000905** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000906** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000907** be closed and that list is walked (and cleared) when the last lock
908** clears.
909**
drh9b35ea62008-11-29 02:20:26 +0000910** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000911**
drh9b35ea62008-11-29 02:20:26 +0000912** Many older versions of linux use the LinuxThreads library which is
913** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000914** A cannot be modified or overridden by a different thread B.
915** Only thread A can modify the lock. Locking behavior is correct
916** if the appliation uses the newer Native Posix Thread Library (NPTL)
917** on linux - with NPTL a lock created by thread A can override locks
918** in thread B. But there is no way to know at compile-time which
919** threading library is being used. So there is no way to know at
920** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000921** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000922** current process.
drh5fdae772004-06-29 03:29:00 +0000923**
drh8af6c222010-05-14 12:43:01 +0000924** SQLite used to support LinuxThreads. But support for LinuxThreads
925** was dropped beginning with version 3.7.0. SQLite will still work with
926** LinuxThreads provided that (1) there is no more than one connection
927** per database file in the same process and (2) database connections
928** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000929*/
930
931/*
932** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000933** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000934*/
935struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000936 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000937#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000938 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000939#else
drh107886a2008-11-21 22:21:50 +0000940 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000941#endif
942};
943
944/*
drhbbd42a62004-05-22 17:41:58 +0000945** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000946** inode. Or, on LinuxThreads, there is one of these structures for
947** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000948**
danielk1977ad94b582007-08-20 06:44:22 +0000949** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000950** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000951** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000952*/
drh8af6c222010-05-14 12:43:01 +0000953struct unixInodeInfo {
954 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000955 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000956 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
957 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000958 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000959 unixShmNode *pShmNode; /* Shared memory associated with this inode */
960 int nLock; /* Number of outstanding file locks */
961 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
962 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
963 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000964#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000965 unsigned long long sharedByte; /* for AFP simulated shared lock */
966#endif
drh6c7d5c52008-11-21 20:32:33 +0000967#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000968 sem_t *pSem; /* Named POSIX semaphore */
969 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000970#endif
drhbbd42a62004-05-22 17:41:58 +0000971};
972
drhda0e7682008-07-30 15:27:54 +0000973/*
drh8af6c222010-05-14 12:43:01 +0000974** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000975*/
drhd91c68f2010-05-14 14:52:25 +0000976static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000977
drh5fdae772004-06-29 03:29:00 +0000978/*
dane18d4952011-02-21 11:46:24 +0000979**
980** This function - unixLogError_x(), is only ever called via the macro
981** unixLogError().
982**
983** It is invoked after an error occurs in an OS function and errno has been
984** set. It logs a message using sqlite3_log() containing the current value of
985** errno and, if possible, the human-readable equivalent from strerror() or
986** strerror_r().
987**
988** The first argument passed to the macro should be the error code that
989** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
990** The two subsequent arguments should be the name of the OS function that
991** failed (e.g. "unlink", "open") and the the associated file-system path,
992** if any.
993*/
drh0e9365c2011-03-02 02:08:13 +0000994#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
995static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000996 int errcode, /* SQLite error code */
997 const char *zFunc, /* Name of OS function that failed */
998 const char *zPath, /* File path associated with error */
999 int iLine /* Source line number where error occurred */
1000){
1001 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001002 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001003
1004 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1005 ** the strerror() function to obtain the human-readable error message
1006 ** equivalent to errno. Otherwise, use strerror_r().
1007 */
1008#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1009 char aErr[80];
1010 memset(aErr, 0, sizeof(aErr));
1011 zErr = aErr;
1012
1013 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1014 ** assume that the system provides the the GNU version of strerror_r() that
1015 ** returns a pointer to a buffer containing the error message. That pointer
1016 ** may point to aErr[], or it may point to some static storage somewhere.
1017 ** Otherwise, assume that the system provides the POSIX version of
1018 ** strerror_r(), which always writes an error message into aErr[].
1019 **
1020 ** If the code incorrectly assumes that it is the POSIX version that is
1021 ** available, the error message will often be an empty string. Not a
1022 ** huge problem. Incorrectly concluding that the GNU version is available
1023 ** could lead to a segfault though.
1024 */
1025#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1026 zErr =
1027# endif
drh0e9365c2011-03-02 02:08:13 +00001028 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001029
1030#elif SQLITE_THREADSAFE
1031 /* This is a threadsafe build, but strerror_r() is not available. */
1032 zErr = "";
1033#else
1034 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001035 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001036#endif
1037
1038 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001039 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001040 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001041 "os_unix.c:%d: (%d) %s(%s) - %s",
1042 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001043 );
1044
1045 return errcode;
1046}
1047
drh0e9365c2011-03-02 02:08:13 +00001048/*
1049** Close a file descriptor.
1050**
1051** We assume that close() almost always works, since it is only in a
1052** very sick application or on a very sick platform that it might fail.
1053** If it does fail, simply leak the file descriptor, but do log the
1054** error.
1055**
1056** Note that it is not safe to retry close() after EINTR since the
1057** file descriptor might have already been reused by another thread.
1058** So we don't even try to recover from an EINTR. Just log the error
1059** and move on.
1060*/
1061static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001062 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001063 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1064 pFile ? pFile->zPath : 0, lineno);
1065 }
1066}
dane18d4952011-02-21 11:46:24 +00001067
1068/*
danb0ac3e32010-06-16 10:55:42 +00001069** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001070*/
drh0e9365c2011-03-02 02:08:13 +00001071static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001072 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001073 UnixUnusedFd *p;
1074 UnixUnusedFd *pNext;
1075 for(p=pInode->pUnused; p; p=pNext){
1076 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001077 robust_close(pFile, p->fd, __LINE__);
1078 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001079 }
drh0e9365c2011-03-02 02:08:13 +00001080 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001081}
1082
1083/*
drh8af6c222010-05-14 12:43:01 +00001084** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001085**
1086** The mutex entered using the unixEnterMutex() function must be held
1087** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001088*/
danb0ac3e32010-06-16 10:55:42 +00001089static void releaseInodeInfo(unixFile *pFile){
1090 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001091 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001092 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001093 pInode->nRef--;
1094 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001095 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001096 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001097 if( pInode->pPrev ){
1098 assert( pInode->pPrev->pNext==pInode );
1099 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001100 }else{
drh8af6c222010-05-14 12:43:01 +00001101 assert( inodeList==pInode );
1102 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001103 }
drh8af6c222010-05-14 12:43:01 +00001104 if( pInode->pNext ){
1105 assert( pInode->pNext->pPrev==pInode );
1106 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001107 }
drh8af6c222010-05-14 12:43:01 +00001108 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001109 }
drhbbd42a62004-05-22 17:41:58 +00001110 }
1111}
1112
1113/*
drh8af6c222010-05-14 12:43:01 +00001114** Given a file descriptor, locate the unixInodeInfo object that
1115** describes that file descriptor. Create a new one if necessary. The
1116** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001117**
dan9359c7b2009-08-21 08:29:10 +00001118** The mutex entered using the unixEnterMutex() function must be held
1119** when this function is called.
1120**
drh6c7d5c52008-11-21 20:32:33 +00001121** Return an appropriate error code.
1122*/
drh8af6c222010-05-14 12:43:01 +00001123static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001124 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001125 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001126){
1127 int rc; /* System call return code */
1128 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001129 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1130 struct stat statbuf; /* Low-level file information */
1131 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001132
dan9359c7b2009-08-21 08:29:10 +00001133 assert( unixMutexHeld() );
1134
drh6c7d5c52008-11-21 20:32:33 +00001135 /* Get low-level information about the file that we can used to
1136 ** create a unique name for the file.
1137 */
1138 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001139 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001140 if( rc!=0 ){
1141 pFile->lastErrno = errno;
1142#ifdef EOVERFLOW
1143 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1144#endif
1145 return SQLITE_IOERR;
1146 }
1147
drheb0d74f2009-02-03 15:27:02 +00001148#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001149 /* On OS X on an msdos filesystem, the inode number is reported
1150 ** incorrectly for zero-size files. See ticket #3260. To work
1151 ** around this problem (we consider it a bug in OS X, not SQLite)
1152 ** we always increase the file size to 1 by writing a single byte
1153 ** prior to accessing the inode number. The one byte written is
1154 ** an ASCII 'S' character which also happens to be the first byte
1155 ** in the header of every SQLite database. In this way, if there
1156 ** is a race condition such that another thread has already populated
1157 ** the first page of the database, no damage is done.
1158 */
drh7ed97b92010-01-20 13:07:21 +00001159 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001160 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001161 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001162 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001163 return SQLITE_IOERR;
1164 }
drh99ab3b12011-03-02 15:09:07 +00001165 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001166 if( rc!=0 ){
1167 pFile->lastErrno = errno;
1168 return SQLITE_IOERR;
1169 }
1170 }
drheb0d74f2009-02-03 15:27:02 +00001171#endif
drh6c7d5c52008-11-21 20:32:33 +00001172
drh8af6c222010-05-14 12:43:01 +00001173 memset(&fileId, 0, sizeof(fileId));
1174 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001175#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001176 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001177#else
drh8af6c222010-05-14 12:43:01 +00001178 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001179#endif
drh8af6c222010-05-14 12:43:01 +00001180 pInode = inodeList;
1181 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1182 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001183 }
drh8af6c222010-05-14 12:43:01 +00001184 if( pInode==0 ){
1185 pInode = sqlite3_malloc( sizeof(*pInode) );
1186 if( pInode==0 ){
1187 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001188 }
drh8af6c222010-05-14 12:43:01 +00001189 memset(pInode, 0, sizeof(*pInode));
1190 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1191 pInode->nRef = 1;
1192 pInode->pNext = inodeList;
1193 pInode->pPrev = 0;
1194 if( inodeList ) inodeList->pPrev = pInode;
1195 inodeList = pInode;
1196 }else{
1197 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001198 }
drh8af6c222010-05-14 12:43:01 +00001199 *ppInode = pInode;
1200 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001201}
drh6c7d5c52008-11-21 20:32:33 +00001202
aswift5b1a2562008-08-22 00:22:35 +00001203
1204/*
danielk197713adf8a2004-06-03 16:08:41 +00001205** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001206** file by this or any other process. If such a lock is held, set *pResOut
1207** to a non-zero value otherwise *pResOut is set to zero. The return value
1208** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001209*/
danielk1977861f7452008-06-05 11:39:11 +00001210static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001211 int rc = SQLITE_OK;
1212 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001213 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001214
danielk1977861f7452008-06-05 11:39:11 +00001215 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1216
drh054889e2005-11-30 03:20:31 +00001217 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001218 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001219
1220 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001221 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001222 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001223 }
1224
drh2ac3ee92004-06-07 16:27:46 +00001225 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001226 */
danielk197709480a92009-02-09 05:32:32 +00001227#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001228 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001229 struct flock lock;
1230 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001231 lock.l_start = RESERVED_BYTE;
1232 lock.l_len = 1;
1233 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001234 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1235 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1236 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001237 } else if( lock.l_type!=F_UNLCK ){
1238 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001239 }
1240 }
danielk197709480a92009-02-09 05:32:32 +00001241#endif
danielk197713adf8a2004-06-03 16:08:41 +00001242
drh6c7d5c52008-11-21 20:32:33 +00001243 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001244 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001245
aswift5b1a2562008-08-22 00:22:35 +00001246 *pResOut = reserved;
1247 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001248}
1249
1250/*
drha7e61d82011-03-12 17:02:57 +00001251** Attempt to set a system-lock on the file pFile. The lock is
1252** described by pLock.
1253**
drh77197112011-03-15 19:08:48 +00001254** If the pFile was opened read/write from unix-excl, then the only lock
1255** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001256** the first time any lock is attempted. All subsequent system locking
1257** operations become no-ops. Locking operations still happen internally,
1258** in order to coordinate access between separate database connections
1259** within this process, but all of that is handled in memory and the
1260** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001261**
1262** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1263** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1264** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001265**
1266** Zero is returned if the call completes successfully, or -1 if a call
1267** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001268*/
1269static int unixFileLock(unixFile *pFile, struct flock *pLock){
1270 int rc;
drh3cb93392011-03-12 18:10:44 +00001271 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001272 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001273 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001274 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1275 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1276 ){
drh3cb93392011-03-12 18:10:44 +00001277 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001278 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001279 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001280 lock.l_whence = SEEK_SET;
1281 lock.l_start = SHARED_FIRST;
1282 lock.l_len = SHARED_SIZE;
1283 lock.l_type = F_WRLCK;
1284 rc = osFcntl(pFile->h, F_SETLK, &lock);
1285 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001286 pInode->bProcessLock = 1;
1287 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001288 }else{
1289 rc = 0;
1290 }
1291 }else{
1292 rc = osFcntl(pFile->h, F_SETLK, pLock);
1293 }
1294 return rc;
1295}
1296
1297/*
drh308c2a52010-05-14 11:30:18 +00001298** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001299** of the following:
1300**
drh2ac3ee92004-06-07 16:27:46 +00001301** (1) SHARED_LOCK
1302** (2) RESERVED_LOCK
1303** (3) PENDING_LOCK
1304** (4) EXCLUSIVE_LOCK
1305**
drhb3e04342004-06-08 00:47:47 +00001306** Sometimes when requesting one lock state, additional lock states
1307** are inserted in between. The locking might fail on one of the later
1308** transitions leaving the lock state different from what it started but
1309** still short of its goal. The following chart shows the allowed
1310** transitions and the inserted intermediate states:
1311**
1312** UNLOCKED -> SHARED
1313** SHARED -> RESERVED
1314** SHARED -> (PENDING) -> EXCLUSIVE
1315** RESERVED -> (PENDING) -> EXCLUSIVE
1316** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001317**
drha6abd042004-06-09 17:37:22 +00001318** This routine will only increase a lock. Use the sqlite3OsUnlock()
1319** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001320*/
drh308c2a52010-05-14 11:30:18 +00001321static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001322 /* The following describes the implementation of the various locks and
1323 ** lock transitions in terms of the POSIX advisory shared and exclusive
1324 ** lock primitives (called read-locks and write-locks below, to avoid
1325 ** confusion with SQLite lock names). The algorithms are complicated
1326 ** slightly in order to be compatible with windows systems simultaneously
1327 ** accessing the same database file, in case that is ever required.
1328 **
1329 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1330 ** byte', each single bytes at well known offsets, and the 'shared byte
1331 ** range', a range of 510 bytes at a well known offset.
1332 **
1333 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1334 ** byte'. If this is successful, a random byte from the 'shared byte
1335 ** range' is read-locked and the lock on the 'pending byte' released.
1336 **
danielk197790ba3bd2004-06-25 08:32:25 +00001337 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1338 ** A RESERVED lock is implemented by grabbing a write-lock on the
1339 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001340 **
1341 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001342 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1343 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1344 ** obtained, but existing SHARED locks are allowed to persist. A process
1345 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1346 ** This property is used by the algorithm for rolling back a journal file
1347 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001348 **
danielk197790ba3bd2004-06-25 08:32:25 +00001349 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1350 ** implemented by obtaining a write-lock on the entire 'shared byte
1351 ** range'. Since all other locks require a read-lock on one of the bytes
1352 ** within this range, this ensures that no other locks are held on the
1353 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001354 **
1355 ** The reason a single byte cannot be used instead of the 'shared byte
1356 ** range' is that some versions of windows do not support read-locks. By
1357 ** locking a random byte from a range, concurrent SHARED locks may exist
1358 ** even if the locking primitive used is always a write-lock.
1359 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001360 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001361 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001362 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001363 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001364 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001365
drh054889e2005-11-30 03:20:31 +00001366 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001367 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1368 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001369 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001370
1371 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001372 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001373 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001374 */
drh308c2a52010-05-14 11:30:18 +00001375 if( pFile->eFileLock>=eFileLock ){
1376 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1377 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001378 return SQLITE_OK;
1379 }
1380
drh0c2694b2009-09-03 16:23:44 +00001381 /* Make sure the locking sequence is correct.
1382 ** (1) We never move from unlocked to anything higher than shared lock.
1383 ** (2) SQLite never explicitly requests a pendig lock.
1384 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001385 */
drh308c2a52010-05-14 11:30:18 +00001386 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1387 assert( eFileLock!=PENDING_LOCK );
1388 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001389
drh8af6c222010-05-14 12:43:01 +00001390 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001391 */
drh6c7d5c52008-11-21 20:32:33 +00001392 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001393 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001394
danielk1977ad94b582007-08-20 06:44:22 +00001395 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001396 ** handle that precludes the requested lock, return BUSY.
1397 */
drh8af6c222010-05-14 12:43:01 +00001398 if( (pFile->eFileLock!=pInode->eFileLock &&
1399 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001400 ){
1401 rc = SQLITE_BUSY;
1402 goto end_lock;
1403 }
1404
1405 /* If a SHARED lock is requested, and some thread using this PID already
1406 ** has a SHARED or RESERVED lock, then increment reference counts and
1407 ** return SQLITE_OK.
1408 */
drh308c2a52010-05-14 11:30:18 +00001409 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001410 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001411 assert( eFileLock==SHARED_LOCK );
1412 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001413 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001414 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001415 pInode->nShared++;
1416 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001417 goto end_lock;
1418 }
1419
danielk19779a1d0ab2004-06-01 14:09:28 +00001420
drh3cde3bb2004-06-12 02:17:14 +00001421 /* A PENDING lock is needed before acquiring a SHARED lock and before
1422 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1423 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001424 */
drh0c2694b2009-09-03 16:23:44 +00001425 lock.l_len = 1L;
1426 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001427 if( eFileLock==SHARED_LOCK
1428 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001429 ){
drh308c2a52010-05-14 11:30:18 +00001430 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001431 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001432 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001433 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001434 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001435 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001436 pFile->lastErrno = tErrno;
1437 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001438 goto end_lock;
1439 }
drh3cde3bb2004-06-12 02:17:14 +00001440 }
1441
1442
1443 /* If control gets to this point, then actually go ahead and make
1444 ** operating system calls for the specified lock.
1445 */
drh308c2a52010-05-14 11:30:18 +00001446 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001447 assert( pInode->nShared==0 );
1448 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001449 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001450
drh2ac3ee92004-06-07 16:27:46 +00001451 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001452 lock.l_start = SHARED_FIRST;
1453 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001454 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001455 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001456 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001457 }
dan661d71a2011-03-30 19:08:03 +00001458
drh2ac3ee92004-06-07 16:27:46 +00001459 /* Drop the temporary PENDING lock */
1460 lock.l_start = PENDING_BYTE;
1461 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001462 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001463 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1464 /* This could happen with a network mount */
1465 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001466 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001467 }
dan661d71a2011-03-30 19:08:03 +00001468
1469 if( rc ){
1470 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001471 pFile->lastErrno = tErrno;
1472 }
dan661d71a2011-03-30 19:08:03 +00001473 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001474 }else{
drh308c2a52010-05-14 11:30:18 +00001475 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001476 pInode->nLock++;
1477 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001478 }
drh8af6c222010-05-14 12:43:01 +00001479 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001480 /* We are trying for an exclusive lock but another thread in this
1481 ** same process is still holding a shared lock. */
1482 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001483 }else{
drh3cde3bb2004-06-12 02:17:14 +00001484 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001485 ** assumed that there is a SHARED or greater lock on the file
1486 ** already.
1487 */
drh308c2a52010-05-14 11:30:18 +00001488 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001489 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001490
1491 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1492 if( eFileLock==RESERVED_LOCK ){
1493 lock.l_start = RESERVED_BYTE;
1494 lock.l_len = 1L;
1495 }else{
1496 lock.l_start = SHARED_FIRST;
1497 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001498 }
dan661d71a2011-03-30 19:08:03 +00001499
1500 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001501 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001502 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001503 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001504 pFile->lastErrno = tErrno;
1505 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001506 }
drhbbd42a62004-05-22 17:41:58 +00001507 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001508
drh8f941bc2009-01-14 23:03:40 +00001509
1510#ifndef NDEBUG
1511 /* Set up the transaction-counter change checking flags when
1512 ** transitioning from a SHARED to a RESERVED lock. The change
1513 ** from SHARED to RESERVED marks the beginning of a normal
1514 ** write operation (not a hot journal rollback).
1515 */
1516 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001517 && pFile->eFileLock<=SHARED_LOCK
1518 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001519 ){
1520 pFile->transCntrChng = 0;
1521 pFile->dbUpdate = 0;
1522 pFile->inNormalWrite = 1;
1523 }
1524#endif
1525
1526
danielk1977ecb2a962004-06-02 06:30:16 +00001527 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001528 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001529 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001530 }else if( eFileLock==EXCLUSIVE_LOCK ){
1531 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001532 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001533 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001534
1535end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001536 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001537 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1538 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001539 return rc;
1540}
1541
1542/*
dan08da86a2009-08-21 17:18:03 +00001543** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001544** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001545*/
1546static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001547 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001548 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001549 p->pNext = pInode->pUnused;
1550 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001551 pFile->h = -1;
1552 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001553}
1554
1555/*
drh308c2a52010-05-14 11:30:18 +00001556** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001557** must be either NO_LOCK or SHARED_LOCK.
1558**
1559** If the locking level of the file descriptor is already at or below
1560** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001561**
1562** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1563** the byte range is divided into 2 parts and the first part is unlocked then
1564** set to a read lock, then the other part is simply unlocked. This works
1565** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1566** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001567*/
drha7e61d82011-03-12 17:02:57 +00001568static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001569 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001570 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001571 struct flock lock;
1572 int rc = SQLITE_OK;
1573 int h;
drha6abd042004-06-09 17:37:22 +00001574
drh054889e2005-11-30 03:20:31 +00001575 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001576 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001577 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001578 getpid()));
drha6abd042004-06-09 17:37:22 +00001579
drh308c2a52010-05-14 11:30:18 +00001580 assert( eFileLock<=SHARED_LOCK );
1581 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001582 return SQLITE_OK;
1583 }
drh6c7d5c52008-11-21 20:32:33 +00001584 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001585 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001586 pInode = pFile->pInode;
1587 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001588 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001589 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001590 SimulateIOErrorBenign(1);
1591 SimulateIOError( h=(-1) )
1592 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001593
1594#ifndef NDEBUG
1595 /* When reducing a lock such that other processes can start
1596 ** reading the database file again, make sure that the
1597 ** transaction counter was updated if any part of the database
1598 ** file changed. If the transaction counter is not updated,
1599 ** other connections to the same file might not realize that
1600 ** the file has changed and hence might not know to flush their
1601 ** cache. The use of a stale cache can lead to database corruption.
1602 */
dan7c246102010-04-12 19:00:29 +00001603#if 0
drh8f941bc2009-01-14 23:03:40 +00001604 assert( pFile->inNormalWrite==0
1605 || pFile->dbUpdate==0
1606 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001607#endif
drh8f941bc2009-01-14 23:03:40 +00001608 pFile->inNormalWrite = 0;
1609#endif
1610
drh7ed97b92010-01-20 13:07:21 +00001611 /* downgrading to a shared lock on NFS involves clearing the write lock
1612 ** before establishing the readlock - to avoid a race condition we downgrade
1613 ** the lock in 2 blocks, so that part of the range will be covered by a
1614 ** write lock until the rest is covered by a read lock:
1615 ** 1: [WWWWW]
1616 ** 2: [....W]
1617 ** 3: [RRRRW]
1618 ** 4: [RRRR.]
1619 */
drh308c2a52010-05-14 11:30:18 +00001620 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001621
1622#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001623 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001624 assert( handleNFSUnlock==0 );
1625#endif
1626#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001627 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001628 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001629 off_t divSize = SHARED_SIZE - 1;
1630
1631 lock.l_type = F_UNLCK;
1632 lock.l_whence = SEEK_SET;
1633 lock.l_start = SHARED_FIRST;
1634 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001635 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001636 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001637 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001638 if( IS_LOCK_ERROR(rc) ){
1639 pFile->lastErrno = tErrno;
1640 }
1641 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001642 }
drh7ed97b92010-01-20 13:07:21 +00001643 lock.l_type = F_RDLCK;
1644 lock.l_whence = SEEK_SET;
1645 lock.l_start = SHARED_FIRST;
1646 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001647 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001648 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001649 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1650 if( IS_LOCK_ERROR(rc) ){
1651 pFile->lastErrno = tErrno;
1652 }
1653 goto end_unlock;
1654 }
1655 lock.l_type = F_UNLCK;
1656 lock.l_whence = SEEK_SET;
1657 lock.l_start = SHARED_FIRST+divSize;
1658 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001659 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001660 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001661 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001662 if( IS_LOCK_ERROR(rc) ){
1663 pFile->lastErrno = tErrno;
1664 }
1665 goto end_unlock;
1666 }
drh30f776f2011-02-25 03:25:07 +00001667 }else
1668#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1669 {
drh7ed97b92010-01-20 13:07:21 +00001670 lock.l_type = F_RDLCK;
1671 lock.l_whence = SEEK_SET;
1672 lock.l_start = SHARED_FIRST;
1673 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001674 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001675 /* In theory, the call to unixFileLock() cannot fail because another
1676 ** process is holding an incompatible lock. If it does, this
1677 ** indicates that the other process is not following the locking
1678 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1679 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1680 ** an assert to fail). */
1681 rc = SQLITE_IOERR_RDLOCK;
1682 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001683 goto end_unlock;
1684 }
drh9c105bb2004-10-02 20:38:28 +00001685 }
1686 }
drhbbd42a62004-05-22 17:41:58 +00001687 lock.l_type = F_UNLCK;
1688 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001689 lock.l_start = PENDING_BYTE;
1690 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001691 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001692 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001693 }else{
danea83bc62011-04-01 11:56:32 +00001694 rc = SQLITE_IOERR_UNLOCK;
1695 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001696 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001697 }
drhbbd42a62004-05-22 17:41:58 +00001698 }
drh308c2a52010-05-14 11:30:18 +00001699 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001700 /* Decrement the shared lock counter. Release the lock using an
1701 ** OS call only when all threads in this same process have released
1702 ** the lock.
1703 */
drh8af6c222010-05-14 12:43:01 +00001704 pInode->nShared--;
1705 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001706 lock.l_type = F_UNLCK;
1707 lock.l_whence = SEEK_SET;
1708 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001709 SimulateIOErrorBenign(1);
1710 SimulateIOError( h=(-1) )
1711 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001712 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001713 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001714 }else{
danea83bc62011-04-01 11:56:32 +00001715 rc = SQLITE_IOERR_UNLOCK;
1716 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001717 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001718 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001719 }
drha6abd042004-06-09 17:37:22 +00001720 }
1721
drhbbd42a62004-05-22 17:41:58 +00001722 /* Decrement the count of locks against this same file. When the
1723 ** count reaches zero, close any other file descriptors whose close
1724 ** was deferred because of outstanding locks.
1725 */
drh8af6c222010-05-14 12:43:01 +00001726 pInode->nLock--;
1727 assert( pInode->nLock>=0 );
1728 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001729 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001730 }
1731 }
aswift5b1a2562008-08-22 00:22:35 +00001732
1733end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001734 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001735 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001736 return rc;
drhbbd42a62004-05-22 17:41:58 +00001737}
1738
1739/*
drh308c2a52010-05-14 11:30:18 +00001740** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001741** must be either NO_LOCK or SHARED_LOCK.
1742**
1743** If the locking level of the file descriptor is already at or below
1744** the requested locking level, this routine is a no-op.
1745*/
drh308c2a52010-05-14 11:30:18 +00001746static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001747 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001748}
1749
1750/*
danielk1977e339d652008-06-28 11:23:00 +00001751** This function performs the parts of the "close file" operation
1752** common to all locking schemes. It closes the directory and file
1753** handles, if they are valid, and sets all fields of the unixFile
1754** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001755**
1756** It is *not* necessary to hold the mutex when this routine is called,
1757** even on VxWorks. A mutex will be acquired on VxWorks by the
1758** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001759*/
1760static int closeUnixFile(sqlite3_file *id){
1761 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001762 if( pFile->h>=0 ){
1763 robust_close(pFile, pFile->h, __LINE__);
1764 pFile->h = -1;
1765 }
1766#if OS_VXWORKS
1767 if( pFile->pId ){
1768 if( pFile->isDelete ){
drh036ac7f2011-08-08 23:18:05 +00001769 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001770 }
1771 vxworksReleaseFileId(pFile->pId);
1772 pFile->pId = 0;
1773 }
1774#endif
1775 OSTRACE(("CLOSE %-3d\n", pFile->h));
1776 OpenCounter(-1);
1777 sqlite3_free(pFile->pUnused);
1778 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001779 return SQLITE_OK;
1780}
1781
1782/*
danielk1977e3026632004-06-22 11:29:02 +00001783** Close a file.
1784*/
danielk197762079062007-08-15 17:08:46 +00001785static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001786 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001787 unixFile *pFile = (unixFile *)id;
1788 unixUnlock(id, NO_LOCK);
1789 unixEnterMutex();
1790
1791 /* unixFile.pInode is always valid here. Otherwise, a different close
1792 ** routine (e.g. nolockClose()) would be called instead.
1793 */
1794 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1795 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1796 /* If there are outstanding locks, do not actually close the file just
1797 ** yet because that would clear those locks. Instead, add the file
1798 ** descriptor to pInode->pUnused list. It will be automatically closed
1799 ** when the last lock is cleared.
1800 */
1801 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001802 }
dan661d71a2011-03-30 19:08:03 +00001803 releaseInodeInfo(pFile);
1804 rc = closeUnixFile(id);
1805 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001806 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001807}
1808
drh734c9862008-11-28 15:37:20 +00001809/************** End of the posix advisory lock implementation *****************
1810******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001811
drh734c9862008-11-28 15:37:20 +00001812/******************************************************************************
1813****************************** No-op Locking **********************************
1814**
1815** Of the various locking implementations available, this is by far the
1816** simplest: locking is ignored. No attempt is made to lock the database
1817** file for reading or writing.
1818**
1819** This locking mode is appropriate for use on read-only databases
1820** (ex: databases that are burned into CD-ROM, for example.) It can
1821** also be used if the application employs some external mechanism to
1822** prevent simultaneous access of the same database by two or more
1823** database connections. But there is a serious risk of database
1824** corruption if this locking mode is used in situations where multiple
1825** database connections are accessing the same database file at the same
1826** time and one or more of those connections are writing.
1827*/
drhbfe66312006-10-03 17:40:40 +00001828
drh734c9862008-11-28 15:37:20 +00001829static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1830 UNUSED_PARAMETER(NotUsed);
1831 *pResOut = 0;
1832 return SQLITE_OK;
1833}
drh734c9862008-11-28 15:37:20 +00001834static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1835 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1836 return SQLITE_OK;
1837}
drh734c9862008-11-28 15:37:20 +00001838static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1839 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1840 return SQLITE_OK;
1841}
1842
1843/*
drh9b35ea62008-11-29 02:20:26 +00001844** Close the file.
drh734c9862008-11-28 15:37:20 +00001845*/
1846static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001847 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001848}
1849
1850/******************* End of the no-op lock implementation *********************
1851******************************************************************************/
1852
1853/******************************************************************************
1854************************* Begin dot-file Locking ******************************
1855**
drh0c2694b2009-09-03 16:23:44 +00001856** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001857** files in order to control access to the database. This works on just
1858** about every filesystem imaginable. But there are serious downsides:
1859**
1860** (1) There is zero concurrency. A single reader blocks all other
1861** connections from reading or writing the database.
1862**
1863** (2) An application crash or power loss can leave stale lock files
1864** sitting around that need to be cleared manually.
1865**
1866** Nevertheless, a dotlock is an appropriate locking mode for use if no
1867** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001868**
1869** Dotfile locking works by creating a file in the same directory as the
1870** database and with the same name but with a ".lock" extension added.
1871** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1872** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001873*/
1874
1875/*
1876** The file suffix added to the data base filename in order to create the
1877** lock file.
1878*/
1879#define DOTLOCK_SUFFIX ".lock"
1880
drh7708e972008-11-29 00:56:52 +00001881/*
1882** This routine checks if there is a RESERVED lock held on the specified
1883** file by this or any other process. If such a lock is held, set *pResOut
1884** to a non-zero value otherwise *pResOut is set to zero. The return value
1885** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1886**
1887** In dotfile locking, either a lock exists or it does not. So in this
1888** variation of CheckReservedLock(), *pResOut is set to true if any lock
1889** is held on the file and false if the file is unlocked.
1890*/
drh734c9862008-11-28 15:37:20 +00001891static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1892 int rc = SQLITE_OK;
1893 int reserved = 0;
1894 unixFile *pFile = (unixFile*)id;
1895
1896 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1897
1898 assert( pFile );
1899
1900 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001901 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001902 /* Either this connection or some other connection in the same process
1903 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001904 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001905 }else{
1906 /* The lock is held if and only if the lockfile exists */
1907 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001908 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001909 }
drh308c2a52010-05-14 11:30:18 +00001910 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001911 *pResOut = reserved;
1912 return rc;
1913}
1914
drh7708e972008-11-29 00:56:52 +00001915/*
drh308c2a52010-05-14 11:30:18 +00001916** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001917** of the following:
1918**
1919** (1) SHARED_LOCK
1920** (2) RESERVED_LOCK
1921** (3) PENDING_LOCK
1922** (4) EXCLUSIVE_LOCK
1923**
1924** Sometimes when requesting one lock state, additional lock states
1925** are inserted in between. The locking might fail on one of the later
1926** transitions leaving the lock state different from what it started but
1927** still short of its goal. The following chart shows the allowed
1928** transitions and the inserted intermediate states:
1929**
1930** UNLOCKED -> SHARED
1931** SHARED -> RESERVED
1932** SHARED -> (PENDING) -> EXCLUSIVE
1933** RESERVED -> (PENDING) -> EXCLUSIVE
1934** PENDING -> EXCLUSIVE
1935**
1936** This routine will only increase a lock. Use the sqlite3OsUnlock()
1937** routine to lower a locking level.
1938**
1939** With dotfile locking, we really only support state (4): EXCLUSIVE.
1940** But we track the other locking levels internally.
1941*/
drh308c2a52010-05-14 11:30:18 +00001942static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001943 unixFile *pFile = (unixFile*)id;
1944 int fd;
1945 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001946 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001947
drh7708e972008-11-29 00:56:52 +00001948
1949 /* If we have any lock, then the lock file already exists. All we have
1950 ** to do is adjust our internal record of the lock level.
1951 */
drh308c2a52010-05-14 11:30:18 +00001952 if( pFile->eFileLock > NO_LOCK ){
1953 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001954 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001955#ifdef HAVE_UTIME
1956 utime(zLockFile, NULL);
1957#else
drh734c9862008-11-28 15:37:20 +00001958 utimes(zLockFile, NULL);
1959#endif
drh7708e972008-11-29 00:56:52 +00001960 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001961 }
1962
1963 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001964 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001965 if( fd<0 ){
1966 /* failed to open/create the file, someone else may have stolen the lock */
1967 int tErrno = errno;
1968 if( EEXIST == tErrno ){
1969 rc = SQLITE_BUSY;
1970 } else {
1971 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1972 if( IS_LOCK_ERROR(rc) ){
1973 pFile->lastErrno = tErrno;
1974 }
1975 }
drh7708e972008-11-29 00:56:52 +00001976 return rc;
drh734c9862008-11-28 15:37:20 +00001977 }
drh0e9365c2011-03-02 02:08:13 +00001978 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001979
1980 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001981 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001982 return rc;
1983}
1984
drh7708e972008-11-29 00:56:52 +00001985/*
drh308c2a52010-05-14 11:30:18 +00001986** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001987** must be either NO_LOCK or SHARED_LOCK.
1988**
1989** If the locking level of the file descriptor is already at or below
1990** the requested locking level, this routine is a no-op.
1991**
1992** When the locking level reaches NO_LOCK, delete the lock file.
1993*/
drh308c2a52010-05-14 11:30:18 +00001994static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001995 unixFile *pFile = (unixFile*)id;
1996 char *zLockFile = (char *)pFile->lockingContext;
1997
1998 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001999 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2000 pFile->eFileLock, getpid()));
2001 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002002
2003 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002004 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002005 return SQLITE_OK;
2006 }
drh7708e972008-11-29 00:56:52 +00002007
2008 /* To downgrade to shared, simply update our internal notion of the
2009 ** lock state. No need to mess with the file on disk.
2010 */
drh308c2a52010-05-14 11:30:18 +00002011 if( eFileLock==SHARED_LOCK ){
2012 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002013 return SQLITE_OK;
2014 }
2015
drh7708e972008-11-29 00:56:52 +00002016 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002017 assert( eFileLock==NO_LOCK );
drh036ac7f2011-08-08 23:18:05 +00002018 if( osUnlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00002019 int rc = 0;
2020 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002021 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002022 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002023 }
2024 if( IS_LOCK_ERROR(rc) ){
2025 pFile->lastErrno = tErrno;
2026 }
2027 return rc;
2028 }
drh308c2a52010-05-14 11:30:18 +00002029 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002030 return SQLITE_OK;
2031}
2032
2033/*
drh9b35ea62008-11-29 02:20:26 +00002034** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002035*/
2036static int dotlockClose(sqlite3_file *id) {
2037 int rc;
2038 if( id ){
2039 unixFile *pFile = (unixFile*)id;
2040 dotlockUnlock(id, NO_LOCK);
2041 sqlite3_free(pFile->lockingContext);
2042 }
drh734c9862008-11-28 15:37:20 +00002043 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002044 return rc;
2045}
2046/****************** End of the dot-file lock implementation *******************
2047******************************************************************************/
2048
2049/******************************************************************************
2050************************** Begin flock Locking ********************************
2051**
2052** Use the flock() system call to do file locking.
2053**
drh6b9d6dd2008-12-03 19:34:47 +00002054** flock() locking is like dot-file locking in that the various
2055** fine-grain locking levels supported by SQLite are collapsed into
2056** a single exclusive lock. In other words, SHARED, RESERVED, and
2057** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2058** still works when you do this, but concurrency is reduced since
2059** only a single process can be reading the database at a time.
2060**
drh734c9862008-11-28 15:37:20 +00002061** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2062** compiling for VXWORKS.
2063*/
2064#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002065
drh6b9d6dd2008-12-03 19:34:47 +00002066/*
drhff812312011-02-23 13:33:46 +00002067** Retry flock() calls that fail with EINTR
2068*/
2069#ifdef EINTR
2070static int robust_flock(int fd, int op){
2071 int rc;
2072 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2073 return rc;
2074}
2075#else
drh5c819272011-02-23 14:00:12 +00002076# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002077#endif
2078
2079
2080/*
drh6b9d6dd2008-12-03 19:34:47 +00002081** This routine checks if there is a RESERVED lock held on the specified
2082** file by this or any other process. If such a lock is held, set *pResOut
2083** to a non-zero value otherwise *pResOut is set to zero. The return value
2084** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2085*/
drh734c9862008-11-28 15:37:20 +00002086static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2087 int rc = SQLITE_OK;
2088 int reserved = 0;
2089 unixFile *pFile = (unixFile*)id;
2090
2091 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2092
2093 assert( pFile );
2094
2095 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002096 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002097 reserved = 1;
2098 }
2099
2100 /* Otherwise see if some other process holds it. */
2101 if( !reserved ){
2102 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002103 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002104 if( !lrc ){
2105 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002106 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002107 if ( lrc ) {
2108 int tErrno = errno;
2109 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002110 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002111 if( IS_LOCK_ERROR(lrc) ){
2112 pFile->lastErrno = tErrno;
2113 rc = lrc;
2114 }
2115 }
2116 } else {
2117 int tErrno = errno;
2118 reserved = 1;
2119 /* someone else might have it reserved */
2120 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2121 if( IS_LOCK_ERROR(lrc) ){
2122 pFile->lastErrno = tErrno;
2123 rc = lrc;
2124 }
2125 }
2126 }
drh308c2a52010-05-14 11:30:18 +00002127 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002128
2129#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2130 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2131 rc = SQLITE_OK;
2132 reserved=1;
2133 }
2134#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2135 *pResOut = reserved;
2136 return rc;
2137}
2138
drh6b9d6dd2008-12-03 19:34:47 +00002139/*
drh308c2a52010-05-14 11:30:18 +00002140** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002141** of the following:
2142**
2143** (1) SHARED_LOCK
2144** (2) RESERVED_LOCK
2145** (3) PENDING_LOCK
2146** (4) EXCLUSIVE_LOCK
2147**
2148** Sometimes when requesting one lock state, additional lock states
2149** are inserted in between. The locking might fail on one of the later
2150** transitions leaving the lock state different from what it started but
2151** still short of its goal. The following chart shows the allowed
2152** transitions and the inserted intermediate states:
2153**
2154** UNLOCKED -> SHARED
2155** SHARED -> RESERVED
2156** SHARED -> (PENDING) -> EXCLUSIVE
2157** RESERVED -> (PENDING) -> EXCLUSIVE
2158** PENDING -> EXCLUSIVE
2159**
2160** flock() only really support EXCLUSIVE locks. We track intermediate
2161** lock states in the sqlite3_file structure, but all locks SHARED or
2162** above are really EXCLUSIVE locks and exclude all other processes from
2163** access the file.
2164**
2165** This routine will only increase a lock. Use the sqlite3OsUnlock()
2166** routine to lower a locking level.
2167*/
drh308c2a52010-05-14 11:30:18 +00002168static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002169 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002170 unixFile *pFile = (unixFile*)id;
2171
2172 assert( pFile );
2173
2174 /* if we already have a lock, it is exclusive.
2175 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002176 if (pFile->eFileLock > NO_LOCK) {
2177 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002178 return SQLITE_OK;
2179 }
2180
2181 /* grab an exclusive lock */
2182
drhff812312011-02-23 13:33:46 +00002183 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002184 int tErrno = errno;
2185 /* didn't get, must be busy */
2186 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2187 if( IS_LOCK_ERROR(rc) ){
2188 pFile->lastErrno = tErrno;
2189 }
2190 } else {
2191 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002192 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002193 }
drh308c2a52010-05-14 11:30:18 +00002194 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2195 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002196#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2197 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2198 rc = SQLITE_BUSY;
2199 }
2200#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2201 return rc;
2202}
2203
drh6b9d6dd2008-12-03 19:34:47 +00002204
2205/*
drh308c2a52010-05-14 11:30:18 +00002206** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002207** must be either NO_LOCK or SHARED_LOCK.
2208**
2209** If the locking level of the file descriptor is already at or below
2210** the requested locking level, this routine is a no-op.
2211*/
drh308c2a52010-05-14 11:30:18 +00002212static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002213 unixFile *pFile = (unixFile*)id;
2214
2215 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002216 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2217 pFile->eFileLock, getpid()));
2218 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002219
2220 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002221 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002222 return SQLITE_OK;
2223 }
2224
2225 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002226 if (eFileLock==SHARED_LOCK) {
2227 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002228 return SQLITE_OK;
2229 }
2230
2231 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002232 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002233#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002234 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002235#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002236 return SQLITE_IOERR_UNLOCK;
2237 }else{
drh308c2a52010-05-14 11:30:18 +00002238 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002239 return SQLITE_OK;
2240 }
2241}
2242
2243/*
2244** Close a file.
2245*/
2246static int flockClose(sqlite3_file *id) {
2247 if( id ){
2248 flockUnlock(id, NO_LOCK);
2249 }
2250 return closeUnixFile(id);
2251}
2252
2253#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2254
2255/******************* End of the flock lock implementation *********************
2256******************************************************************************/
2257
2258/******************************************************************************
2259************************ Begin Named Semaphore Locking ************************
2260**
2261** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002262**
2263** Semaphore locking is like dot-lock and flock in that it really only
2264** supports EXCLUSIVE locking. Only a single process can read or write
2265** the database file at a time. This reduces potential concurrency, but
2266** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002267*/
2268#if OS_VXWORKS
2269
drh6b9d6dd2008-12-03 19:34:47 +00002270/*
2271** This routine checks if there is a RESERVED lock held on the specified
2272** file by this or any other process. If such a lock is held, set *pResOut
2273** to a non-zero value otherwise *pResOut is set to zero. The return value
2274** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2275*/
drh734c9862008-11-28 15:37:20 +00002276static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2277 int rc = SQLITE_OK;
2278 int reserved = 0;
2279 unixFile *pFile = (unixFile*)id;
2280
2281 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2282
2283 assert( pFile );
2284
2285 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002286 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002287 reserved = 1;
2288 }
2289
2290 /* Otherwise see if some other process holds it. */
2291 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002292 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002293 struct stat statBuf;
2294
2295 if( sem_trywait(pSem)==-1 ){
2296 int tErrno = errno;
2297 if( EAGAIN != tErrno ){
2298 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2299 pFile->lastErrno = tErrno;
2300 } else {
2301 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002302 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002303 }
2304 }else{
2305 /* we could have it if we want it */
2306 sem_post(pSem);
2307 }
2308 }
drh308c2a52010-05-14 11:30:18 +00002309 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002310
2311 *pResOut = reserved;
2312 return rc;
2313}
2314
drh6b9d6dd2008-12-03 19:34:47 +00002315/*
drh308c2a52010-05-14 11:30:18 +00002316** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002317** of the following:
2318**
2319** (1) SHARED_LOCK
2320** (2) RESERVED_LOCK
2321** (3) PENDING_LOCK
2322** (4) EXCLUSIVE_LOCK
2323**
2324** Sometimes when requesting one lock state, additional lock states
2325** are inserted in between. The locking might fail on one of the later
2326** transitions leaving the lock state different from what it started but
2327** still short of its goal. The following chart shows the allowed
2328** transitions and the inserted intermediate states:
2329**
2330** UNLOCKED -> SHARED
2331** SHARED -> RESERVED
2332** SHARED -> (PENDING) -> EXCLUSIVE
2333** RESERVED -> (PENDING) -> EXCLUSIVE
2334** PENDING -> EXCLUSIVE
2335**
2336** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2337** lock states in the sqlite3_file structure, but all locks SHARED or
2338** above are really EXCLUSIVE locks and exclude all other processes from
2339** access the file.
2340**
2341** This routine will only increase a lock. Use the sqlite3OsUnlock()
2342** routine to lower a locking level.
2343*/
drh308c2a52010-05-14 11:30:18 +00002344static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002345 unixFile *pFile = (unixFile*)id;
2346 int fd;
drh8af6c222010-05-14 12:43:01 +00002347 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002348 int rc = SQLITE_OK;
2349
2350 /* if we already have a lock, it is exclusive.
2351 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002352 if (pFile->eFileLock > NO_LOCK) {
2353 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002354 rc = SQLITE_OK;
2355 goto sem_end_lock;
2356 }
2357
2358 /* lock semaphore now but bail out when already locked. */
2359 if( sem_trywait(pSem)==-1 ){
2360 rc = SQLITE_BUSY;
2361 goto sem_end_lock;
2362 }
2363
2364 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002365 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002366
2367 sem_end_lock:
2368 return rc;
2369}
2370
drh6b9d6dd2008-12-03 19:34:47 +00002371/*
drh308c2a52010-05-14 11:30:18 +00002372** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002373** must be either NO_LOCK or SHARED_LOCK.
2374**
2375** If the locking level of the file descriptor is already at or below
2376** the requested locking level, this routine is a no-op.
2377*/
drh308c2a52010-05-14 11:30:18 +00002378static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002379 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002380 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002381
2382 assert( pFile );
2383 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002384 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2385 pFile->eFileLock, getpid()));
2386 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002387
2388 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002389 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002390 return SQLITE_OK;
2391 }
2392
2393 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002394 if (eFileLock==SHARED_LOCK) {
2395 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002396 return SQLITE_OK;
2397 }
2398
2399 /* no, really unlock. */
2400 if ( sem_post(pSem)==-1 ) {
2401 int rc, tErrno = errno;
2402 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2403 if( IS_LOCK_ERROR(rc) ){
2404 pFile->lastErrno = tErrno;
2405 }
2406 return rc;
2407 }
drh308c2a52010-05-14 11:30:18 +00002408 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002409 return SQLITE_OK;
2410}
2411
2412/*
2413 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002414 */
drh734c9862008-11-28 15:37:20 +00002415static int semClose(sqlite3_file *id) {
2416 if( id ){
2417 unixFile *pFile = (unixFile*)id;
2418 semUnlock(id, NO_LOCK);
2419 assert( pFile );
2420 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002421 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002422 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002423 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002424 }
2425 return SQLITE_OK;
2426}
2427
2428#endif /* OS_VXWORKS */
2429/*
2430** Named semaphore locking is only available on VxWorks.
2431**
2432*************** End of the named semaphore lock implementation ****************
2433******************************************************************************/
2434
2435
2436/******************************************************************************
2437*************************** Begin AFP Locking *********************************
2438**
2439** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2440** on Apple Macintosh computers - both OS9 and OSX.
2441**
2442** Third-party implementations of AFP are available. But this code here
2443** only works on OSX.
2444*/
2445
drhd2cb50b2009-01-09 21:41:17 +00002446#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002447/*
2448** The afpLockingContext structure contains all afp lock specific state
2449*/
drhbfe66312006-10-03 17:40:40 +00002450typedef struct afpLockingContext afpLockingContext;
2451struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002452 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002453 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002454};
2455
2456struct ByteRangeLockPB2
2457{
2458 unsigned long long offset; /* offset to first byte to lock */
2459 unsigned long long length; /* nbr of bytes to lock */
2460 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2461 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2462 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2463 int fd; /* file desc to assoc this lock with */
2464};
2465
drhfd131da2007-08-07 17:13:03 +00002466#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002467
drh6b9d6dd2008-12-03 19:34:47 +00002468/*
2469** This is a utility for setting or clearing a bit-range lock on an
2470** AFP filesystem.
2471**
2472** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2473*/
2474static int afpSetLock(
2475 const char *path, /* Name of the file to be locked or unlocked */
2476 unixFile *pFile, /* Open file descriptor on path */
2477 unsigned long long offset, /* First byte to be locked */
2478 unsigned long long length, /* Number of bytes to lock */
2479 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002480){
drh6b9d6dd2008-12-03 19:34:47 +00002481 struct ByteRangeLockPB2 pb;
2482 int err;
drhbfe66312006-10-03 17:40:40 +00002483
2484 pb.unLockFlag = setLockFlag ? 0 : 1;
2485 pb.startEndFlag = 0;
2486 pb.offset = offset;
2487 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002488 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002489
drh308c2a52010-05-14 11:30:18 +00002490 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002491 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002492 offset, length));
drhbfe66312006-10-03 17:40:40 +00002493 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2494 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002495 int rc;
2496 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002497 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2498 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002499#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2500 rc = SQLITE_BUSY;
2501#else
drh734c9862008-11-28 15:37:20 +00002502 rc = sqliteErrorFromPosixError(tErrno,
2503 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002504#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002505 if( IS_LOCK_ERROR(rc) ){
2506 pFile->lastErrno = tErrno;
2507 }
2508 return rc;
drhbfe66312006-10-03 17:40:40 +00002509 } else {
aswift5b1a2562008-08-22 00:22:35 +00002510 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002511 }
2512}
2513
drh6b9d6dd2008-12-03 19:34:47 +00002514/*
2515** This routine checks if there is a RESERVED lock held on the specified
2516** file by this or any other process. If such a lock is held, set *pResOut
2517** to a non-zero value otherwise *pResOut is set to zero. The return value
2518** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2519*/
danielk1977e339d652008-06-28 11:23:00 +00002520static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002521 int rc = SQLITE_OK;
2522 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002523 unixFile *pFile = (unixFile*)id;
2524
aswift5b1a2562008-08-22 00:22:35 +00002525 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2526
2527 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002528 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002529 if( context->reserved ){
2530 *pResOut = 1;
2531 return SQLITE_OK;
2532 }
drh8af6c222010-05-14 12:43:01 +00002533 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002534
2535 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002536 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002537 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002538 }
2539
2540 /* Otherwise see if some other process holds it.
2541 */
aswift5b1a2562008-08-22 00:22:35 +00002542 if( !reserved ){
2543 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002544 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002545 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002546 /* if we succeeded in taking the reserved lock, unlock it to restore
2547 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002548 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002549 } else {
2550 /* if we failed to get the lock then someone else must have it */
2551 reserved = 1;
2552 }
2553 if( IS_LOCK_ERROR(lrc) ){
2554 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002555 }
2556 }
drhbfe66312006-10-03 17:40:40 +00002557
drh7ed97b92010-01-20 13:07:21 +00002558 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002559 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002560
2561 *pResOut = reserved;
2562 return rc;
drhbfe66312006-10-03 17:40:40 +00002563}
2564
drh6b9d6dd2008-12-03 19:34:47 +00002565/*
drh308c2a52010-05-14 11:30:18 +00002566** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002567** of the following:
2568**
2569** (1) SHARED_LOCK
2570** (2) RESERVED_LOCK
2571** (3) PENDING_LOCK
2572** (4) EXCLUSIVE_LOCK
2573**
2574** Sometimes when requesting one lock state, additional lock states
2575** are inserted in between. The locking might fail on one of the later
2576** transitions leaving the lock state different from what it started but
2577** still short of its goal. The following chart shows the allowed
2578** transitions and the inserted intermediate states:
2579**
2580** UNLOCKED -> SHARED
2581** SHARED -> RESERVED
2582** SHARED -> (PENDING) -> EXCLUSIVE
2583** RESERVED -> (PENDING) -> EXCLUSIVE
2584** PENDING -> EXCLUSIVE
2585**
2586** This routine will only increase a lock. Use the sqlite3OsUnlock()
2587** routine to lower a locking level.
2588*/
drh308c2a52010-05-14 11:30:18 +00002589static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002590 int rc = SQLITE_OK;
2591 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002592 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002593 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002594
2595 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002596 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2597 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002598 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002599
drhbfe66312006-10-03 17:40:40 +00002600 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002601 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002602 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002603 */
drh308c2a52010-05-14 11:30:18 +00002604 if( pFile->eFileLock>=eFileLock ){
2605 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2606 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002607 return SQLITE_OK;
2608 }
2609
2610 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002611 ** (1) We never move from unlocked to anything higher than shared lock.
2612 ** (2) SQLite never explicitly requests a pendig lock.
2613 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002614 */
drh308c2a52010-05-14 11:30:18 +00002615 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2616 assert( eFileLock!=PENDING_LOCK );
2617 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002618
drh8af6c222010-05-14 12:43:01 +00002619 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002620 */
drh6c7d5c52008-11-21 20:32:33 +00002621 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002622 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002623
2624 /* If some thread using this PID has a lock via a different unixFile*
2625 ** handle that precludes the requested lock, return BUSY.
2626 */
drh8af6c222010-05-14 12:43:01 +00002627 if( (pFile->eFileLock!=pInode->eFileLock &&
2628 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002629 ){
2630 rc = SQLITE_BUSY;
2631 goto afp_end_lock;
2632 }
2633
2634 /* If a SHARED lock is requested, and some thread using this PID already
2635 ** has a SHARED or RESERVED lock, then increment reference counts and
2636 ** return SQLITE_OK.
2637 */
drh308c2a52010-05-14 11:30:18 +00002638 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002639 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002640 assert( eFileLock==SHARED_LOCK );
2641 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002642 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002643 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002644 pInode->nShared++;
2645 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002646 goto afp_end_lock;
2647 }
drhbfe66312006-10-03 17:40:40 +00002648
2649 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002650 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2651 ** be released.
2652 */
drh308c2a52010-05-14 11:30:18 +00002653 if( eFileLock==SHARED_LOCK
2654 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002655 ){
2656 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002657 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002658 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002659 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002660 goto afp_end_lock;
2661 }
2662 }
2663
2664 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002665 ** operating system calls for the specified lock.
2666 */
drh308c2a52010-05-14 11:30:18 +00002667 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002668 int lrc1, lrc2, lrc1Errno;
2669 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002670
drh8af6c222010-05-14 12:43:01 +00002671 assert( pInode->nShared==0 );
2672 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002673
2674 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002675 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002676 /* note that the quality of the randomness doesn't matter that much */
2677 lk = random();
drh8af6c222010-05-14 12:43:01 +00002678 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002679 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002680 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002681 if( IS_LOCK_ERROR(lrc1) ){
2682 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002683 }
aswift5b1a2562008-08-22 00:22:35 +00002684 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002685 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002686
aswift5b1a2562008-08-22 00:22:35 +00002687 if( IS_LOCK_ERROR(lrc1) ) {
2688 pFile->lastErrno = lrc1Errno;
2689 rc = lrc1;
2690 goto afp_end_lock;
2691 } else if( IS_LOCK_ERROR(lrc2) ){
2692 rc = lrc2;
2693 goto afp_end_lock;
2694 } else if( lrc1 != SQLITE_OK ) {
2695 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002696 } else {
drh308c2a52010-05-14 11:30:18 +00002697 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002698 pInode->nLock++;
2699 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002700 }
drh8af6c222010-05-14 12:43:01 +00002701 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002702 /* We are trying for an exclusive lock but another thread in this
2703 ** same process is still holding a shared lock. */
2704 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002705 }else{
2706 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2707 ** assumed that there is a SHARED or greater lock on the file
2708 ** already.
2709 */
2710 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002711 assert( 0!=pFile->eFileLock );
2712 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002713 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002714 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002715 if( !failed ){
2716 context->reserved = 1;
2717 }
drhbfe66312006-10-03 17:40:40 +00002718 }
drh308c2a52010-05-14 11:30:18 +00002719 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002720 /* Acquire an EXCLUSIVE lock */
2721
2722 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002723 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002724 */
drh6b9d6dd2008-12-03 19:34:47 +00002725 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002726 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002727 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002728 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002729 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002730 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002731 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002732 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002733 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2734 ** a critical I/O error
2735 */
2736 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2737 SQLITE_IOERR_LOCK;
2738 goto afp_end_lock;
2739 }
2740 }else{
aswift5b1a2562008-08-22 00:22:35 +00002741 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002742 }
2743 }
aswift5b1a2562008-08-22 00:22:35 +00002744 if( failed ){
2745 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002746 }
2747 }
2748
2749 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002750 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002751 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002752 }else if( eFileLock==EXCLUSIVE_LOCK ){
2753 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002754 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002755 }
2756
2757afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002758 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002759 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2760 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002761 return rc;
2762}
2763
2764/*
drh308c2a52010-05-14 11:30:18 +00002765** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002766** must be either NO_LOCK or SHARED_LOCK.
2767**
2768** If the locking level of the file descriptor is already at or below
2769** the requested locking level, this routine is a no-op.
2770*/
drh308c2a52010-05-14 11:30:18 +00002771static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002772 int rc = SQLITE_OK;
2773 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002774 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002775 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2776 int skipShared = 0;
2777#ifdef SQLITE_TEST
2778 int h = pFile->h;
2779#endif
drhbfe66312006-10-03 17:40:40 +00002780
2781 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002782 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002783 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002784 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002785
drh308c2a52010-05-14 11:30:18 +00002786 assert( eFileLock<=SHARED_LOCK );
2787 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002788 return SQLITE_OK;
2789 }
drh6c7d5c52008-11-21 20:32:33 +00002790 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002791 pInode = pFile->pInode;
2792 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002793 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002794 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002795 SimulateIOErrorBenign(1);
2796 SimulateIOError( h=(-1) )
2797 SimulateIOErrorBenign(0);
2798
2799#ifndef NDEBUG
2800 /* When reducing a lock such that other processes can start
2801 ** reading the database file again, make sure that the
2802 ** transaction counter was updated if any part of the database
2803 ** file changed. If the transaction counter is not updated,
2804 ** other connections to the same file might not realize that
2805 ** the file has changed and hence might not know to flush their
2806 ** cache. The use of a stale cache can lead to database corruption.
2807 */
2808 assert( pFile->inNormalWrite==0
2809 || pFile->dbUpdate==0
2810 || pFile->transCntrChng==1 );
2811 pFile->inNormalWrite = 0;
2812#endif
aswiftaebf4132008-11-21 00:10:35 +00002813
drh308c2a52010-05-14 11:30:18 +00002814 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002815 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002816 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002817 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002818 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002819 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2820 } else {
2821 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002822 }
2823 }
drh308c2a52010-05-14 11:30:18 +00002824 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002825 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002826 }
drh308c2a52010-05-14 11:30:18 +00002827 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002828 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2829 if( !rc ){
2830 context->reserved = 0;
2831 }
aswiftaebf4132008-11-21 00:10:35 +00002832 }
drh8af6c222010-05-14 12:43:01 +00002833 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2834 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002835 }
aswiftaebf4132008-11-21 00:10:35 +00002836 }
drh308c2a52010-05-14 11:30:18 +00002837 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002838
drh7ed97b92010-01-20 13:07:21 +00002839 /* Decrement the shared lock counter. Release the lock using an
2840 ** OS call only when all threads in this same process have released
2841 ** the lock.
2842 */
drh8af6c222010-05-14 12:43:01 +00002843 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2844 pInode->nShared--;
2845 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002846 SimulateIOErrorBenign(1);
2847 SimulateIOError( h=(-1) )
2848 SimulateIOErrorBenign(0);
2849 if( !skipShared ){
2850 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2851 }
2852 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002853 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002854 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002855 }
2856 }
2857 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002858 pInode->nLock--;
2859 assert( pInode->nLock>=0 );
2860 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002861 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002862 }
2863 }
drhbfe66312006-10-03 17:40:40 +00002864 }
drh7ed97b92010-01-20 13:07:21 +00002865
drh6c7d5c52008-11-21 20:32:33 +00002866 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002867 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002868 return rc;
2869}
2870
2871/*
drh339eb0b2008-03-07 15:34:11 +00002872** Close a file & cleanup AFP specific locking context
2873*/
danielk1977e339d652008-06-28 11:23:00 +00002874static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002875 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002876 if( id ){
2877 unixFile *pFile = (unixFile*)id;
2878 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002879 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002880 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002881 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002882 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002883 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002884 ** the last lock is cleared.
2885 */
dan08da86a2009-08-21 17:18:03 +00002886 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002887 }
danb0ac3e32010-06-16 10:55:42 +00002888 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002889 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002890 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002891 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002892 }
drh7ed97b92010-01-20 13:07:21 +00002893 return rc;
drhbfe66312006-10-03 17:40:40 +00002894}
2895
drhd2cb50b2009-01-09 21:41:17 +00002896#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002897/*
2898** The code above is the AFP lock implementation. The code is specific
2899** to MacOSX and does not work on other unix platforms. No alternative
2900** is available. If you don't compile for a mac, then the "unix-afp"
2901** VFS is not available.
2902**
2903********************* End of the AFP lock implementation **********************
2904******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002905
drh7ed97b92010-01-20 13:07:21 +00002906/******************************************************************************
2907*************************** Begin NFS Locking ********************************/
2908
2909#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2910/*
drh308c2a52010-05-14 11:30:18 +00002911 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002912 ** must be either NO_LOCK or SHARED_LOCK.
2913 **
2914 ** If the locking level of the file descriptor is already at or below
2915 ** the requested locking level, this routine is a no-op.
2916 */
drh308c2a52010-05-14 11:30:18 +00002917static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002918 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002919}
2920
2921#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2922/*
2923** The code above is the NFS lock implementation. The code is specific
2924** to MacOSX and does not work on other unix platforms. No alternative
2925** is available.
2926**
2927********************* End of the NFS lock implementation **********************
2928******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002929
2930/******************************************************************************
2931**************** Non-locking sqlite3_file methods *****************************
2932**
2933** The next division contains implementations for all methods of the
2934** sqlite3_file object other than the locking methods. The locking
2935** methods were defined in divisions above (one locking method per
2936** division). Those methods that are common to all locking modes
2937** are gather together into this division.
2938*/
drhbfe66312006-10-03 17:40:40 +00002939
2940/*
drh734c9862008-11-28 15:37:20 +00002941** Seek to the offset passed as the second argument, then read cnt
2942** bytes into pBuf. Return the number of bytes actually read.
2943**
2944** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2945** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2946** one system to another. Since SQLite does not define USE_PREAD
2947** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2948** See tickets #2741 and #2681.
2949**
2950** To avoid stomping the errno value on a failed read the lastErrno value
2951** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002952*/
drh734c9862008-11-28 15:37:20 +00002953static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2954 int got;
drh7ed97b92010-01-20 13:07:21 +00002955#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002956 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002957#endif
drh734c9862008-11-28 15:37:20 +00002958 TIMER_START;
2959#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002960 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002961 SimulateIOError( got = -1 );
2962#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002963 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002964 SimulateIOError( got = -1 );
2965#else
2966 newOffset = lseek(id->h, offset, SEEK_SET);
2967 SimulateIOError( newOffset-- );
2968 if( newOffset!=offset ){
2969 if( newOffset == -1 ){
2970 ((unixFile*)id)->lastErrno = errno;
2971 }else{
2972 ((unixFile*)id)->lastErrno = 0;
2973 }
2974 return -1;
2975 }
drhe562be52011-03-02 18:01:10 +00002976 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002977#endif
2978 TIMER_END;
2979 if( got<0 ){
2980 ((unixFile*)id)->lastErrno = errno;
2981 }
drh308c2a52010-05-14 11:30:18 +00002982 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002983 return got;
drhbfe66312006-10-03 17:40:40 +00002984}
2985
2986/*
drh734c9862008-11-28 15:37:20 +00002987** Read data from a file into a buffer. Return SQLITE_OK if all
2988** bytes were read successfully and SQLITE_IOERR if anything goes
2989** wrong.
drh339eb0b2008-03-07 15:34:11 +00002990*/
drh734c9862008-11-28 15:37:20 +00002991static int unixRead(
2992 sqlite3_file *id,
2993 void *pBuf,
2994 int amt,
2995 sqlite3_int64 offset
2996){
dan08da86a2009-08-21 17:18:03 +00002997 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002998 int got;
2999 assert( id );
drh08c6d442009-02-09 17:34:07 +00003000
dan08da86a2009-08-21 17:18:03 +00003001 /* If this is a database file (not a journal, master-journal or temp
3002 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003003#if 0
dane946c392009-08-22 11:39:46 +00003004 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003005 || offset>=PENDING_BYTE+512
3006 || offset+amt<=PENDING_BYTE
3007 );
dan7c246102010-04-12 19:00:29 +00003008#endif
drh08c6d442009-02-09 17:34:07 +00003009
dan08da86a2009-08-21 17:18:03 +00003010 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003011 if( got==amt ){
3012 return SQLITE_OK;
3013 }else if( got<0 ){
3014 /* lastErrno set by seekAndRead */
3015 return SQLITE_IOERR_READ;
3016 }else{
dan08da86a2009-08-21 17:18:03 +00003017 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003018 /* Unread parts of the buffer must be zero-filled */
3019 memset(&((char*)pBuf)[got], 0, amt-got);
3020 return SQLITE_IOERR_SHORT_READ;
3021 }
3022}
3023
3024/*
3025** Seek to the offset in id->offset then read cnt bytes into pBuf.
3026** Return the number of bytes actually read. Update the offset.
3027**
3028** To avoid stomping the errno value on a failed write the lastErrno value
3029** is set before returning.
3030*/
3031static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3032 int got;
drh7ed97b92010-01-20 13:07:21 +00003033#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003034 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003035#endif
drh734c9862008-11-28 15:37:20 +00003036 TIMER_START;
3037#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003038 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003039#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003040 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003041#else
drhbd1e50c2011-08-19 14:54:12 +00003042 do{
3043 newOffset = lseek(id->h, offset, SEEK_SET);
3044 SimulateIOError( newOffset-- );
3045 if( newOffset!=offset ){
3046 if( newOffset == -1 ){
3047 ((unixFile*)id)->lastErrno = errno;
3048 }else{
3049 ((unixFile*)id)->lastErrno = 0;
3050 }
3051 return -1;
drh734c9862008-11-28 15:37:20 +00003052 }
drhbd1e50c2011-08-19 14:54:12 +00003053 got = osWrite(id->h, pBuf, cnt);
3054 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003055#endif
3056 TIMER_END;
3057 if( got<0 ){
3058 ((unixFile*)id)->lastErrno = errno;
3059 }
3060
drh308c2a52010-05-14 11:30:18 +00003061 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003062 return got;
3063}
3064
3065
3066/*
3067** Write data from a buffer into a file. Return SQLITE_OK on success
3068** or some other error code on failure.
3069*/
3070static int unixWrite(
3071 sqlite3_file *id,
3072 const void *pBuf,
3073 int amt,
3074 sqlite3_int64 offset
3075){
dan08da86a2009-08-21 17:18:03 +00003076 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003077 int wrote = 0;
3078 assert( id );
3079 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003080
dan08da86a2009-08-21 17:18:03 +00003081 /* If this is a database file (not a journal, master-journal or temp
3082 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003083#if 0
dane946c392009-08-22 11:39:46 +00003084 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003085 || offset>=PENDING_BYTE+512
3086 || offset+amt<=PENDING_BYTE
3087 );
dan7c246102010-04-12 19:00:29 +00003088#endif
drh08c6d442009-02-09 17:34:07 +00003089
drh8f941bc2009-01-14 23:03:40 +00003090#ifndef NDEBUG
3091 /* If we are doing a normal write to a database file (as opposed to
3092 ** doing a hot-journal rollback or a write to some file other than a
3093 ** normal database file) then record the fact that the database
3094 ** has changed. If the transaction counter is modified, record that
3095 ** fact too.
3096 */
dan08da86a2009-08-21 17:18:03 +00003097 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003098 pFile->dbUpdate = 1; /* The database has been modified */
3099 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003100 int rc;
drh8f941bc2009-01-14 23:03:40 +00003101 char oldCntr[4];
3102 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003103 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003104 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003105 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003106 pFile->transCntrChng = 1; /* The transaction counter has changed */
3107 }
3108 }
3109 }
3110#endif
3111
dan08da86a2009-08-21 17:18:03 +00003112 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003113 amt -= wrote;
3114 offset += wrote;
3115 pBuf = &((char*)pBuf)[wrote];
3116 }
3117 SimulateIOError(( wrote=(-1), amt=1 ));
3118 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003119
drh734c9862008-11-28 15:37:20 +00003120 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003121 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003122 /* lastErrno set by seekAndWrite */
3123 return SQLITE_IOERR_WRITE;
3124 }else{
dan08da86a2009-08-21 17:18:03 +00003125 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003126 return SQLITE_FULL;
3127 }
3128 }
dan6e09d692010-07-27 18:34:15 +00003129
drh734c9862008-11-28 15:37:20 +00003130 return SQLITE_OK;
3131}
3132
3133#ifdef SQLITE_TEST
3134/*
3135** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003136** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003137*/
3138int sqlite3_sync_count = 0;
3139int sqlite3_fullsync_count = 0;
3140#endif
3141
3142/*
drh89240432009-03-25 01:06:01 +00003143** We do not trust systems to provide a working fdatasync(). Some do.
3144** Others do no. To be safe, we will stick with the (slower) fsync().
3145** If you know that your system does support fdatasync() correctly,
3146** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003147*/
drh89240432009-03-25 01:06:01 +00003148#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003149# define fdatasync fsync
3150#endif
3151
3152/*
3153** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3154** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3155** only available on Mac OS X. But that could change.
3156*/
3157#ifdef F_FULLFSYNC
3158# define HAVE_FULLFSYNC 1
3159#else
3160# define HAVE_FULLFSYNC 0
3161#endif
3162
3163
3164/*
3165** The fsync() system call does not work as advertised on many
3166** unix systems. The following procedure is an attempt to make
3167** it work better.
3168**
3169** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3170** for testing when we want to run through the test suite quickly.
3171** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3172** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3173** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003174**
3175** SQLite sets the dataOnly flag if the size of the file is unchanged.
3176** The idea behind dataOnly is that it should only write the file content
3177** to disk, not the inode. We only set dataOnly if the file size is
3178** unchanged since the file size is part of the inode. However,
3179** Ted Ts'o tells us that fdatasync() will also write the inode if the
3180** file size has changed. The only real difference between fdatasync()
3181** and fsync(), Ted tells us, is that fdatasync() will not flush the
3182** inode if the mtime or owner or other inode attributes have changed.
3183** We only care about the file size, not the other file attributes, so
3184** as far as SQLite is concerned, an fdatasync() is always adequate.
3185** So, we always use fdatasync() if it is available, regardless of
3186** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003187*/
3188static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003189 int rc;
drh734c9862008-11-28 15:37:20 +00003190
3191 /* The following "ifdef/elif/else/" block has the same structure as
3192 ** the one below. It is replicated here solely to avoid cluttering
3193 ** up the real code with the UNUSED_PARAMETER() macros.
3194 */
3195#ifdef SQLITE_NO_SYNC
3196 UNUSED_PARAMETER(fd);
3197 UNUSED_PARAMETER(fullSync);
3198 UNUSED_PARAMETER(dataOnly);
3199#elif HAVE_FULLFSYNC
3200 UNUSED_PARAMETER(dataOnly);
3201#else
3202 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003203 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003204#endif
3205
3206 /* Record the number of times that we do a normal fsync() and
3207 ** FULLSYNC. This is used during testing to verify that this procedure
3208 ** gets called with the correct arguments.
3209 */
3210#ifdef SQLITE_TEST
3211 if( fullSync ) sqlite3_fullsync_count++;
3212 sqlite3_sync_count++;
3213#endif
3214
3215 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3216 ** no-op
3217 */
3218#ifdef SQLITE_NO_SYNC
3219 rc = SQLITE_OK;
3220#elif HAVE_FULLFSYNC
3221 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003222 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003223 }else{
3224 rc = 1;
3225 }
3226 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003227 ** It shouldn't be possible for fullfsync to fail on the local
3228 ** file system (on OSX), so failure indicates that FULLFSYNC
3229 ** isn't supported for this file system. So, attempt an fsync
3230 ** and (for now) ignore the overhead of a superfluous fcntl call.
3231 ** It'd be better to detect fullfsync support once and avoid
3232 ** the fcntl call every time sync is called.
3233 */
drh734c9862008-11-28 15:37:20 +00003234 if( rc ) rc = fsync(fd);
3235
drh7ed97b92010-01-20 13:07:21 +00003236#elif defined(__APPLE__)
3237 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3238 ** so currently we default to the macro that redefines fdatasync to fsync
3239 */
3240 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003241#else
drh0b647ff2009-03-21 14:41:04 +00003242 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003243#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003244 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003245 rc = fsync(fd);
3246 }
drh0b647ff2009-03-21 14:41:04 +00003247#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003248#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3249
3250 if( OS_VXWORKS && rc!= -1 ){
3251 rc = 0;
3252 }
chw97185482008-11-17 08:05:31 +00003253 return rc;
drhbfe66312006-10-03 17:40:40 +00003254}
3255
drh734c9862008-11-28 15:37:20 +00003256/*
drh0059eae2011-08-08 23:48:40 +00003257** Open a file descriptor to the directory containing file zFilename.
3258** If successful, *pFd is set to the opened file descriptor and
3259** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3260** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3261** value.
3262**
drh90315a22011-08-10 01:52:12 +00003263** The directory file descriptor is used for only one thing - to
3264** fsync() a directory to make sure file creation and deletion events
3265** are flushed to disk. Such fsyncs are not needed on newer
3266** journaling filesystems, but are required on older filesystems.
3267**
3268** This routine can be overridden using the xSetSysCall interface.
3269** The ability to override this routine was added in support of the
3270** chromium sandbox. Opening a directory is a security risk (we are
3271** told) so making it overrideable allows the chromium sandbox to
3272** replace this routine with a harmless no-op. To make this routine
3273** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3274** *pFd set to a negative number.
3275**
drh0059eae2011-08-08 23:48:40 +00003276** If SQLITE_OK is returned, the caller is responsible for closing
3277** the file descriptor *pFd using close().
3278*/
3279static int openDirectory(const char *zFilename, int *pFd){
3280 int ii;
3281 int fd = -1;
3282 char zDirname[MAX_PATHNAME+1];
3283
3284 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3285 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3286 if( ii>0 ){
3287 zDirname[ii] = '\0';
3288 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3289 if( fd>=0 ){
3290#ifdef FD_CLOEXEC
3291 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3292#endif
3293 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3294 }
3295 }
3296 *pFd = fd;
3297 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3298}
3299
3300/*
drh734c9862008-11-28 15:37:20 +00003301** Make sure all writes to a particular file are committed to disk.
3302**
3303** If dataOnly==0 then both the file itself and its metadata (file
3304** size, access time, etc) are synced. If dataOnly!=0 then only the
3305** file data is synced.
3306**
3307** Under Unix, also make sure that the directory entry for the file
3308** has been created by fsync-ing the directory that contains the file.
3309** If we do not do this and we encounter a power failure, the directory
3310** entry for the journal might not exist after we reboot. The next
3311** SQLite to access the file will not know that the journal exists (because
3312** the directory entry for the journal was never created) and the transaction
3313** will not roll back - possibly leading to database corruption.
3314*/
3315static int unixSync(sqlite3_file *id, int flags){
3316 int rc;
3317 unixFile *pFile = (unixFile*)id;
3318
3319 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3320 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3321
3322 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3323 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3324 || (flags&0x0F)==SQLITE_SYNC_FULL
3325 );
3326
3327 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3328 ** line is to test that doing so does not cause any problems.
3329 */
3330 SimulateDiskfullError( return SQLITE_FULL );
3331
3332 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003333 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003334 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3335 SimulateIOError( rc=1 );
3336 if( rc ){
3337 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003338 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003339 }
drh0059eae2011-08-08 23:48:40 +00003340
3341 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003342 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3343 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003344 */
3345 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3346 int dirfd;
3347 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003348 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003349 rc = osOpenDirectory(pFile->zPath, &dirfd);
3350 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003351 full_fsync(dirfd, 0, 0);
3352 robust_close(pFile, dirfd, __LINE__);
drh734c9862008-11-28 15:37:20 +00003353 }
drh0059eae2011-08-08 23:48:40 +00003354 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003355 }
3356 return rc;
3357}
3358
3359/*
3360** Truncate an open file to a specified size
3361*/
3362static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003363 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003364 int rc;
dan6e09d692010-07-27 18:34:15 +00003365 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003366 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003367
3368 /* If the user has configured a chunk-size for this file, truncate the
3369 ** file so that it consists of an integer number of chunks (i.e. the
3370 ** actual file size after the operation may be larger than the requested
3371 ** size).
3372 */
3373 if( pFile->szChunk ){
3374 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3375 }
3376
drhff812312011-02-23 13:33:46 +00003377 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003378 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003379 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003380 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003381 }else{
drh3313b142009-11-06 04:13:18 +00003382#ifndef NDEBUG
3383 /* If we are doing a normal write to a database file (as opposed to
3384 ** doing a hot-journal rollback or a write to some file other than a
3385 ** normal database file) and we truncate the file to zero length,
3386 ** that effectively updates the change counter. This might happen
3387 ** when restoring a database using the backup API from a zero-length
3388 ** source.
3389 */
dan6e09d692010-07-27 18:34:15 +00003390 if( pFile->inNormalWrite && nByte==0 ){
3391 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003392 }
3393#endif
3394
drh734c9862008-11-28 15:37:20 +00003395 return SQLITE_OK;
3396 }
3397}
3398
3399/*
3400** Determine the current size of a file in bytes
3401*/
3402static int unixFileSize(sqlite3_file *id, i64 *pSize){
3403 int rc;
3404 struct stat buf;
3405 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003406 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003407 SimulateIOError( rc=1 );
3408 if( rc!=0 ){
3409 ((unixFile*)id)->lastErrno = errno;
3410 return SQLITE_IOERR_FSTAT;
3411 }
3412 *pSize = buf.st_size;
3413
drh8af6c222010-05-14 12:43:01 +00003414 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003415 ** writes a single byte into that file in order to work around a bug
3416 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3417 ** layers, we need to report this file size as zero even though it is
3418 ** really 1. Ticket #3260.
3419 */
3420 if( *pSize==1 ) *pSize = 0;
3421
3422
3423 return SQLITE_OK;
3424}
3425
drhd2cb50b2009-01-09 21:41:17 +00003426#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003427/*
3428** Handler for proxy-locking file-control verbs. Defined below in the
3429** proxying locking division.
3430*/
3431static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003432#endif
drh715ff302008-12-03 22:32:44 +00003433
dan502019c2010-07-28 14:26:17 +00003434/*
3435** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3436** file-control operation.
3437**
3438** If the user has configured a chunk-size for this file, it could be
3439** that the file needs to be extended at this point. Otherwise, the
3440** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3441*/
3442static int fcntlSizeHint(unixFile *pFile, i64 nByte){
drh7d2dc712011-07-25 23:25:47 +00003443 { /* preserve indentation of removed "if" */
dan502019c2010-07-28 14:26:17 +00003444 i64 nSize; /* Required file size */
drh7d2dc712011-07-25 23:25:47 +00003445 i64 szChunk; /* Chunk size */
dan502019c2010-07-28 14:26:17 +00003446 struct stat buf; /* Used to hold return values of fstat() */
3447
drh99ab3b12011-03-02 15:09:07 +00003448 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003449
drh7d2dc712011-07-25 23:25:47 +00003450 szChunk = pFile->szChunk;
3451 if( szChunk==0 ){
3452 nSize = nByte;
3453 }else{
3454 nSize = ((nByte+szChunk-1) / szChunk) * szChunk;
3455 }
dan502019c2010-07-28 14:26:17 +00003456 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003457
dan502019c2010-07-28 14:26:17 +00003458#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003459 /* The code below is handling the return value of osFallocate()
3460 ** correctly. posix_fallocate() is defined to "returns zero on success,
3461 ** or an error number on failure". See the manpage for details. */
3462 int err;
drhff812312011-02-23 13:33:46 +00003463 do{
dan661d71a2011-03-30 19:08:03 +00003464 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3465 }while( err==EINTR );
3466 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003467#else
3468 /* If the OS does not have posix_fallocate(), fake it. First use
3469 ** ftruncate() to set the file size, then write a single byte to
3470 ** the last byte in each block within the extended region. This
3471 ** is the same technique used by glibc to implement posix_fallocate()
3472 ** on systems that do not have a real fallocate() system call.
3473 */
3474 int nBlk = buf.st_blksize; /* File-system block size */
3475 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003476
drhff812312011-02-23 13:33:46 +00003477 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003478 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003479 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003480 }
3481 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003482 while( iWrite<nSize ){
3483 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3484 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003485 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003486 }
dan502019c2010-07-28 14:26:17 +00003487#endif
3488 }
3489 }
3490
3491 return SQLITE_OK;
3492}
danielk1977ad94b582007-08-20 06:44:22 +00003493
danielk1977e3026632004-06-22 11:29:02 +00003494/*
drh9e33c2c2007-08-31 18:34:59 +00003495** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003496*/
drhcc6bb3e2007-08-31 16:11:35 +00003497static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003498 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003499 switch( op ){
3500 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003501 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003502 return SQLITE_OK;
3503 }
drh7708e972008-11-29 00:56:52 +00003504 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003505 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003506 return SQLITE_OK;
3507 }
dan6e09d692010-07-27 18:34:15 +00003508 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003509 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003510 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003511 }
drh9ff27ec2010-05-19 19:26:05 +00003512 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003513 int rc;
3514 SimulateIOErrorBenign(1);
3515 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3516 SimulateIOErrorBenign(0);
3517 return rc;
drhf0b190d2011-07-26 16:03:07 +00003518 }
3519 case SQLITE_FCNTL_PERSIST_WAL: {
3520 int bPersist = *(int*)pArg;
3521 if( bPersist<0 ){
drh253cea52011-07-26 16:23:25 +00003522 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
drhf0b190d2011-07-26 16:03:07 +00003523 }else if( bPersist==0 ){
3524 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
3525 }else{
3526 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
3527 }
3528 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003529 }
drh8f941bc2009-01-14 23:03:40 +00003530#ifndef NDEBUG
3531 /* The pager calls this method to signal that it has done
3532 ** a rollback and that the database is therefore unchanged and
3533 ** it hence it is OK for the transaction change counter to be
3534 ** unchanged.
3535 */
3536 case SQLITE_FCNTL_DB_UNCHANGED: {
3537 ((unixFile*)id)->dbUpdate = 0;
3538 return SQLITE_OK;
3539 }
3540#endif
drhd2cb50b2009-01-09 21:41:17 +00003541#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003542 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003543 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003544 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003545 }
drhd2cb50b2009-01-09 21:41:17 +00003546#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003547 case SQLITE_FCNTL_SYNC_OMITTED: {
3548 return SQLITE_OK; /* A no-op */
3549 }
drh9e33c2c2007-08-31 18:34:59 +00003550 }
drh0b52b7d2011-01-26 19:46:22 +00003551 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003552}
3553
3554/*
danielk1977a3d4c882007-03-23 10:08:38 +00003555** Return the sector size in bytes of the underlying block device for
3556** the specified file. This is almost always 512 bytes, but may be
3557** larger for some devices.
3558**
3559** SQLite code assumes this function cannot fail. It also assumes that
3560** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003561** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003562** same for both.
3563*/
danielk1977397d65f2008-11-19 11:35:39 +00003564static int unixSectorSize(sqlite3_file *NotUsed){
3565 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003566 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003567}
3568
danielk197790949c22007-08-17 16:50:38 +00003569/*
danielk1977397d65f2008-11-19 11:35:39 +00003570** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003571*/
danielk1977397d65f2008-11-19 11:35:39 +00003572static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3573 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003574 return 0;
3575}
3576
drhd9e5c4f2010-05-12 18:01:39 +00003577#ifndef SQLITE_OMIT_WAL
3578
3579
3580/*
drhd91c68f2010-05-14 14:52:25 +00003581** Object used to represent an shared memory buffer.
3582**
3583** When multiple threads all reference the same wal-index, each thread
3584** has its own unixShm object, but they all point to a single instance
3585** of this unixShmNode object. In other words, each wal-index is opened
3586** only once per process.
3587**
3588** Each unixShmNode object is connected to a single unixInodeInfo object.
3589** We could coalesce this object into unixInodeInfo, but that would mean
3590** every open file that does not use shared memory (in other words, most
3591** open files) would have to carry around this extra information. So
3592** the unixInodeInfo object contains a pointer to this unixShmNode object
3593** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003594**
3595** unixMutexHeld() must be true when creating or destroying
3596** this object or while reading or writing the following fields:
3597**
3598** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003599**
3600** The following fields are read-only after the object is created:
3601**
3602** fid
3603** zFilename
3604**
drhd91c68f2010-05-14 14:52:25 +00003605** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003606** unixMutexHeld() is true when reading or writing any other field
3607** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003608*/
drhd91c68f2010-05-14 14:52:25 +00003609struct unixShmNode {
3610 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003611 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003612 char *zFilename; /* Name of the mmapped file */
3613 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003614 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003615 u16 nRegion; /* Size of array apRegion */
3616 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003617 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003618 int nRef; /* Number of unixShm objects pointing to this */
3619 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003620#ifdef SQLITE_DEBUG
3621 u8 exclMask; /* Mask of exclusive locks held */
3622 u8 sharedMask; /* Mask of shared locks held */
3623 u8 nextShmId; /* Next available unixShm.id value */
3624#endif
3625};
3626
3627/*
drhd9e5c4f2010-05-12 18:01:39 +00003628** Structure used internally by this VFS to record the state of an
3629** open shared memory connection.
3630**
drhd91c68f2010-05-14 14:52:25 +00003631** The following fields are initialized when this object is created and
3632** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003633**
drhd91c68f2010-05-14 14:52:25 +00003634** unixShm.pFile
3635** unixShm.id
3636**
3637** All other fields are read/write. The unixShm.pFile->mutex must be held
3638** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003639*/
3640struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003641 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3642 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003643 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003644 u16 sharedMask; /* Mask of shared locks held */
3645 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003646#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003647 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003648#endif
3649};
3650
3651/*
drhd9e5c4f2010-05-12 18:01:39 +00003652** Constants used for locking
3653*/
drhbd9676c2010-06-23 17:58:38 +00003654#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003655#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003656
drhd9e5c4f2010-05-12 18:01:39 +00003657/*
drh73b64e42010-05-30 19:55:15 +00003658** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003659**
3660** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3661** otherwise.
3662*/
3663static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003664 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3665 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003666 int ofst, /* First byte of the locking range */
3667 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003668){
3669 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003670 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003671
drhd91c68f2010-05-14 14:52:25 +00003672 /* Access to the unixShmNode object is serialized by the caller */
3673 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003674
drh73b64e42010-05-30 19:55:15 +00003675 /* Shared locks never span more than one byte */
3676 assert( n==1 || lockType!=F_RDLCK );
3677
3678 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003679 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003680
drh3cb93392011-03-12 18:10:44 +00003681 if( pShmNode->h>=0 ){
3682 /* Initialize the locking parameters */
3683 memset(&f, 0, sizeof(f));
3684 f.l_type = lockType;
3685 f.l_whence = SEEK_SET;
3686 f.l_start = ofst;
3687 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003688
drh3cb93392011-03-12 18:10:44 +00003689 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3690 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3691 }
drhd9e5c4f2010-05-12 18:01:39 +00003692
3693 /* Update the global lock state and do debug tracing */
3694#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003695 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003696 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003697 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003698 if( rc==SQLITE_OK ){
3699 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003700 OSTRACE(("unlock %d ok", ofst));
3701 pShmNode->exclMask &= ~mask;
3702 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003703 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003704 OSTRACE(("read-lock %d ok", ofst));
3705 pShmNode->exclMask &= ~mask;
3706 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003707 }else{
3708 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003709 OSTRACE(("write-lock %d ok", ofst));
3710 pShmNode->exclMask |= mask;
3711 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003712 }
3713 }else{
3714 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003715 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003716 }else if( lockType==F_RDLCK ){
3717 OSTRACE(("read-lock failed"));
3718 }else{
3719 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003720 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003721 }
3722 }
drh20e1f082010-05-31 16:10:12 +00003723 OSTRACE((" - afterwards %03x,%03x\n",
3724 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003725 }
drhd9e5c4f2010-05-12 18:01:39 +00003726#endif
3727
3728 return rc;
3729}
3730
drhd9e5c4f2010-05-12 18:01:39 +00003731
3732/*
drhd91c68f2010-05-14 14:52:25 +00003733** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003734**
3735** This is not a VFS shared-memory method; it is a utility function called
3736** by VFS shared-memory methods.
3737*/
drhd91c68f2010-05-14 14:52:25 +00003738static void unixShmPurge(unixFile *pFd){
3739 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003740 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003741 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003742 int i;
drhd91c68f2010-05-14 14:52:25 +00003743 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003744 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003745 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003746 if( p->h>=0 ){
3747 munmap(p->apRegion[i], p->szRegion);
3748 }else{
3749 sqlite3_free(p->apRegion[i]);
3750 }
dan13a3cb82010-06-11 19:04:21 +00003751 }
dan18801912010-06-14 14:07:50 +00003752 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003753 if( p->h>=0 ){
3754 robust_close(pFd, p->h, __LINE__);
3755 p->h = -1;
3756 }
drhd91c68f2010-05-14 14:52:25 +00003757 p->pInode->pShmNode = 0;
3758 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003759 }
3760}
3761
3762/*
danda9fe0c2010-07-13 18:44:03 +00003763** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003764** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003765**
drh7234c6d2010-06-19 15:10:09 +00003766** The file used to implement shared-memory is in the same directory
3767** as the open database file and has the same name as the open database
3768** file with the "-shm" suffix added. For example, if the database file
3769** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003770** for shared memory will be called "/home/user1/config.db-shm".
3771**
3772** Another approach to is to use files in /dev/shm or /dev/tmp or an
3773** some other tmpfs mount. But if a file in a different directory
3774** from the database file is used, then differing access permissions
3775** or a chroot() might cause two different processes on the same
3776** database to end up using different files for shared memory -
3777** meaning that their memory would not really be shared - resulting
3778** in database corruption. Nevertheless, this tmpfs file usage
3779** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3780** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3781** option results in an incompatible build of SQLite; builds of SQLite
3782** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3783** same database file at the same time, database corruption will likely
3784** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3785** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003786**
3787** When opening a new shared-memory file, if no other instances of that
3788** file are currently open, in this process or in other processes, then
3789** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003790**
3791** If the original database file (pDbFd) is using the "unix-excl" VFS
3792** that means that an exclusive lock is held on the database file and
3793** that no other processes are able to read or write the database. In
3794** that case, we do not really need shared memory. No shared memory
3795** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003796*/
danda9fe0c2010-07-13 18:44:03 +00003797static int unixOpenSharedMemory(unixFile *pDbFd){
3798 struct unixShm *p = 0; /* The connection to be opened */
3799 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3800 int rc; /* Result code */
3801 unixInodeInfo *pInode; /* The inode of fd */
3802 char *zShmFilename; /* Name of the file used for SHM */
3803 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003804
danda9fe0c2010-07-13 18:44:03 +00003805 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003806 p = sqlite3_malloc( sizeof(*p) );
3807 if( p==0 ) return SQLITE_NOMEM;
3808 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003809 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003810
danda9fe0c2010-07-13 18:44:03 +00003811 /* Check to see if a unixShmNode object already exists. Reuse an existing
3812 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003813 */
3814 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003815 pInode = pDbFd->pInode;
3816 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003817 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003818 struct stat sStat; /* fstat() info for database file */
3819
3820 /* Call fstat() to figure out the permissions on the database file. If
3821 ** a new *-shm file is created, an attempt will be made to create it
3822 ** with the same permissions. The actual permissions the file is created
3823 ** with are subject to the current umask setting.
3824 */
drh3cb93392011-03-12 18:10:44 +00003825 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003826 rc = SQLITE_IOERR_FSTAT;
3827 goto shm_open_err;
3828 }
3829
drha4ced192010-07-15 18:32:40 +00003830#ifdef SQLITE_SHM_DIRECTORY
3831 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3832#else
drh7234c6d2010-06-19 15:10:09 +00003833 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003834#endif
drh7234c6d2010-06-19 15:10:09 +00003835 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003836 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003837 rc = SQLITE_NOMEM;
3838 goto shm_open_err;
3839 }
drhd91c68f2010-05-14 14:52:25 +00003840 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003841 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003842#ifdef SQLITE_SHM_DIRECTORY
3843 sqlite3_snprintf(nShmFilename, zShmFilename,
3844 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3845 (u32)sStat.st_ino, (u32)sStat.st_dev);
3846#else
drh7234c6d2010-06-19 15:10:09 +00003847 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003848 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003849#endif
drhd91c68f2010-05-14 14:52:25 +00003850 pShmNode->h = -1;
3851 pDbFd->pInode->pShmNode = pShmNode;
3852 pShmNode->pInode = pDbFd->pInode;
3853 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3854 if( pShmNode->mutex==0 ){
3855 rc = SQLITE_NOMEM;
3856 goto shm_open_err;
3857 }
drhd9e5c4f2010-05-12 18:01:39 +00003858
drh3cb93392011-03-12 18:10:44 +00003859 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003860 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3861 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003862 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003863 const char *zRO;
3864 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003865 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003866 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3867 (sStat.st_mode & 0777));
3868 pShmNode->isReadonly = 1;
3869 }
3870 if( pShmNode->h<0 ){
3871 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3872 goto shm_open_err;
3873 }
drhd9e5c4f2010-05-12 18:01:39 +00003874 }
drh3cb93392011-03-12 18:10:44 +00003875
3876 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003877 ** If not, truncate the file to zero length.
3878 */
3879 rc = SQLITE_OK;
3880 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3881 if( robust_ftruncate(pShmNode->h, 0) ){
3882 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003883 }
3884 }
drh66dfec8b2011-06-01 20:01:49 +00003885 if( rc==SQLITE_OK ){
3886 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3887 }
3888 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003889 }
drhd9e5c4f2010-05-12 18:01:39 +00003890 }
3891
drhd91c68f2010-05-14 14:52:25 +00003892 /* Make the new connection a child of the unixShmNode */
3893 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003894#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003895 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003896#endif
drhd91c68f2010-05-14 14:52:25 +00003897 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003898 pDbFd->pShm = p;
3899 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003900
3901 /* The reference count on pShmNode has already been incremented under
3902 ** the cover of the unixEnterMutex() mutex and the pointer from the
3903 ** new (struct unixShm) object to the pShmNode has been set. All that is
3904 ** left to do is to link the new object into the linked list starting
3905 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3906 ** mutex.
3907 */
3908 sqlite3_mutex_enter(pShmNode->mutex);
3909 p->pNext = pShmNode->pFirst;
3910 pShmNode->pFirst = p;
3911 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003912 return SQLITE_OK;
3913
3914 /* Jump here on any error */
3915shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003916 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003917 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003918 unixLeaveMutex();
3919 return rc;
3920}
3921
3922/*
danda9fe0c2010-07-13 18:44:03 +00003923** This function is called to obtain a pointer to region iRegion of the
3924** shared-memory associated with the database file fd. Shared-memory regions
3925** are numbered starting from zero. Each shared-memory region is szRegion
3926** bytes in size.
3927**
3928** If an error occurs, an error code is returned and *pp is set to NULL.
3929**
3930** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3931** region has not been allocated (by any client, including one running in a
3932** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3933** bExtend is non-zero and the requested shared-memory region has not yet
3934** been allocated, it is allocated by this function.
3935**
3936** If the shared-memory region has already been allocated or is allocated by
3937** this call as described above, then it is mapped into this processes
3938** address space (if it is not already), *pp is set to point to the mapped
3939** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003940*/
danda9fe0c2010-07-13 18:44:03 +00003941static int unixShmMap(
3942 sqlite3_file *fd, /* Handle open on database file */
3943 int iRegion, /* Region to retrieve */
3944 int szRegion, /* Size of regions */
3945 int bExtend, /* True to extend file if necessary */
3946 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003947){
danda9fe0c2010-07-13 18:44:03 +00003948 unixFile *pDbFd = (unixFile*)fd;
3949 unixShm *p;
3950 unixShmNode *pShmNode;
3951 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003952
danda9fe0c2010-07-13 18:44:03 +00003953 /* If the shared-memory file has not yet been opened, open it now. */
3954 if( pDbFd->pShm==0 ){
3955 rc = unixOpenSharedMemory(pDbFd);
3956 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003957 }
drhd9e5c4f2010-05-12 18:01:39 +00003958
danda9fe0c2010-07-13 18:44:03 +00003959 p = pDbFd->pShm;
3960 pShmNode = p->pShmNode;
3961 sqlite3_mutex_enter(pShmNode->mutex);
3962 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003963 assert( pShmNode->pInode==pDbFd->pInode );
3964 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3965 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003966
3967 if( pShmNode->nRegion<=iRegion ){
3968 char **apNew; /* New apRegion[] array */
3969 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3970 struct stat sStat; /* Used by fstat() */
3971
3972 pShmNode->szRegion = szRegion;
3973
drh3cb93392011-03-12 18:10:44 +00003974 if( pShmNode->h>=0 ){
3975 /* The requested region is not mapped into this processes address space.
3976 ** Check to see if it has been allocated (i.e. if the wal-index file is
3977 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003978 */
drh3cb93392011-03-12 18:10:44 +00003979 if( osFstat(pShmNode->h, &sStat) ){
3980 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003981 goto shmpage_out;
3982 }
drh3cb93392011-03-12 18:10:44 +00003983
3984 if( sStat.st_size<nByte ){
3985 /* The requested memory region does not exist. If bExtend is set to
3986 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3987 **
3988 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3989 ** the requested memory region.
3990 */
3991 if( !bExtend ) goto shmpage_out;
3992 if( robust_ftruncate(pShmNode->h, nByte) ){
3993 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3994 pShmNode->zFilename);
3995 goto shmpage_out;
3996 }
3997 }
danda9fe0c2010-07-13 18:44:03 +00003998 }
3999
4000 /* Map the requested memory region into this processes address space. */
4001 apNew = (char **)sqlite3_realloc(
4002 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4003 );
4004 if( !apNew ){
4005 rc = SQLITE_IOERR_NOMEM;
4006 goto shmpage_out;
4007 }
4008 pShmNode->apRegion = apNew;
4009 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004010 void *pMem;
4011 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004012 pMem = mmap(0, szRegion,
4013 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004014 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4015 );
4016 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004017 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004018 goto shmpage_out;
4019 }
4020 }else{
4021 pMem = sqlite3_malloc(szRegion);
4022 if( pMem==0 ){
4023 rc = SQLITE_NOMEM;
4024 goto shmpage_out;
4025 }
4026 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004027 }
4028 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4029 pShmNode->nRegion++;
4030 }
4031 }
4032
4033shmpage_out:
4034 if( pShmNode->nRegion>iRegion ){
4035 *pp = pShmNode->apRegion[iRegion];
4036 }else{
4037 *pp = 0;
4038 }
drh66dfec8b2011-06-01 20:01:49 +00004039 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004040 sqlite3_mutex_leave(pShmNode->mutex);
4041 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004042}
4043
4044/*
drhd9e5c4f2010-05-12 18:01:39 +00004045** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004046**
4047** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4048** different here than in posix. In xShmLock(), one can go from unlocked
4049** to shared and back or from unlocked to exclusive and back. But one may
4050** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004051*/
4052static int unixShmLock(
4053 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004054 int ofst, /* First lock to acquire or release */
4055 int n, /* Number of locks to acquire or release */
4056 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004057){
drh73b64e42010-05-30 19:55:15 +00004058 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4059 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4060 unixShm *pX; /* For looping over all siblings */
4061 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4062 int rc = SQLITE_OK; /* Result code */
4063 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004064
drhd91c68f2010-05-14 14:52:25 +00004065 assert( pShmNode==pDbFd->pInode->pShmNode );
4066 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004067 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004068 assert( n>=1 );
4069 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4070 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4071 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4072 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4073 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004074 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4075 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004076
drhc99597c2010-05-31 01:41:15 +00004077 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004078 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004079 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004080 if( flags & SQLITE_SHM_UNLOCK ){
4081 u16 allMask = 0; /* Mask of locks held by siblings */
4082
4083 /* See if any siblings hold this same lock */
4084 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4085 if( pX==p ) continue;
4086 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4087 allMask |= pX->sharedMask;
4088 }
4089
4090 /* Unlock the system-level locks */
4091 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004092 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004093 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004094 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004095 }
drh73b64e42010-05-30 19:55:15 +00004096
4097 /* Undo the local locks */
4098 if( rc==SQLITE_OK ){
4099 p->exclMask &= ~mask;
4100 p->sharedMask &= ~mask;
4101 }
4102 }else if( flags & SQLITE_SHM_SHARED ){
4103 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4104
4105 /* Find out which shared locks are already held by sibling connections.
4106 ** If any sibling already holds an exclusive lock, go ahead and return
4107 ** SQLITE_BUSY.
4108 */
4109 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004110 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004111 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004112 break;
4113 }
4114 allShared |= pX->sharedMask;
4115 }
4116
4117 /* Get shared locks at the system level, if necessary */
4118 if( rc==SQLITE_OK ){
4119 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004120 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004121 }else{
drh73b64e42010-05-30 19:55:15 +00004122 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004123 }
drhd9e5c4f2010-05-12 18:01:39 +00004124 }
drh73b64e42010-05-30 19:55:15 +00004125
4126 /* Get the local shared locks */
4127 if( rc==SQLITE_OK ){
4128 p->sharedMask |= mask;
4129 }
4130 }else{
4131 /* Make sure no sibling connections hold locks that will block this
4132 ** lock. If any do, return SQLITE_BUSY right away.
4133 */
4134 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004135 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4136 rc = SQLITE_BUSY;
4137 break;
4138 }
4139 }
4140
4141 /* Get the exclusive locks at the system level. Then if successful
4142 ** also mark the local connection as being locked.
4143 */
4144 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004145 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004146 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004147 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004148 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004149 }
drhd9e5c4f2010-05-12 18:01:39 +00004150 }
4151 }
drhd91c68f2010-05-14 14:52:25 +00004152 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004153 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4154 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004155 return rc;
4156}
4157
drh286a2882010-05-20 23:51:06 +00004158/*
4159** Implement a memory barrier or memory fence on shared memory.
4160**
4161** All loads and stores begun before the barrier must complete before
4162** any load or store begun after the barrier.
4163*/
4164static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004165 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004166){
drhff828942010-06-26 21:34:06 +00004167 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004168 unixEnterMutex();
4169 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004170}
4171
dan18801912010-06-14 14:07:50 +00004172/*
danda9fe0c2010-07-13 18:44:03 +00004173** Close a connection to shared-memory. Delete the underlying
4174** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004175**
4176** If there is no shared memory associated with the connection then this
4177** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004178*/
danda9fe0c2010-07-13 18:44:03 +00004179static int unixShmUnmap(
4180 sqlite3_file *fd, /* The underlying database file */
4181 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004182){
danda9fe0c2010-07-13 18:44:03 +00004183 unixShm *p; /* The connection to be closed */
4184 unixShmNode *pShmNode; /* The underlying shared-memory file */
4185 unixShm **pp; /* For looping over sibling connections */
4186 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004187
danda9fe0c2010-07-13 18:44:03 +00004188 pDbFd = (unixFile*)fd;
4189 p = pDbFd->pShm;
4190 if( p==0 ) return SQLITE_OK;
4191 pShmNode = p->pShmNode;
4192
4193 assert( pShmNode==pDbFd->pInode->pShmNode );
4194 assert( pShmNode->pInode==pDbFd->pInode );
4195
4196 /* Remove connection p from the set of connections associated
4197 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004198 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004199 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4200 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004201
danda9fe0c2010-07-13 18:44:03 +00004202 /* Free the connection p */
4203 sqlite3_free(p);
4204 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004205 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004206
4207 /* If pShmNode->nRef has reached 0, then close the underlying
4208 ** shared-memory file, too */
4209 unixEnterMutex();
4210 assert( pShmNode->nRef>0 );
4211 pShmNode->nRef--;
4212 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004213 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004214 unixShmPurge(pDbFd);
4215 }
4216 unixLeaveMutex();
4217
4218 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004219}
drh286a2882010-05-20 23:51:06 +00004220
danda9fe0c2010-07-13 18:44:03 +00004221
drhd9e5c4f2010-05-12 18:01:39 +00004222#else
drh6b017cc2010-06-14 18:01:46 +00004223# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004224# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004225# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004226# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004227#endif /* #ifndef SQLITE_OMIT_WAL */
4228
drh734c9862008-11-28 15:37:20 +00004229/*
4230** Here ends the implementation of all sqlite3_file methods.
4231**
4232********************** End sqlite3_file Methods *******************************
4233******************************************************************************/
4234
4235/*
drh6b9d6dd2008-12-03 19:34:47 +00004236** This division contains definitions of sqlite3_io_methods objects that
4237** implement various file locking strategies. It also contains definitions
4238** of "finder" functions. A finder-function is used to locate the appropriate
4239** sqlite3_io_methods object for a particular database file. The pAppData
4240** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4241** the correct finder-function for that VFS.
4242**
4243** Most finder functions return a pointer to a fixed sqlite3_io_methods
4244** object. The only interesting finder-function is autolockIoFinder, which
4245** looks at the filesystem type and tries to guess the best locking
4246** strategy from that.
4247**
drh1875f7a2008-12-08 18:19:17 +00004248** For finder-funtion F, two objects are created:
4249**
4250** (1) The real finder-function named "FImpt()".
4251**
dane946c392009-08-22 11:39:46 +00004252** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004253**
4254**
4255** A pointer to the F pointer is used as the pAppData value for VFS
4256** objects. We have to do this instead of letting pAppData point
4257** directly at the finder-function since C90 rules prevent a void*
4258** from be cast into a function pointer.
4259**
drh6b9d6dd2008-12-03 19:34:47 +00004260**
drh7708e972008-11-29 00:56:52 +00004261** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004262**
drh7708e972008-11-29 00:56:52 +00004263** * A constant sqlite3_io_methods object call METHOD that has locking
4264** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4265**
4266** * An I/O method finder function called FINDER that returns a pointer
4267** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004268*/
drhd9e5c4f2010-05-12 18:01:39 +00004269#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004270static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004271 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004272 CLOSE, /* xClose */ \
4273 unixRead, /* xRead */ \
4274 unixWrite, /* xWrite */ \
4275 unixTruncate, /* xTruncate */ \
4276 unixSync, /* xSync */ \
4277 unixFileSize, /* xFileSize */ \
4278 LOCK, /* xLock */ \
4279 UNLOCK, /* xUnlock */ \
4280 CKLOCK, /* xCheckReservedLock */ \
4281 unixFileControl, /* xFileControl */ \
4282 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004283 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004284 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004285 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004286 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004287 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004288}; \
drh0c2694b2009-09-03 16:23:44 +00004289static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4290 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004291 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004292} \
drh0c2694b2009-09-03 16:23:44 +00004293static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004294 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004295
4296/*
4297** Here are all of the sqlite3_io_methods objects for each of the
4298** locking strategies. Functions that return pointers to these methods
4299** are also created.
4300*/
4301IOMETHODS(
4302 posixIoFinder, /* Finder function name */
4303 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004304 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004305 unixClose, /* xClose method */
4306 unixLock, /* xLock method */
4307 unixUnlock, /* xUnlock method */
4308 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004309)
drh7708e972008-11-29 00:56:52 +00004310IOMETHODS(
4311 nolockIoFinder, /* Finder function name */
4312 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004313 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004314 nolockClose, /* xClose method */
4315 nolockLock, /* xLock method */
4316 nolockUnlock, /* xUnlock method */
4317 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004318)
drh7708e972008-11-29 00:56:52 +00004319IOMETHODS(
4320 dotlockIoFinder, /* Finder function name */
4321 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004322 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004323 dotlockClose, /* xClose method */
4324 dotlockLock, /* xLock method */
4325 dotlockUnlock, /* xUnlock method */
4326 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004327)
drh7708e972008-11-29 00:56:52 +00004328
chw78a13182009-04-07 05:35:03 +00004329#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004330IOMETHODS(
4331 flockIoFinder, /* Finder function name */
4332 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004333 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004334 flockClose, /* xClose method */
4335 flockLock, /* xLock method */
4336 flockUnlock, /* xUnlock method */
4337 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004338)
drh7708e972008-11-29 00:56:52 +00004339#endif
4340
drh6c7d5c52008-11-21 20:32:33 +00004341#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004342IOMETHODS(
4343 semIoFinder, /* Finder function name */
4344 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004345 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004346 semClose, /* xClose method */
4347 semLock, /* xLock method */
4348 semUnlock, /* xUnlock method */
4349 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004350)
aswiftaebf4132008-11-21 00:10:35 +00004351#endif
drh7708e972008-11-29 00:56:52 +00004352
drhd2cb50b2009-01-09 21:41:17 +00004353#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004354IOMETHODS(
4355 afpIoFinder, /* Finder function name */
4356 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004357 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004358 afpClose, /* xClose method */
4359 afpLock, /* xLock method */
4360 afpUnlock, /* xUnlock method */
4361 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004362)
drh715ff302008-12-03 22:32:44 +00004363#endif
4364
4365/*
4366** The proxy locking method is a "super-method" in the sense that it
4367** opens secondary file descriptors for the conch and lock files and
4368** it uses proxy, dot-file, AFP, and flock() locking methods on those
4369** secondary files. For this reason, the division that implements
4370** proxy locking is located much further down in the file. But we need
4371** to go ahead and define the sqlite3_io_methods and finder function
4372** for proxy locking here. So we forward declare the I/O methods.
4373*/
drhd2cb50b2009-01-09 21:41:17 +00004374#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004375static int proxyClose(sqlite3_file*);
4376static int proxyLock(sqlite3_file*, int);
4377static int proxyUnlock(sqlite3_file*, int);
4378static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004379IOMETHODS(
4380 proxyIoFinder, /* Finder function name */
4381 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004382 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004383 proxyClose, /* xClose method */
4384 proxyLock, /* xLock method */
4385 proxyUnlock, /* xUnlock method */
4386 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004387)
aswiftaebf4132008-11-21 00:10:35 +00004388#endif
drh7708e972008-11-29 00:56:52 +00004389
drh7ed97b92010-01-20 13:07:21 +00004390/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4391#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4392IOMETHODS(
4393 nfsIoFinder, /* Finder function name */
4394 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004395 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004396 unixClose, /* xClose method */
4397 unixLock, /* xLock method */
4398 nfsUnlock, /* xUnlock method */
4399 unixCheckReservedLock /* xCheckReservedLock method */
4400)
4401#endif
drh7708e972008-11-29 00:56:52 +00004402
drhd2cb50b2009-01-09 21:41:17 +00004403#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004404/*
drh6b9d6dd2008-12-03 19:34:47 +00004405** This "finder" function attempts to determine the best locking strategy
4406** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004407** object that implements that strategy.
4408**
4409** This is for MacOSX only.
4410*/
drh1875f7a2008-12-08 18:19:17 +00004411static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004412 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004413 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004414){
4415 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004416 const char *zFilesystem; /* Filesystem type name */
4417 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004418 } aMap[] = {
4419 { "hfs", &posixIoMethods },
4420 { "ufs", &posixIoMethods },
4421 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004422 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004423 { "webdav", &nolockIoMethods },
4424 { 0, 0 }
4425 };
4426 int i;
4427 struct statfs fsInfo;
4428 struct flock lockInfo;
4429
4430 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004431 /* If filePath==NULL that means we are dealing with a transient file
4432 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004433 return &nolockIoMethods;
4434 }
4435 if( statfs(filePath, &fsInfo) != -1 ){
4436 if( fsInfo.f_flags & MNT_RDONLY ){
4437 return &nolockIoMethods;
4438 }
4439 for(i=0; aMap[i].zFilesystem; i++){
4440 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4441 return aMap[i].pMethods;
4442 }
4443 }
4444 }
4445
4446 /* Default case. Handles, amongst others, "nfs".
4447 ** Test byte-range lock using fcntl(). If the call succeeds,
4448 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004449 */
drh7708e972008-11-29 00:56:52 +00004450 lockInfo.l_len = 1;
4451 lockInfo.l_start = 0;
4452 lockInfo.l_whence = SEEK_SET;
4453 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004454 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004455 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4456 return &nfsIoMethods;
4457 } else {
4458 return &posixIoMethods;
4459 }
drh7708e972008-11-29 00:56:52 +00004460 }else{
4461 return &dotlockIoMethods;
4462 }
4463}
drh0c2694b2009-09-03 16:23:44 +00004464static const sqlite3_io_methods
4465 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004466
drhd2cb50b2009-01-09 21:41:17 +00004467#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004468
chw78a13182009-04-07 05:35:03 +00004469#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4470/*
4471** This "finder" function attempts to determine the best locking strategy
4472** for the database file "filePath". It then returns the sqlite3_io_methods
4473** object that implements that strategy.
4474**
4475** This is for VXWorks only.
4476*/
4477static const sqlite3_io_methods *autolockIoFinderImpl(
4478 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004479 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004480){
4481 struct flock lockInfo;
4482
4483 if( !filePath ){
4484 /* If filePath==NULL that means we are dealing with a transient file
4485 ** that does not need to be locked. */
4486 return &nolockIoMethods;
4487 }
4488
4489 /* Test if fcntl() is supported and use POSIX style locks.
4490 ** Otherwise fall back to the named semaphore method.
4491 */
4492 lockInfo.l_len = 1;
4493 lockInfo.l_start = 0;
4494 lockInfo.l_whence = SEEK_SET;
4495 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004496 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004497 return &posixIoMethods;
4498 }else{
4499 return &semIoMethods;
4500 }
4501}
drh0c2694b2009-09-03 16:23:44 +00004502static const sqlite3_io_methods
4503 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004504
4505#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4506
drh7708e972008-11-29 00:56:52 +00004507/*
4508** An abstract type for a pointer to a IO method finder function:
4509*/
drh0c2694b2009-09-03 16:23:44 +00004510typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004511
aswiftaebf4132008-11-21 00:10:35 +00004512
drh734c9862008-11-28 15:37:20 +00004513/****************************************************************************
4514**************************** sqlite3_vfs methods ****************************
4515**
4516** This division contains the implementation of methods on the
4517** sqlite3_vfs object.
4518*/
4519
danielk1977a3d4c882007-03-23 10:08:38 +00004520/*
danielk1977e339d652008-06-28 11:23:00 +00004521** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004522*/
4523static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004524 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004525 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004526 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004527 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004528 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004529 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004530 int isDelete, /* Delete on close if true */
4531 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004532){
drh7708e972008-11-29 00:56:52 +00004533 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004534 unixFile *pNew = (unixFile *)pId;
4535 int rc = SQLITE_OK;
4536
drh8af6c222010-05-14 12:43:01 +00004537 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004538
dane946c392009-08-22 11:39:46 +00004539 /* Parameter isDelete is only used on vxworks. Express this explicitly
4540 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004541 */
drh7708e972008-11-29 00:56:52 +00004542 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004543
dan00157392010-10-05 11:33:15 +00004544 /* Usually the path zFilename should not be a relative pathname. The
4545 ** exception is when opening the proxy "conch" file in builds that
4546 ** include the special Apple locking styles.
4547 */
dan00157392010-10-05 11:33:15 +00004548#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004549 assert( zFilename==0 || zFilename[0]=='/'
4550 || pVfs->pAppData==(void*)&autolockIoFinder );
4551#else
4552 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004553#endif
dan00157392010-10-05 11:33:15 +00004554
drh308c2a52010-05-14 11:30:18 +00004555 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004556 pNew->h = h;
drhd9e5c4f2010-05-12 18:01:39 +00004557 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004558 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4559 pNew->ctrlFlags = UNIXFILE_EXCL;
4560 }else{
4561 pNew->ctrlFlags = 0;
4562 }
drh77197112011-03-15 19:08:48 +00004563 if( isReadOnly ){
4564 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4565 }
drh0059eae2011-08-08 23:48:40 +00004566 if( syncDir ){
4567 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4568 }
drh339eb0b2008-03-07 15:34:11 +00004569
drh6c7d5c52008-11-21 20:32:33 +00004570#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004571 pNew->pId = vxworksFindFileId(zFilename);
4572 if( pNew->pId==0 ){
4573 noLock = 1;
4574 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004575 }
4576#endif
4577
drhda0e7682008-07-30 15:27:54 +00004578 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004579 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004580 }else{
drh0c2694b2009-09-03 16:23:44 +00004581 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004582#if SQLITE_ENABLE_LOCKING_STYLE
4583 /* Cache zFilename in the locking context (AFP and dotlock override) for
4584 ** proxyLock activation is possible (remote proxy is based on db name)
4585 ** zFilename remains valid until file is closed, to support */
4586 pNew->lockingContext = (void*)zFilename;
4587#endif
drhda0e7682008-07-30 15:27:54 +00004588 }
danielk1977e339d652008-06-28 11:23:00 +00004589
drh7ed97b92010-01-20 13:07:21 +00004590 if( pLockingStyle == &posixIoMethods
4591#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4592 || pLockingStyle == &nfsIoMethods
4593#endif
4594 ){
drh7708e972008-11-29 00:56:52 +00004595 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004596 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004597 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004598 /* If an error occured in findInodeInfo(), close the file descriptor
4599 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004600 ** in two scenarios:
4601 **
4602 ** (a) A call to fstat() failed.
4603 ** (b) A malloc failed.
4604 **
4605 ** Scenario (b) may only occur if the process is holding no other
4606 ** file descriptors open on the same file. If there were other file
4607 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004608 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004609 ** handle h - as it is guaranteed that no posix locks will be released
4610 ** by doing so.
4611 **
4612 ** If scenario (a) caused the error then things are not so safe. The
4613 ** implicit assumption here is that if fstat() fails, things are in
4614 ** such bad shape that dropping a lock or two doesn't matter much.
4615 */
drh0e9365c2011-03-02 02:08:13 +00004616 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004617 h = -1;
4618 }
drh7708e972008-11-29 00:56:52 +00004619 unixLeaveMutex();
4620 }
danielk1977e339d652008-06-28 11:23:00 +00004621
drhd2cb50b2009-01-09 21:41:17 +00004622#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004623 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004624 /* AFP locking uses the file path so it needs to be included in
4625 ** the afpLockingContext.
4626 */
4627 afpLockingContext *pCtx;
4628 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4629 if( pCtx==0 ){
4630 rc = SQLITE_NOMEM;
4631 }else{
4632 /* NB: zFilename exists and remains valid until the file is closed
4633 ** according to requirement F11141. So we do not need to make a
4634 ** copy of the filename. */
4635 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004636 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004637 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004638 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004639 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004640 if( rc!=SQLITE_OK ){
4641 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004642 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004643 h = -1;
4644 }
drh7708e972008-11-29 00:56:52 +00004645 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004646 }
drh7708e972008-11-29 00:56:52 +00004647 }
4648#endif
danielk1977e339d652008-06-28 11:23:00 +00004649
drh7708e972008-11-29 00:56:52 +00004650 else if( pLockingStyle == &dotlockIoMethods ){
4651 /* Dotfile locking uses the file path so it needs to be included in
4652 ** the dotlockLockingContext
4653 */
4654 char *zLockFile;
4655 int nFilename;
drhea678832008-12-10 19:26:22 +00004656 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004657 zLockFile = (char *)sqlite3_malloc(nFilename);
4658 if( zLockFile==0 ){
4659 rc = SQLITE_NOMEM;
4660 }else{
4661 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004662 }
drh7708e972008-11-29 00:56:52 +00004663 pNew->lockingContext = zLockFile;
4664 }
danielk1977e339d652008-06-28 11:23:00 +00004665
drh6c7d5c52008-11-21 20:32:33 +00004666#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004667 else if( pLockingStyle == &semIoMethods ){
4668 /* Named semaphore locking uses the file path so it needs to be
4669 ** included in the semLockingContext
4670 */
4671 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004672 rc = findInodeInfo(pNew, &pNew->pInode);
4673 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4674 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004675 int n;
drh2238dcc2009-08-27 17:56:20 +00004676 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004677 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004678 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004679 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004680 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4681 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004682 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004683 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004684 }
chw97185482008-11-17 08:05:31 +00004685 }
drh7708e972008-11-29 00:56:52 +00004686 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004687 }
drh7708e972008-11-29 00:56:52 +00004688#endif
aswift5b1a2562008-08-22 00:22:35 +00004689
4690 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004691#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004692 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004693 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004694 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004695 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004696 isDelete = 0;
4697 }
4698 pNew->isDelete = isDelete;
4699#endif
danielk1977e339d652008-06-28 11:23:00 +00004700 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004701 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004702 }else{
drh7708e972008-11-29 00:56:52 +00004703 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004704 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004705 }
danielk1977e339d652008-06-28 11:23:00 +00004706 return rc;
drh054889e2005-11-30 03:20:31 +00004707}
drh9c06c952005-11-26 00:25:00 +00004708
danielk1977ad94b582007-08-20 06:44:22 +00004709/*
drh8b3cf822010-06-01 21:02:51 +00004710** Return the name of a directory in which to put temporary files.
4711** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004712*/
drh7234c6d2010-06-19 15:10:09 +00004713static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004714 static const char *azDirs[] = {
4715 0,
aswiftaebf4132008-11-21 00:10:35 +00004716 0,
danielk197717b90b52008-06-06 11:11:25 +00004717 "/var/tmp",
4718 "/usr/tmp",
4719 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004720 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004721 };
drh8b3cf822010-06-01 21:02:51 +00004722 unsigned int i;
4723 struct stat buf;
4724 const char *zDir = 0;
4725
4726 azDirs[0] = sqlite3_temp_directory;
4727 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004728 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004729 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004730 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004731 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004732 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004733 break;
4734 }
4735 return zDir;
4736}
4737
4738/*
4739** Create a temporary file name in zBuf. zBuf must be allocated
4740** by the calling process and must be big enough to hold at least
4741** pVfs->mxPathname bytes.
4742*/
4743static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004744 static const unsigned char zChars[] =
4745 "abcdefghijklmnopqrstuvwxyz"
4746 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4747 "0123456789";
drh41022642008-11-21 00:24:42 +00004748 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004749 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004750
4751 /* It's odd to simulate an io-error here, but really this is just
4752 ** using the io-error infrastructure to test that SQLite handles this
4753 ** function failing.
4754 */
4755 SimulateIOError( return SQLITE_IOERR );
4756
drh7234c6d2010-06-19 15:10:09 +00004757 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004758 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004759
4760 /* Check that the output buffer is large enough for the temporary file
4761 ** name. If it is not, return SQLITE_ERROR.
4762 */
danielk197700e13612008-11-17 19:18:54 +00004763 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004764 return SQLITE_ERROR;
4765 }
4766
4767 do{
4768 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004769 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004770 sqlite3_randomness(15, &zBuf[j]);
4771 for(i=0; i<15; i++, j++){
4772 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4773 }
4774 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004775 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004776 return SQLITE_OK;
4777}
4778
drhd2cb50b2009-01-09 21:41:17 +00004779#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004780/*
4781** Routine to transform a unixFile into a proxy-locking unixFile.
4782** Implementation in the proxy-lock division, but used by unixOpen()
4783** if SQLITE_PREFER_PROXY_LOCKING is defined.
4784*/
4785static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004786#endif
drhc66d5b62008-12-03 22:48:32 +00004787
dan08da86a2009-08-21 17:18:03 +00004788/*
4789** Search for an unused file descriptor that was opened on the database
4790** file (not a journal or master-journal file) identified by pathname
4791** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4792** argument to this function.
4793**
4794** Such a file descriptor may exist if a database connection was closed
4795** but the associated file descriptor could not be closed because some
4796** other file descriptor open on the same file is holding a file-lock.
4797** Refer to comments in the unixClose() function and the lengthy comment
4798** describing "Posix Advisory Locking" at the start of this file for
4799** further details. Also, ticket #4018.
4800**
4801** If a suitable file descriptor is found, then it is returned. If no
4802** such file descriptor is located, -1 is returned.
4803*/
dane946c392009-08-22 11:39:46 +00004804static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4805 UnixUnusedFd *pUnused = 0;
4806
4807 /* Do not search for an unused file descriptor on vxworks. Not because
4808 ** vxworks would not benefit from the change (it might, we're not sure),
4809 ** but because no way to test it is currently available. It is better
4810 ** not to risk breaking vxworks support for the sake of such an obscure
4811 ** feature. */
4812#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004813 struct stat sStat; /* Results of stat() call */
4814
4815 /* A stat() call may fail for various reasons. If this happens, it is
4816 ** almost certain that an open() call on the same path will also fail.
4817 ** For this reason, if an error occurs in the stat() call here, it is
4818 ** ignored and -1 is returned. The caller will try to open a new file
4819 ** descriptor on the same path, fail, and return an error to SQLite.
4820 **
4821 ** Even if a subsequent open() call does succeed, the consequences of
4822 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004823 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004824 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004825
4826 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004827 pInode = inodeList;
4828 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4829 || pInode->fileId.ino!=sStat.st_ino) ){
4830 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004831 }
drh8af6c222010-05-14 12:43:01 +00004832 if( pInode ){
dane946c392009-08-22 11:39:46 +00004833 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004834 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004835 pUnused = *pp;
4836 if( pUnused ){
4837 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004838 }
4839 }
4840 unixLeaveMutex();
4841 }
dane946c392009-08-22 11:39:46 +00004842#endif /* if !OS_VXWORKS */
4843 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004844}
danielk197717b90b52008-06-06 11:11:25 +00004845
4846/*
danddb0ac42010-07-14 14:48:58 +00004847** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004848** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004849** and a value suitable for passing as the third argument to open(2) is
4850** written to *pMode. If an IO error occurs, an SQLite error code is
4851** returned and the value of *pMode is not modified.
4852**
4853** If the file being opened is a temporary file, it is always created with
4854** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004855** is a database or master journal file, it is created with the permissions
4856** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004857**
drh8ab58662010-07-15 18:38:39 +00004858** Finally, if the file being opened is a WAL or regular journal file, then
4859** this function queries the file-system for the permissions on the
4860** corresponding database file and sets *pMode to this value. Whenever
4861** possible, WAL and journal files are created using the same permissions
4862** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004863**
4864** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4865** original filename is unavailable. But 8_3_NAMES is only used for
4866** FAT filesystems and permissions do not matter there, so just use
4867** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004868*/
4869static int findCreateFileMode(
4870 const char *zPath, /* Path of file (possibly) being created */
4871 int flags, /* Flags passed as 4th argument to xOpen() */
4872 mode_t *pMode /* OUT: Permissions to open file with */
4873){
4874 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004875 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004876 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004877 char zDb[MAX_PATHNAME+1]; /* Database file path */
4878 int nDb; /* Number of valid bytes in zDb */
4879 struct stat sStat; /* Output of stat() on database file */
4880
dana0c989d2010-11-05 18:07:37 +00004881 /* zPath is a path to a WAL or journal file. The following block derives
4882 ** the path to the associated database file from zPath. This block handles
4883 ** the following naming conventions:
4884 **
4885 ** "<path to db>-journal"
4886 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004887 ** "<path to db>-journalNN"
4888 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004889 **
drh81cc5162011-05-17 20:36:21 +00004890 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004891 ** used by the test_multiplex.c module.
4892 */
4893 nDb = sqlite3Strlen30(zPath) - 1;
drh81cc5162011-05-17 20:36:21 +00004894 while( nDb>0 && zPath[nDb]!='-' ) nDb--;
4895 if( nDb==0 ) return SQLITE_OK;
danddb0ac42010-07-14 14:48:58 +00004896 memcpy(zDb, zPath, nDb);
4897 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004898
drh58384f12011-07-28 00:14:45 +00004899 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004900 *pMode = sStat.st_mode & 0777;
4901 }else{
4902 rc = SQLITE_IOERR_FSTAT;
4903 }
4904 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4905 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004906 }
4907 return rc;
4908}
4909
4910/*
danielk1977ad94b582007-08-20 06:44:22 +00004911** Open the file zPath.
4912**
danielk1977b4b47412007-08-17 15:53:36 +00004913** Previously, the SQLite OS layer used three functions in place of this
4914** one:
4915**
4916** sqlite3OsOpenReadWrite();
4917** sqlite3OsOpenReadOnly();
4918** sqlite3OsOpenExclusive();
4919**
4920** These calls correspond to the following combinations of flags:
4921**
4922** ReadWrite() -> (READWRITE | CREATE)
4923** ReadOnly() -> (READONLY)
4924** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4925**
4926** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4927** true, the file was configured to be automatically deleted when the
4928** file handle closed. To achieve the same effect using this new
4929** interface, add the DELETEONCLOSE flag to those specified above for
4930** OpenExclusive().
4931*/
4932static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004933 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4934 const char *zPath, /* Pathname of file to be opened */
4935 sqlite3_file *pFile, /* The file descriptor to be filled in */
4936 int flags, /* Input flags to control the opening */
4937 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004938){
dan08da86a2009-08-21 17:18:03 +00004939 unixFile *p = (unixFile *)pFile;
4940 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004941 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004942 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004943 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004944 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004945
4946 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4947 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4948 int isCreate = (flags & SQLITE_OPEN_CREATE);
4949 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4950 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004951#if SQLITE_ENABLE_LOCKING_STYLE
4952 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4953#endif
danielk1977b4b47412007-08-17 15:53:36 +00004954
danielk1977fee2d252007-08-18 10:59:19 +00004955 /* If creating a master or main-file journal, this function will open
4956 ** a file-descriptor on the directory too. The first time unixSync()
4957 ** is called the directory file descriptor will be fsync()ed and close()d.
4958 */
drh0059eae2011-08-08 23:48:40 +00004959 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00004960 eType==SQLITE_OPEN_MASTER_JOURNAL
4961 || eType==SQLITE_OPEN_MAIN_JOURNAL
4962 || eType==SQLITE_OPEN_WAL
4963 ));
danielk1977fee2d252007-08-18 10:59:19 +00004964
danielk197717b90b52008-06-06 11:11:25 +00004965 /* If argument zPath is a NULL pointer, this function is required to open
4966 ** a temporary file. Use this buffer to store the file name in.
4967 */
4968 char zTmpname[MAX_PATHNAME+1];
4969 const char *zName = zPath;
4970
danielk1977fee2d252007-08-18 10:59:19 +00004971 /* Check the following statements are true:
4972 **
4973 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4974 ** (b) if CREATE is set, then READWRITE must also be set, and
4975 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004976 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004977 */
danielk1977b4b47412007-08-17 15:53:36 +00004978 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004979 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004980 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004981 assert(isDelete==0 || isCreate);
4982
danddb0ac42010-07-14 14:48:58 +00004983 /* The main DB, main journal, WAL file and master journal are never
4984 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004985 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4986 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4987 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004988 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004989
danielk1977fee2d252007-08-18 10:59:19 +00004990 /* Assert that the upper layer has set one of the "file-type" flags. */
4991 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4992 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4993 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004994 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004995 );
4996
dan08da86a2009-08-21 17:18:03 +00004997 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004998
dan08da86a2009-08-21 17:18:03 +00004999 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005000 UnixUnusedFd *pUnused;
5001 pUnused = findReusableFd(zName, flags);
5002 if( pUnused ){
5003 fd = pUnused->fd;
5004 }else{
dan6aa657f2009-08-24 18:57:58 +00005005 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005006 if( !pUnused ){
5007 return SQLITE_NOMEM;
5008 }
5009 }
5010 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00005011 }else if( !zName ){
5012 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005013 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00005014 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005015 if( rc!=SQLITE_OK ){
5016 return rc;
5017 }
5018 zName = zTmpname;
5019 }
5020
dan08da86a2009-08-21 17:18:03 +00005021 /* Determine the value of the flags parameter passed to POSIX function
5022 ** open(). These must be calculated even if open() is not called, as
5023 ** they may be stored as part of the file handle and used by the
5024 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005025 if( isReadonly ) openFlags |= O_RDONLY;
5026 if( isReadWrite ) openFlags |= O_RDWR;
5027 if( isCreate ) openFlags |= O_CREAT;
5028 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5029 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005030
danielk1977b4b47412007-08-17 15:53:36 +00005031 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005032 mode_t openMode; /* Permissions to create file with */
5033 rc = findCreateFileMode(zName, flags, &openMode);
5034 if( rc!=SQLITE_OK ){
5035 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005036 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005037 return rc;
5038 }
drhad4f1e52011-03-04 15:43:57 +00005039 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005040 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005041 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5042 /* Failed to open the file for read/write access. Try read-only. */
5043 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005044 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005045 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005046 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005047 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005048 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005049 }
5050 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005051 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005052 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005053 }
danielk1977b4b47412007-08-17 15:53:36 +00005054 }
dan08da86a2009-08-21 17:18:03 +00005055 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005056 if( pOutFlags ){
5057 *pOutFlags = flags;
5058 }
5059
dane946c392009-08-22 11:39:46 +00005060 if( p->pUnused ){
5061 p->pUnused->fd = fd;
5062 p->pUnused->flags = flags;
5063 }
5064
danielk1977b4b47412007-08-17 15:53:36 +00005065 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005066#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005067 zPath = zName;
5068#else
drh036ac7f2011-08-08 23:18:05 +00005069 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005070#endif
danielk1977b4b47412007-08-17 15:53:36 +00005071 }
drh41022642008-11-21 00:24:42 +00005072#if SQLITE_ENABLE_LOCKING_STYLE
5073 else{
dan08da86a2009-08-21 17:18:03 +00005074 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005075 }
5076#endif
5077
danielk1977e339d652008-06-28 11:23:00 +00005078#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005079 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005080#endif
5081
drhda0e7682008-07-30 15:27:54 +00005082 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005083
drh7ed97b92010-01-20 13:07:21 +00005084
5085#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5086 struct statfs fsInfo;
5087 if( fstatfs(fd, &fsInfo) == -1 ){
5088 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005089 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005090 return SQLITE_IOERR_ACCESS;
5091 }
5092 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5093 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5094 }
5095#endif
5096
5097#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005098#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005099 isAutoProxy = 1;
5100#endif
5101 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005102 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5103 int useProxy = 0;
5104
dan08da86a2009-08-21 17:18:03 +00005105 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5106 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005107 if( envforce!=NULL ){
5108 useProxy = atoi(envforce)>0;
5109 }else{
5110 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005111 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005112 /* In theory, the close(fd) call is sub-optimal. If the file opened
5113 ** with fd is a database file, and there are other connections open
5114 ** on that file that are currently holding advisory locks on it,
5115 ** then the call to close() will cancel those locks. In practice,
5116 ** we're assuming that statfs() doesn't fail very often. At least
5117 ** not while other file descriptors opened by the same process on
5118 ** the same file are working. */
5119 p->lastErrno = errno;
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 ){
drh0059eae2011-08-08 23:48:40 +00005127 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005128 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
drh0059eae2011-08-08 23:48:40 +00005145 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005146 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);
drh036ac7f2011-08-08 23:18:05 +00005167 if( osUnlink(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;
drh90315a22011-08-10 01:52:12 +00005173 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005174 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;
drh58384f12011-07-28 00:14:45 +00005226 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005227 *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;
drh715ff302008-12-03 22:32:44 +00005745 unixFile *pNew;
5746 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005747 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005748 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005749 int terrno = 0;
5750 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005751
drh7ed97b92010-01-20 13:07:21 +00005752 /* 1. first try to open/create the file
5753 ** 2. if that fails, and this is a lock file (not-conch), try creating
5754 ** the parent directories and then try again.
5755 ** 3. if that fails, try to open the file read-only
5756 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5757 */
5758 pUnused = findReusableFd(path, openFlags);
5759 if( pUnused ){
5760 fd = pUnused->fd;
5761 }else{
5762 pUnused = sqlite3_malloc(sizeof(*pUnused));
5763 if( !pUnused ){
5764 return SQLITE_NOMEM;
5765 }
5766 }
5767 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005768 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005769 terrno = errno;
5770 if( fd<0 && errno==ENOENT && islockfile ){
5771 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005772 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005773 }
5774 }
5775 }
5776 if( fd<0 ){
5777 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005778 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005779 terrno = errno;
5780 }
5781 if( fd<0 ){
5782 if( islockfile ){
5783 return SQLITE_BUSY;
5784 }
5785 switch (terrno) {
5786 case EACCES:
5787 return SQLITE_PERM;
5788 case EIO:
5789 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5790 default:
drh9978c972010-02-23 17:36:32 +00005791 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005792 }
5793 }
5794
5795 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5796 if( pNew==NULL ){
5797 rc = SQLITE_NOMEM;
5798 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005799 }
5800 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005801 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005802 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005803 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005804 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005805 pUnused->fd = fd;
5806 pUnused->flags = openFlags;
5807 pNew->pUnused = pUnused;
5808
drh0059eae2011-08-08 23:48:40 +00005809 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005810 if( rc==SQLITE_OK ){
5811 *ppFile = pNew;
5812 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005813 }
drh7ed97b92010-01-20 13:07:21 +00005814end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005815 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005816 sqlite3_free(pNew);
5817 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005818 return rc;
5819}
5820
drh7ed97b92010-01-20 13:07:21 +00005821#ifdef SQLITE_TEST
5822/* simulate multiple hosts by creating unique hostid file paths */
5823int sqlite3_hostid_num = 0;
5824#endif
5825
5826#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5827
drh0ab216a2010-07-02 17:10:40 +00005828/* Not always defined in the headers as it ought to be */
5829extern int gethostuuid(uuid_t id, const struct timespec *wait);
5830
drh7ed97b92010-01-20 13:07:21 +00005831/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5832** bytes of writable memory.
5833*/
5834static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005835 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5836 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005837#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5838 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005839 {
5840 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5841 if( gethostuuid(pHostID, &timeout) ){
5842 int err = errno;
5843 if( pError ){
5844 *pError = err;
5845 }
5846 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005847 }
drh7ed97b92010-01-20 13:07:21 +00005848 }
drhe8b0c9b2010-09-25 14:13:17 +00005849#endif
drh7ed97b92010-01-20 13:07:21 +00005850#ifdef SQLITE_TEST
5851 /* simulate multiple hosts by creating unique hostid file paths */
5852 if( sqlite3_hostid_num != 0){
5853 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5854 }
5855#endif
5856
5857 return SQLITE_OK;
5858}
5859
5860/* The conch file contains the header, host id and lock file path
5861 */
5862#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5863#define PROXY_HEADERLEN 1 /* conch file header length */
5864#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5865#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5866
5867/*
5868** Takes an open conch file, copies the contents to a new path and then moves
5869** it back. The newly created file's file descriptor is assigned to the
5870** conch file structure and finally the original conch file descriptor is
5871** closed. Returns zero if successful.
5872*/
5873static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5874 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5875 unixFile *conchFile = pCtx->conchFile;
5876 char tPath[MAXPATHLEN];
5877 char buf[PROXY_MAXCONCHLEN];
5878 char *cPath = pCtx->conchFilePath;
5879 size_t readLen = 0;
5880 size_t pathLen = 0;
5881 char errmsg[64] = "";
5882 int fd = -1;
5883 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005884 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005885
5886 /* create a new path by replace the trailing '-conch' with '-break' */
5887 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5888 if( pathLen>MAXPATHLEN || pathLen<6 ||
5889 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005890 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005891 goto end_breaklock;
5892 }
5893 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005894 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005895 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005896 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005897 goto end_breaklock;
5898 }
5899 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005900 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5901 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005902 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005903 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005904 goto end_breaklock;
5905 }
drhe562be52011-03-02 18:01:10 +00005906 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005907 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005908 goto end_breaklock;
5909 }
5910 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005911 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005912 goto end_breaklock;
5913 }
5914 rc = 0;
5915 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005916 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005917 conchFile->h = fd;
5918 conchFile->openFlags = O_RDWR | O_CREAT;
5919
5920end_breaklock:
5921 if( rc ){
5922 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005923 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005924 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005925 }
5926 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5927 }
5928 return rc;
5929}
5930
5931/* Take the requested lock on the conch file and break a stale lock if the
5932** host id matches.
5933*/
5934static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5935 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5936 unixFile *conchFile = pCtx->conchFile;
5937 int rc = SQLITE_OK;
5938 int nTries = 0;
5939 struct timespec conchModTime;
5940
5941 do {
5942 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5943 nTries ++;
5944 if( rc==SQLITE_BUSY ){
5945 /* If the lock failed (busy):
5946 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5947 * 2nd try: fail if the mod time changed or host id is different, wait
5948 * 10 sec and try again
5949 * 3rd try: break the lock unless the mod time has changed.
5950 */
5951 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005952 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005953 pFile->lastErrno = errno;
5954 return SQLITE_IOERR_LOCK;
5955 }
5956
5957 if( nTries==1 ){
5958 conchModTime = buf.st_mtimespec;
5959 usleep(500000); /* wait 0.5 sec and try the lock again*/
5960 continue;
5961 }
5962
5963 assert( nTries>1 );
5964 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5965 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5966 return SQLITE_BUSY;
5967 }
5968
5969 if( nTries==2 ){
5970 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005971 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005972 if( len<0 ){
5973 pFile->lastErrno = errno;
5974 return SQLITE_IOERR_LOCK;
5975 }
5976 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5977 /* don't break the lock if the host id doesn't match */
5978 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5979 return SQLITE_BUSY;
5980 }
5981 }else{
5982 /* don't break the lock on short read or a version mismatch */
5983 return SQLITE_BUSY;
5984 }
5985 usleep(10000000); /* wait 10 sec and try the lock again */
5986 continue;
5987 }
5988
5989 assert( nTries==3 );
5990 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5991 rc = SQLITE_OK;
5992 if( lockType==EXCLUSIVE_LOCK ){
5993 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5994 }
5995 if( !rc ){
5996 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5997 }
5998 }
5999 }
6000 } while( rc==SQLITE_BUSY && nTries<3 );
6001
6002 return rc;
6003}
6004
6005/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006006** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6007** lockPath means that the lockPath in the conch file will be used if the
6008** host IDs match, or a new lock path will be generated automatically
6009** and written to the conch file.
6010*/
6011static int proxyTakeConch(unixFile *pFile){
6012 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6013
drh7ed97b92010-01-20 13:07:21 +00006014 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006015 return SQLITE_OK;
6016 }else{
6017 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006018 uuid_t myHostID;
6019 int pError = 0;
6020 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006021 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006022 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006023 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006024 int createConch = 0;
6025 int hostIdMatch = 0;
6026 int readLen = 0;
6027 int tryOldLockPath = 0;
6028 int forceNewLockPath = 0;
6029
drh308c2a52010-05-14 11:30:18 +00006030 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6031 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006032
drh7ed97b92010-01-20 13:07:21 +00006033 rc = proxyGetHostID(myHostID, &pError);
6034 if( (rc&0xff)==SQLITE_IOERR ){
6035 pFile->lastErrno = pError;
6036 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006037 }
drh7ed97b92010-01-20 13:07:21 +00006038 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006039 if( rc!=SQLITE_OK ){
6040 goto end_takeconch;
6041 }
drh7ed97b92010-01-20 13:07:21 +00006042 /* read the existing conch file */
6043 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6044 if( readLen<0 ){
6045 /* I/O error: lastErrno set by seekAndRead */
6046 pFile->lastErrno = conchFile->lastErrno;
6047 rc = SQLITE_IOERR_READ;
6048 goto end_takeconch;
6049 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6050 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6051 /* a short read or version format mismatch means we need to create a new
6052 ** conch file.
6053 */
6054 createConch = 1;
6055 }
6056 /* if the host id matches and the lock path already exists in the conch
6057 ** we'll try to use the path there, if we can't open that path, we'll
6058 ** retry with a new auto-generated path
6059 */
6060 do { /* in case we need to try again for an :auto: named lock file */
6061
6062 if( !createConch && !forceNewLockPath ){
6063 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6064 PROXY_HOSTIDLEN);
6065 /* if the conch has data compare the contents */
6066 if( !pCtx->lockProxyPath ){
6067 /* for auto-named local lock file, just check the host ID and we'll
6068 ** use the local lock file path that's already in there
6069 */
6070 if( hostIdMatch ){
6071 size_t pathLen = (readLen - PROXY_PATHINDEX);
6072
6073 if( pathLen>=MAXPATHLEN ){
6074 pathLen=MAXPATHLEN-1;
6075 }
6076 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6077 lockPath[pathLen] = 0;
6078 tempLockPath = lockPath;
6079 tryOldLockPath = 1;
6080 /* create a copy of the lock path if the conch is taken */
6081 goto end_takeconch;
6082 }
6083 }else if( hostIdMatch
6084 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6085 readLen-PROXY_PATHINDEX)
6086 ){
6087 /* conch host and lock path match */
6088 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006089 }
drh7ed97b92010-01-20 13:07:21 +00006090 }
6091
6092 /* if the conch isn't writable and doesn't match, we can't take it */
6093 if( (conchFile->openFlags&O_RDWR) == 0 ){
6094 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006095 goto end_takeconch;
6096 }
drh7ed97b92010-01-20 13:07:21 +00006097
6098 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006099 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006100 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6101 tempLockPath = lockPath;
6102 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006103 }
drh7ed97b92010-01-20 13:07:21 +00006104
6105 /* update conch with host and path (this will fail if other process
6106 ** has a shared lock already), if the host id matches, use the big
6107 ** stick.
drh715ff302008-12-03 22:32:44 +00006108 */
drh7ed97b92010-01-20 13:07:21 +00006109 futimes(conchFile->h, NULL);
6110 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006111 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006112 /* We are trying for an exclusive lock but another thread in this
6113 ** same process is still holding a shared lock. */
6114 rc = SQLITE_BUSY;
6115 } else {
6116 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006117 }
drh715ff302008-12-03 22:32:44 +00006118 }else{
drh7ed97b92010-01-20 13:07:21 +00006119 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006120 }
drh7ed97b92010-01-20 13:07:21 +00006121 if( rc==SQLITE_OK ){
6122 char writeBuffer[PROXY_MAXCONCHLEN];
6123 int writeSize = 0;
6124
6125 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6126 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6127 if( pCtx->lockProxyPath!=NULL ){
6128 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6129 }else{
6130 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6131 }
6132 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006133 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006134 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6135 fsync(conchFile->h);
6136 /* If we created a new conch file (not just updated the contents of a
6137 ** valid conch file), try to match the permissions of the database
6138 */
6139 if( rc==SQLITE_OK && createConch ){
6140 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006141 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006142 if( err==0 ){
6143 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6144 S_IROTH|S_IWOTH);
6145 /* try to match the database file R/W permissions, ignore failure */
6146#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006147 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006148#else
drhff812312011-02-23 13:33:46 +00006149 do{
drhe562be52011-03-02 18:01:10 +00006150 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006151 }while( rc==(-1) && errno==EINTR );
6152 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006153 int code = errno;
6154 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6155 cmode, code, strerror(code));
6156 } else {
6157 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6158 }
6159 }else{
6160 int code = errno;
6161 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6162 err, code, strerror(code));
6163#endif
6164 }
drh715ff302008-12-03 22:32:44 +00006165 }
6166 }
drh7ed97b92010-01-20 13:07:21 +00006167 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6168
6169 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006170 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006171 if( rc==SQLITE_OK && pFile->openFlags ){
6172 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006173 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006174 }
6175 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006176 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006177 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006178 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006179 if( fd>=0 ){
6180 pFile->h = fd;
6181 }else{
drh9978c972010-02-23 17:36:32 +00006182 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006183 during locking */
6184 }
6185 }
6186 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6187 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6188 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6189 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6190 /* we couldn't create the proxy lock file with the old lock file path
6191 ** so try again via auto-naming
6192 */
6193 forceNewLockPath = 1;
6194 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006195 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006196 }
6197 }
6198 if( rc==SQLITE_OK ){
6199 /* Need to make a copy of path if we extracted the value
6200 ** from the conch file or the path was allocated on the stack
6201 */
6202 if( tempLockPath ){
6203 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6204 if( !pCtx->lockProxyPath ){
6205 rc = SQLITE_NOMEM;
6206 }
6207 }
6208 }
6209 if( rc==SQLITE_OK ){
6210 pCtx->conchHeld = 1;
6211
6212 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6213 afpLockingContext *afpCtx;
6214 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6215 afpCtx->dbPath = pCtx->lockProxyPath;
6216 }
6217 } else {
6218 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6219 }
drh308c2a52010-05-14 11:30:18 +00006220 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6221 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006222 return rc;
drh308c2a52010-05-14 11:30:18 +00006223 } while (1); /* in case we need to retry the :auto: lock file -
6224 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006225 }
6226}
6227
6228/*
6229** If pFile holds a lock on a conch file, then release that lock.
6230*/
6231static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006232 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006233 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6234 unixFile *conchFile; /* Name of the conch file */
6235
6236 pCtx = (proxyLockingContext *)pFile->lockingContext;
6237 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006238 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006239 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006240 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006241 if( pCtx->conchHeld>0 ){
6242 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6243 }
drh715ff302008-12-03 22:32:44 +00006244 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006245 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6246 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006247 return rc;
6248}
6249
6250/*
6251** Given the name of a database file, compute the name of its conch file.
6252** Store the conch filename in memory obtained from sqlite3_malloc().
6253** Make *pConchPath point to the new name. Return SQLITE_OK on success
6254** or SQLITE_NOMEM if unable to obtain memory.
6255**
6256** The caller is responsible for ensuring that the allocated memory
6257** space is eventually freed.
6258**
6259** *pConchPath is set to NULL if a memory allocation error occurs.
6260*/
6261static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6262 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006263 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006264 char *conchPath; /* buffer in which to construct conch name */
6265
6266 /* Allocate space for the conch filename and initialize the name to
6267 ** the name of the original database file. */
6268 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6269 if( conchPath==0 ){
6270 return SQLITE_NOMEM;
6271 }
6272 memcpy(conchPath, dbPath, len+1);
6273
6274 /* now insert a "." before the last / character */
6275 for( i=(len-1); i>=0; i-- ){
6276 if( conchPath[i]=='/' ){
6277 i++;
6278 break;
6279 }
6280 }
6281 conchPath[i]='.';
6282 while ( i<len ){
6283 conchPath[i+1]=dbPath[i];
6284 i++;
6285 }
6286
6287 /* append the "-conch" suffix to the file */
6288 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006289 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006290
6291 return SQLITE_OK;
6292}
6293
6294
6295/* Takes a fully configured proxy locking-style unix file and switches
6296** the local lock file path
6297*/
6298static int switchLockProxyPath(unixFile *pFile, const char *path) {
6299 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6300 char *oldPath = pCtx->lockProxyPath;
6301 int rc = SQLITE_OK;
6302
drh308c2a52010-05-14 11:30:18 +00006303 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006304 return SQLITE_BUSY;
6305 }
6306
6307 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6308 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6309 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6310 return SQLITE_OK;
6311 }else{
6312 unixFile *lockProxy = pCtx->lockProxy;
6313 pCtx->lockProxy=NULL;
6314 pCtx->conchHeld = 0;
6315 if( lockProxy!=NULL ){
6316 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6317 if( rc ) return rc;
6318 sqlite3_free(lockProxy);
6319 }
6320 sqlite3_free(oldPath);
6321 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6322 }
6323
6324 return rc;
6325}
6326
6327/*
6328** pFile is a file that has been opened by a prior xOpen call. dbPath
6329** is a string buffer at least MAXPATHLEN+1 characters in size.
6330**
6331** This routine find the filename associated with pFile and writes it
6332** int dbPath.
6333*/
6334static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006335#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006336 if( pFile->pMethod == &afpIoMethods ){
6337 /* afp style keeps a reference to the db path in the filePath field
6338 ** of the struct */
drhea678832008-12-10 19:26:22 +00006339 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006340 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6341 } else
drh715ff302008-12-03 22:32:44 +00006342#endif
6343 if( pFile->pMethod == &dotlockIoMethods ){
6344 /* dot lock style uses the locking context to store the dot lock
6345 ** file path */
6346 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6347 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6348 }else{
6349 /* all other styles use the locking context to store the db file path */
6350 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006351 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006352 }
6353 return SQLITE_OK;
6354}
6355
6356/*
6357** Takes an already filled in unix file and alters it so all file locking
6358** will be performed on the local proxy lock file. The following fields
6359** are preserved in the locking context so that they can be restored and
6360** the unix structure properly cleaned up at close time:
6361** ->lockingContext
6362** ->pMethod
6363*/
6364static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6365 proxyLockingContext *pCtx;
6366 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6367 char *lockPath=NULL;
6368 int rc = SQLITE_OK;
6369
drh308c2a52010-05-14 11:30:18 +00006370 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006371 return SQLITE_BUSY;
6372 }
6373 proxyGetDbPathForUnixFile(pFile, dbPath);
6374 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6375 lockPath=NULL;
6376 }else{
6377 lockPath=(char *)path;
6378 }
6379
drh308c2a52010-05-14 11:30:18 +00006380 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6381 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006382
6383 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6384 if( pCtx==0 ){
6385 return SQLITE_NOMEM;
6386 }
6387 memset(pCtx, 0, sizeof(*pCtx));
6388
6389 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6390 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006391 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6392 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6393 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6394 ** (c) the file system is read-only, then enable no-locking access.
6395 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6396 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6397 */
6398 struct statfs fsInfo;
6399 struct stat conchInfo;
6400 int goLockless = 0;
6401
drh99ab3b12011-03-02 15:09:07 +00006402 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006403 int err = errno;
6404 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6405 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6406 }
6407 }
6408 if( goLockless ){
6409 pCtx->conchHeld = -1; /* read only FS/ lockless */
6410 rc = SQLITE_OK;
6411 }
6412 }
drh715ff302008-12-03 22:32:44 +00006413 }
6414 if( rc==SQLITE_OK && lockPath ){
6415 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6416 }
6417
6418 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006419 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6420 if( pCtx->dbPath==NULL ){
6421 rc = SQLITE_NOMEM;
6422 }
6423 }
6424 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006425 /* all memory is allocated, proxys are created and assigned,
6426 ** switch the locking context and pMethod then return.
6427 */
drh715ff302008-12-03 22:32:44 +00006428 pCtx->oldLockingContext = pFile->lockingContext;
6429 pFile->lockingContext = pCtx;
6430 pCtx->pOldMethod = pFile->pMethod;
6431 pFile->pMethod = &proxyIoMethods;
6432 }else{
6433 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006434 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006435 sqlite3_free(pCtx->conchFile);
6436 }
drhd56b1212010-08-11 06:14:15 +00006437 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006438 sqlite3_free(pCtx->conchFilePath);
6439 sqlite3_free(pCtx);
6440 }
drh308c2a52010-05-14 11:30:18 +00006441 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6442 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006443 return rc;
6444}
6445
6446
6447/*
6448** This routine handles sqlite3_file_control() calls that are specific
6449** to proxy locking.
6450*/
6451static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6452 switch( op ){
6453 case SQLITE_GET_LOCKPROXYFILE: {
6454 unixFile *pFile = (unixFile*)id;
6455 if( pFile->pMethod == &proxyIoMethods ){
6456 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6457 proxyTakeConch(pFile);
6458 if( pCtx->lockProxyPath ){
6459 *(const char **)pArg = pCtx->lockProxyPath;
6460 }else{
6461 *(const char **)pArg = ":auto: (not held)";
6462 }
6463 } else {
6464 *(const char **)pArg = NULL;
6465 }
6466 return SQLITE_OK;
6467 }
6468 case SQLITE_SET_LOCKPROXYFILE: {
6469 unixFile *pFile = (unixFile*)id;
6470 int rc = SQLITE_OK;
6471 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6472 if( pArg==NULL || (const char *)pArg==0 ){
6473 if( isProxyStyle ){
6474 /* turn off proxy locking - not supported */
6475 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6476 }else{
6477 /* turn off proxy locking - already off - NOOP */
6478 rc = SQLITE_OK;
6479 }
6480 }else{
6481 const char *proxyPath = (const char *)pArg;
6482 if( isProxyStyle ){
6483 proxyLockingContext *pCtx =
6484 (proxyLockingContext*)pFile->lockingContext;
6485 if( !strcmp(pArg, ":auto:")
6486 || (pCtx->lockProxyPath &&
6487 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6488 ){
6489 rc = SQLITE_OK;
6490 }else{
6491 rc = switchLockProxyPath(pFile, proxyPath);
6492 }
6493 }else{
6494 /* turn on proxy file locking */
6495 rc = proxyTransformUnixFile(pFile, proxyPath);
6496 }
6497 }
6498 return rc;
6499 }
6500 default: {
6501 assert( 0 ); /* The call assures that only valid opcodes are sent */
6502 }
6503 }
6504 /*NOTREACHED*/
6505 return SQLITE_ERROR;
6506}
6507
6508/*
6509** Within this division (the proxying locking implementation) the procedures
6510** above this point are all utilities. The lock-related methods of the
6511** proxy-locking sqlite3_io_method object follow.
6512*/
6513
6514
6515/*
6516** This routine checks if there is a RESERVED lock held on the specified
6517** file by this or any other process. If such a lock is held, set *pResOut
6518** to a non-zero value otherwise *pResOut is set to zero. The return value
6519** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6520*/
6521static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6522 unixFile *pFile = (unixFile*)id;
6523 int rc = proxyTakeConch(pFile);
6524 if( rc==SQLITE_OK ){
6525 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006526 if( pCtx->conchHeld>0 ){
6527 unixFile *proxy = pCtx->lockProxy;
6528 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6529 }else{ /* conchHeld < 0 is lockless */
6530 pResOut=0;
6531 }
drh715ff302008-12-03 22:32:44 +00006532 }
6533 return rc;
6534}
6535
6536/*
drh308c2a52010-05-14 11:30:18 +00006537** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006538** of the following:
6539**
6540** (1) SHARED_LOCK
6541** (2) RESERVED_LOCK
6542** (3) PENDING_LOCK
6543** (4) EXCLUSIVE_LOCK
6544**
6545** Sometimes when requesting one lock state, additional lock states
6546** are inserted in between. The locking might fail on one of the later
6547** transitions leaving the lock state different from what it started but
6548** still short of its goal. The following chart shows the allowed
6549** transitions and the inserted intermediate states:
6550**
6551** UNLOCKED -> SHARED
6552** SHARED -> RESERVED
6553** SHARED -> (PENDING) -> EXCLUSIVE
6554** RESERVED -> (PENDING) -> EXCLUSIVE
6555** PENDING -> EXCLUSIVE
6556**
6557** This routine will only increase a lock. Use the sqlite3OsUnlock()
6558** routine to lower a locking level.
6559*/
drh308c2a52010-05-14 11:30:18 +00006560static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006561 unixFile *pFile = (unixFile*)id;
6562 int rc = proxyTakeConch(pFile);
6563 if( rc==SQLITE_OK ){
6564 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006565 if( pCtx->conchHeld>0 ){
6566 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006567 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6568 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006569 }else{
6570 /* conchHeld < 0 is lockless */
6571 }
drh715ff302008-12-03 22:32:44 +00006572 }
6573 return rc;
6574}
6575
6576
6577/*
drh308c2a52010-05-14 11:30:18 +00006578** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006579** must be either NO_LOCK or SHARED_LOCK.
6580**
6581** If the locking level of the file descriptor is already at or below
6582** the requested locking level, this routine is a no-op.
6583*/
drh308c2a52010-05-14 11:30:18 +00006584static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006585 unixFile *pFile = (unixFile*)id;
6586 int rc = proxyTakeConch(pFile);
6587 if( rc==SQLITE_OK ){
6588 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006589 if( pCtx->conchHeld>0 ){
6590 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006591 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6592 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006593 }else{
6594 /* conchHeld < 0 is lockless */
6595 }
drh715ff302008-12-03 22:32:44 +00006596 }
6597 return rc;
6598}
6599
6600/*
6601** Close a file that uses proxy locks.
6602*/
6603static int proxyClose(sqlite3_file *id) {
6604 if( id ){
6605 unixFile *pFile = (unixFile*)id;
6606 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6607 unixFile *lockProxy = pCtx->lockProxy;
6608 unixFile *conchFile = pCtx->conchFile;
6609 int rc = SQLITE_OK;
6610
6611 if( lockProxy ){
6612 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6613 if( rc ) return rc;
6614 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6615 if( rc ) return rc;
6616 sqlite3_free(lockProxy);
6617 pCtx->lockProxy = 0;
6618 }
6619 if( conchFile ){
6620 if( pCtx->conchHeld ){
6621 rc = proxyReleaseConch(pFile);
6622 if( rc ) return rc;
6623 }
6624 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6625 if( rc ) return rc;
6626 sqlite3_free(conchFile);
6627 }
drhd56b1212010-08-11 06:14:15 +00006628 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006629 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006630 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006631 /* restore the original locking context and pMethod then close it */
6632 pFile->lockingContext = pCtx->oldLockingContext;
6633 pFile->pMethod = pCtx->pOldMethod;
6634 sqlite3_free(pCtx);
6635 return pFile->pMethod->xClose(id);
6636 }
6637 return SQLITE_OK;
6638}
6639
6640
6641
drhd2cb50b2009-01-09 21:41:17 +00006642#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006643/*
6644** The proxy locking style is intended for use with AFP filesystems.
6645** And since AFP is only supported on MacOSX, the proxy locking is also
6646** restricted to MacOSX.
6647**
6648**
6649******************* End of the proxy lock implementation **********************
6650******************************************************************************/
6651
drh734c9862008-11-28 15:37:20 +00006652/*
danielk1977e339d652008-06-28 11:23:00 +00006653** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006654**
6655** This routine registers all VFS implementations for unix-like operating
6656** systems. This routine, and the sqlite3_os_end() routine that follows,
6657** should be the only routines in this file that are visible from other
6658** files.
drh6b9d6dd2008-12-03 19:34:47 +00006659**
6660** This routine is called once during SQLite initialization and by a
6661** single thread. The memory allocation and mutex subsystems have not
6662** necessarily been initialized when this routine is called, and so they
6663** should not be used.
drh153c62c2007-08-24 03:51:33 +00006664*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006665int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006666 /*
6667 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006668 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6669 ** to the "finder" function. (pAppData is a pointer to a pointer because
6670 ** silly C90 rules prohibit a void* from being cast to a function pointer
6671 ** and so we have to go through the intermediate pointer to avoid problems
6672 ** when compiling with -pedantic-errors on GCC.)
6673 **
6674 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006675 ** finder-function. The finder-function returns a pointer to the
6676 ** sqlite_io_methods object that implements the desired locking
6677 ** behaviors. See the division above that contains the IOMETHODS
6678 ** macro for addition information on finder-functions.
6679 **
6680 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6681 ** object. But the "autolockIoFinder" available on MacOSX does a little
6682 ** more than that; it looks at the filesystem type that hosts the
6683 ** database file and tries to choose an locking method appropriate for
6684 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006685 */
drh7708e972008-11-29 00:56:52 +00006686 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006687 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006688 sizeof(unixFile), /* szOsFile */ \
6689 MAX_PATHNAME, /* mxPathname */ \
6690 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006691 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006692 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006693 unixOpen, /* xOpen */ \
6694 unixDelete, /* xDelete */ \
6695 unixAccess, /* xAccess */ \
6696 unixFullPathname, /* xFullPathname */ \
6697 unixDlOpen, /* xDlOpen */ \
6698 unixDlError, /* xDlError */ \
6699 unixDlSym, /* xDlSym */ \
6700 unixDlClose, /* xDlClose */ \
6701 unixRandomness, /* xRandomness */ \
6702 unixSleep, /* xSleep */ \
6703 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006704 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006705 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006706 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006707 unixGetSystemCall, /* xGetSystemCall */ \
6708 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006709 }
6710
drh6b9d6dd2008-12-03 19:34:47 +00006711 /*
6712 ** All default VFSes for unix are contained in the following array.
6713 **
6714 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6715 ** by the SQLite core when the VFS is registered. So the following
6716 ** array cannot be const.
6717 */
danielk1977e339d652008-06-28 11:23:00 +00006718 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006719#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006720 UNIXVFS("unix", autolockIoFinder ),
6721#else
6722 UNIXVFS("unix", posixIoFinder ),
6723#endif
6724 UNIXVFS("unix-none", nolockIoFinder ),
6725 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006726 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006727#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006728 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006729#endif
6730#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006731 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006732#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006733 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006734#endif
chw78a13182009-04-07 05:35:03 +00006735#endif
drhd2cb50b2009-01-09 21:41:17 +00006736#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006737 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006738 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006739 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006740#endif
drh153c62c2007-08-24 03:51:33 +00006741 };
drh6b9d6dd2008-12-03 19:34:47 +00006742 unsigned int i; /* Loop counter */
6743
drh2aa5a002011-04-13 13:42:25 +00006744 /* Double-check that the aSyscall[] array has been constructed
6745 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh90315a22011-08-10 01:52:12 +00006746 assert( ArraySize(aSyscall)==18 );
drh2aa5a002011-04-13 13:42:25 +00006747
drh6b9d6dd2008-12-03 19:34:47 +00006748 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006749 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006750 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006751 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006752 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006753}
danielk1977e339d652008-06-28 11:23:00 +00006754
6755/*
drh6b9d6dd2008-12-03 19:34:47 +00006756** Shutdown the operating system interface.
6757**
6758** Some operating systems might need to do some cleanup in this routine,
6759** to release dynamically allocated objects. But not on unix.
6760** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006761*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006762int sqlite3_os_end(void){
6763 return SQLITE_OK;
6764}
drhdce8bdb2007-08-16 13:01:44 +00006765
danielk197729bafea2008-06-26 10:41:19 +00006766#endif /* SQLITE_OS_UNIX */