blob: 857ed58a9ff9e58943c1e36970ed5a3e440ab69c [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
3042 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003043 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003044 if( newOffset!=offset ){
3045 if( newOffset == -1 ){
3046 ((unixFile*)id)->lastErrno = errno;
3047 }else{
3048 ((unixFile*)id)->lastErrno = 0;
3049 }
3050 return -1;
3051 }
drhe562be52011-03-02 18:01:10 +00003052 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003053#endif
3054 TIMER_END;
3055 if( got<0 ){
3056 ((unixFile*)id)->lastErrno = errno;
3057 }
3058
drh308c2a52010-05-14 11:30:18 +00003059 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003060 return got;
3061}
3062
3063
3064/*
3065** Write data from a buffer into a file. Return SQLITE_OK on success
3066** or some other error code on failure.
3067*/
3068static int unixWrite(
3069 sqlite3_file *id,
3070 const void *pBuf,
3071 int amt,
3072 sqlite3_int64 offset
3073){
dan08da86a2009-08-21 17:18:03 +00003074 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003075 int wrote = 0;
3076 assert( id );
3077 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003078
dan08da86a2009-08-21 17:18:03 +00003079 /* If this is a database file (not a journal, master-journal or temp
3080 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003081#if 0
dane946c392009-08-22 11:39:46 +00003082 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003083 || offset>=PENDING_BYTE+512
3084 || offset+amt<=PENDING_BYTE
3085 );
dan7c246102010-04-12 19:00:29 +00003086#endif
drh08c6d442009-02-09 17:34:07 +00003087
drh8f941bc2009-01-14 23:03:40 +00003088#ifndef NDEBUG
3089 /* If we are doing a normal write to a database file (as opposed to
3090 ** doing a hot-journal rollback or a write to some file other than a
3091 ** normal database file) then record the fact that the database
3092 ** has changed. If the transaction counter is modified, record that
3093 ** fact too.
3094 */
dan08da86a2009-08-21 17:18:03 +00003095 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003096 pFile->dbUpdate = 1; /* The database has been modified */
3097 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003098 int rc;
drh8f941bc2009-01-14 23:03:40 +00003099 char oldCntr[4];
3100 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003101 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003102 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003103 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003104 pFile->transCntrChng = 1; /* The transaction counter has changed */
3105 }
3106 }
3107 }
3108#endif
3109
dan08da86a2009-08-21 17:18:03 +00003110 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003111 amt -= wrote;
3112 offset += wrote;
3113 pBuf = &((char*)pBuf)[wrote];
3114 }
3115 SimulateIOError(( wrote=(-1), amt=1 ));
3116 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003117
drh734c9862008-11-28 15:37:20 +00003118 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003119 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003120 /* lastErrno set by seekAndWrite */
3121 return SQLITE_IOERR_WRITE;
3122 }else{
dan08da86a2009-08-21 17:18:03 +00003123 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003124 return SQLITE_FULL;
3125 }
3126 }
dan6e09d692010-07-27 18:34:15 +00003127
drh734c9862008-11-28 15:37:20 +00003128 return SQLITE_OK;
3129}
3130
3131#ifdef SQLITE_TEST
3132/*
3133** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003134** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003135*/
3136int sqlite3_sync_count = 0;
3137int sqlite3_fullsync_count = 0;
3138#endif
3139
3140/*
drh89240432009-03-25 01:06:01 +00003141** We do not trust systems to provide a working fdatasync(). Some do.
3142** Others do no. To be safe, we will stick with the (slower) fsync().
3143** If you know that your system does support fdatasync() correctly,
3144** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003145*/
drh89240432009-03-25 01:06:01 +00003146#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003147# define fdatasync fsync
3148#endif
3149
3150/*
3151** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3152** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3153** only available on Mac OS X. But that could change.
3154*/
3155#ifdef F_FULLFSYNC
3156# define HAVE_FULLFSYNC 1
3157#else
3158# define HAVE_FULLFSYNC 0
3159#endif
3160
3161
3162/*
3163** The fsync() system call does not work as advertised on many
3164** unix systems. The following procedure is an attempt to make
3165** it work better.
3166**
3167** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3168** for testing when we want to run through the test suite quickly.
3169** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3170** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3171** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003172**
3173** SQLite sets the dataOnly flag if the size of the file is unchanged.
3174** The idea behind dataOnly is that it should only write the file content
3175** to disk, not the inode. We only set dataOnly if the file size is
3176** unchanged since the file size is part of the inode. However,
3177** Ted Ts'o tells us that fdatasync() will also write the inode if the
3178** file size has changed. The only real difference between fdatasync()
3179** and fsync(), Ted tells us, is that fdatasync() will not flush the
3180** inode if the mtime or owner or other inode attributes have changed.
3181** We only care about the file size, not the other file attributes, so
3182** as far as SQLite is concerned, an fdatasync() is always adequate.
3183** So, we always use fdatasync() if it is available, regardless of
3184** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003185*/
3186static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003187 int rc;
drh734c9862008-11-28 15:37:20 +00003188
3189 /* The following "ifdef/elif/else/" block has the same structure as
3190 ** the one below. It is replicated here solely to avoid cluttering
3191 ** up the real code with the UNUSED_PARAMETER() macros.
3192 */
3193#ifdef SQLITE_NO_SYNC
3194 UNUSED_PARAMETER(fd);
3195 UNUSED_PARAMETER(fullSync);
3196 UNUSED_PARAMETER(dataOnly);
3197#elif HAVE_FULLFSYNC
3198 UNUSED_PARAMETER(dataOnly);
3199#else
3200 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003201 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003202#endif
3203
3204 /* Record the number of times that we do a normal fsync() and
3205 ** FULLSYNC. This is used during testing to verify that this procedure
3206 ** gets called with the correct arguments.
3207 */
3208#ifdef SQLITE_TEST
3209 if( fullSync ) sqlite3_fullsync_count++;
3210 sqlite3_sync_count++;
3211#endif
3212
3213 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3214 ** no-op
3215 */
3216#ifdef SQLITE_NO_SYNC
3217 rc = SQLITE_OK;
3218#elif HAVE_FULLFSYNC
3219 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003220 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003221 }else{
3222 rc = 1;
3223 }
3224 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003225 ** It shouldn't be possible for fullfsync to fail on the local
3226 ** file system (on OSX), so failure indicates that FULLFSYNC
3227 ** isn't supported for this file system. So, attempt an fsync
3228 ** and (for now) ignore the overhead of a superfluous fcntl call.
3229 ** It'd be better to detect fullfsync support once and avoid
3230 ** the fcntl call every time sync is called.
3231 */
drh734c9862008-11-28 15:37:20 +00003232 if( rc ) rc = fsync(fd);
3233
drh7ed97b92010-01-20 13:07:21 +00003234#elif defined(__APPLE__)
3235 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3236 ** so currently we default to the macro that redefines fdatasync to fsync
3237 */
3238 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003239#else
drh0b647ff2009-03-21 14:41:04 +00003240 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003241#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003242 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003243 rc = fsync(fd);
3244 }
drh0b647ff2009-03-21 14:41:04 +00003245#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003246#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3247
3248 if( OS_VXWORKS && rc!= -1 ){
3249 rc = 0;
3250 }
chw97185482008-11-17 08:05:31 +00003251 return rc;
drhbfe66312006-10-03 17:40:40 +00003252}
3253
drh734c9862008-11-28 15:37:20 +00003254/*
drh0059eae2011-08-08 23:48:40 +00003255** Open a file descriptor to the directory containing file zFilename.
3256** If successful, *pFd is set to the opened file descriptor and
3257** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3258** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3259** value.
3260**
drh90315a22011-08-10 01:52:12 +00003261** The directory file descriptor is used for only one thing - to
3262** fsync() a directory to make sure file creation and deletion events
3263** are flushed to disk. Such fsyncs are not needed on newer
3264** journaling filesystems, but are required on older filesystems.
3265**
3266** This routine can be overridden using the xSetSysCall interface.
3267** The ability to override this routine was added in support of the
3268** chromium sandbox. Opening a directory is a security risk (we are
3269** told) so making it overrideable allows the chromium sandbox to
3270** replace this routine with a harmless no-op. To make this routine
3271** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3272** *pFd set to a negative number.
3273**
drh0059eae2011-08-08 23:48:40 +00003274** If SQLITE_OK is returned, the caller is responsible for closing
3275** the file descriptor *pFd using close().
3276*/
3277static int openDirectory(const char *zFilename, int *pFd){
3278 int ii;
3279 int fd = -1;
3280 char zDirname[MAX_PATHNAME+1];
3281
3282 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3283 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3284 if( ii>0 ){
3285 zDirname[ii] = '\0';
3286 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3287 if( fd>=0 ){
3288#ifdef FD_CLOEXEC
3289 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3290#endif
3291 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3292 }
3293 }
3294 *pFd = fd;
3295 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3296}
3297
3298/*
drh734c9862008-11-28 15:37:20 +00003299** Make sure all writes to a particular file are committed to disk.
3300**
3301** If dataOnly==0 then both the file itself and its metadata (file
3302** size, access time, etc) are synced. If dataOnly!=0 then only the
3303** file data is synced.
3304**
3305** Under Unix, also make sure that the directory entry for the file
3306** has been created by fsync-ing the directory that contains the file.
3307** If we do not do this and we encounter a power failure, the directory
3308** entry for the journal might not exist after we reboot. The next
3309** SQLite to access the file will not know that the journal exists (because
3310** the directory entry for the journal was never created) and the transaction
3311** will not roll back - possibly leading to database corruption.
3312*/
3313static int unixSync(sqlite3_file *id, int flags){
3314 int rc;
3315 unixFile *pFile = (unixFile*)id;
3316
3317 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3318 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3319
3320 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3321 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3322 || (flags&0x0F)==SQLITE_SYNC_FULL
3323 );
3324
3325 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3326 ** line is to test that doing so does not cause any problems.
3327 */
3328 SimulateDiskfullError( return SQLITE_FULL );
3329
3330 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003331 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003332 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3333 SimulateIOError( rc=1 );
3334 if( rc ){
3335 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003336 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003337 }
drh0059eae2011-08-08 23:48:40 +00003338
3339 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003340 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3341 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003342 */
3343 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3344 int dirfd;
3345 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003346 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003347 rc = osOpenDirectory(pFile->zPath, &dirfd);
3348 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003349 full_fsync(dirfd, 0, 0);
3350 robust_close(pFile, dirfd, __LINE__);
drh734c9862008-11-28 15:37:20 +00003351 }
drh0059eae2011-08-08 23:48:40 +00003352 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003353 }
3354 return rc;
3355}
3356
3357/*
3358** Truncate an open file to a specified size
3359*/
3360static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003361 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003362 int rc;
dan6e09d692010-07-27 18:34:15 +00003363 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003364 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003365
3366 /* If the user has configured a chunk-size for this file, truncate the
3367 ** file so that it consists of an integer number of chunks (i.e. the
3368 ** actual file size after the operation may be larger than the requested
3369 ** size).
3370 */
3371 if( pFile->szChunk ){
3372 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3373 }
3374
drhff812312011-02-23 13:33:46 +00003375 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003376 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003377 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003378 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003379 }else{
drh3313b142009-11-06 04:13:18 +00003380#ifndef NDEBUG
3381 /* If we are doing a normal write to a database file (as opposed to
3382 ** doing a hot-journal rollback or a write to some file other than a
3383 ** normal database file) and we truncate the file to zero length,
3384 ** that effectively updates the change counter. This might happen
3385 ** when restoring a database using the backup API from a zero-length
3386 ** source.
3387 */
dan6e09d692010-07-27 18:34:15 +00003388 if( pFile->inNormalWrite && nByte==0 ){
3389 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003390 }
3391#endif
3392
drh734c9862008-11-28 15:37:20 +00003393 return SQLITE_OK;
3394 }
3395}
3396
3397/*
3398** Determine the current size of a file in bytes
3399*/
3400static int unixFileSize(sqlite3_file *id, i64 *pSize){
3401 int rc;
3402 struct stat buf;
3403 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003404 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003405 SimulateIOError( rc=1 );
3406 if( rc!=0 ){
3407 ((unixFile*)id)->lastErrno = errno;
3408 return SQLITE_IOERR_FSTAT;
3409 }
3410 *pSize = buf.st_size;
3411
drh8af6c222010-05-14 12:43:01 +00003412 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003413 ** writes a single byte into that file in order to work around a bug
3414 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3415 ** layers, we need to report this file size as zero even though it is
3416 ** really 1. Ticket #3260.
3417 */
3418 if( *pSize==1 ) *pSize = 0;
3419
3420
3421 return SQLITE_OK;
3422}
3423
drhd2cb50b2009-01-09 21:41:17 +00003424#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003425/*
3426** Handler for proxy-locking file-control verbs. Defined below in the
3427** proxying locking division.
3428*/
3429static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003430#endif
drh715ff302008-12-03 22:32:44 +00003431
dan502019c2010-07-28 14:26:17 +00003432/*
3433** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3434** file-control operation.
3435**
3436** If the user has configured a chunk-size for this file, it could be
3437** that the file needs to be extended at this point. Otherwise, the
3438** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3439*/
3440static int fcntlSizeHint(unixFile *pFile, i64 nByte){
drh7d2dc712011-07-25 23:25:47 +00003441 { /* preserve indentation of removed "if" */
dan502019c2010-07-28 14:26:17 +00003442 i64 nSize; /* Required file size */
drh7d2dc712011-07-25 23:25:47 +00003443 i64 szChunk; /* Chunk size */
dan502019c2010-07-28 14:26:17 +00003444 struct stat buf; /* Used to hold return values of fstat() */
3445
drh99ab3b12011-03-02 15:09:07 +00003446 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003447
drh7d2dc712011-07-25 23:25:47 +00003448 szChunk = pFile->szChunk;
3449 if( szChunk==0 ){
3450 nSize = nByte;
3451 }else{
3452 nSize = ((nByte+szChunk-1) / szChunk) * szChunk;
3453 }
dan502019c2010-07-28 14:26:17 +00003454 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003455
dan502019c2010-07-28 14:26:17 +00003456#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003457 /* The code below is handling the return value of osFallocate()
3458 ** correctly. posix_fallocate() is defined to "returns zero on success,
3459 ** or an error number on failure". See the manpage for details. */
3460 int err;
drhff812312011-02-23 13:33:46 +00003461 do{
dan661d71a2011-03-30 19:08:03 +00003462 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3463 }while( err==EINTR );
3464 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003465#else
3466 /* If the OS does not have posix_fallocate(), fake it. First use
3467 ** ftruncate() to set the file size, then write a single byte to
3468 ** the last byte in each block within the extended region. This
3469 ** is the same technique used by glibc to implement posix_fallocate()
3470 ** on systems that do not have a real fallocate() system call.
3471 */
3472 int nBlk = buf.st_blksize; /* File-system block size */
3473 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003474
drhff812312011-02-23 13:33:46 +00003475 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003476 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003477 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003478 }
3479 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003480 while( iWrite<nSize ){
3481 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3482 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003483 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003484 }
dan502019c2010-07-28 14:26:17 +00003485#endif
3486 }
3487 }
3488
3489 return SQLITE_OK;
3490}
danielk1977ad94b582007-08-20 06:44:22 +00003491
danielk1977e3026632004-06-22 11:29:02 +00003492/*
drh9e33c2c2007-08-31 18:34:59 +00003493** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003494*/
drhcc6bb3e2007-08-31 16:11:35 +00003495static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003496 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003497 switch( op ){
3498 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003499 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003500 return SQLITE_OK;
3501 }
drh7708e972008-11-29 00:56:52 +00003502 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003503 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003504 return SQLITE_OK;
3505 }
dan6e09d692010-07-27 18:34:15 +00003506 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003507 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003508 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003509 }
drh9ff27ec2010-05-19 19:26:05 +00003510 case SQLITE_FCNTL_SIZE_HINT: {
drhf0b190d2011-07-26 16:03:07 +00003511 return fcntlSizeHint(pFile, *(i64 *)pArg);
3512 }
3513 case SQLITE_FCNTL_PERSIST_WAL: {
3514 int bPersist = *(int*)pArg;
3515 if( bPersist<0 ){
drh253cea52011-07-26 16:23:25 +00003516 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
drhf0b190d2011-07-26 16:03:07 +00003517 }else if( bPersist==0 ){
3518 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
3519 }else{
3520 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
3521 }
3522 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003523 }
drh8f941bc2009-01-14 23:03:40 +00003524#ifndef NDEBUG
3525 /* The pager calls this method to signal that it has done
3526 ** a rollback and that the database is therefore unchanged and
3527 ** it hence it is OK for the transaction change counter to be
3528 ** unchanged.
3529 */
3530 case SQLITE_FCNTL_DB_UNCHANGED: {
3531 ((unixFile*)id)->dbUpdate = 0;
3532 return SQLITE_OK;
3533 }
3534#endif
drhd2cb50b2009-01-09 21:41:17 +00003535#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003536 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003537 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003538 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003539 }
drhd2cb50b2009-01-09 21:41:17 +00003540#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003541 case SQLITE_FCNTL_SYNC_OMITTED: {
3542 return SQLITE_OK; /* A no-op */
3543 }
drh9e33c2c2007-08-31 18:34:59 +00003544 }
drh0b52b7d2011-01-26 19:46:22 +00003545 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003546}
3547
3548/*
danielk1977a3d4c882007-03-23 10:08:38 +00003549** Return the sector size in bytes of the underlying block device for
3550** the specified file. This is almost always 512 bytes, but may be
3551** larger for some devices.
3552**
3553** SQLite code assumes this function cannot fail. It also assumes that
3554** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003555** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003556** same for both.
3557*/
danielk1977397d65f2008-11-19 11:35:39 +00003558static int unixSectorSize(sqlite3_file *NotUsed){
3559 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003560 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003561}
3562
danielk197790949c22007-08-17 16:50:38 +00003563/*
danielk1977397d65f2008-11-19 11:35:39 +00003564** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003565*/
danielk1977397d65f2008-11-19 11:35:39 +00003566static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3567 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003568 return 0;
3569}
3570
drhd9e5c4f2010-05-12 18:01:39 +00003571#ifndef SQLITE_OMIT_WAL
3572
3573
3574/*
drhd91c68f2010-05-14 14:52:25 +00003575** Object used to represent an shared memory buffer.
3576**
3577** When multiple threads all reference the same wal-index, each thread
3578** has its own unixShm object, but they all point to a single instance
3579** of this unixShmNode object. In other words, each wal-index is opened
3580** only once per process.
3581**
3582** Each unixShmNode object is connected to a single unixInodeInfo object.
3583** We could coalesce this object into unixInodeInfo, but that would mean
3584** every open file that does not use shared memory (in other words, most
3585** open files) would have to carry around this extra information. So
3586** the unixInodeInfo object contains a pointer to this unixShmNode object
3587** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003588**
3589** unixMutexHeld() must be true when creating or destroying
3590** this object or while reading or writing the following fields:
3591**
3592** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003593**
3594** The following fields are read-only after the object is created:
3595**
3596** fid
3597** zFilename
3598**
drhd91c68f2010-05-14 14:52:25 +00003599** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003600** unixMutexHeld() is true when reading or writing any other field
3601** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003602*/
drhd91c68f2010-05-14 14:52:25 +00003603struct unixShmNode {
3604 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003605 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003606 char *zFilename; /* Name of the mmapped file */
3607 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003608 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003609 u16 nRegion; /* Size of array apRegion */
3610 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003611 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003612 int nRef; /* Number of unixShm objects pointing to this */
3613 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003614#ifdef SQLITE_DEBUG
3615 u8 exclMask; /* Mask of exclusive locks held */
3616 u8 sharedMask; /* Mask of shared locks held */
3617 u8 nextShmId; /* Next available unixShm.id value */
3618#endif
3619};
3620
3621/*
drhd9e5c4f2010-05-12 18:01:39 +00003622** Structure used internally by this VFS to record the state of an
3623** open shared memory connection.
3624**
drhd91c68f2010-05-14 14:52:25 +00003625** The following fields are initialized when this object is created and
3626** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003627**
drhd91c68f2010-05-14 14:52:25 +00003628** unixShm.pFile
3629** unixShm.id
3630**
3631** All other fields are read/write. The unixShm.pFile->mutex must be held
3632** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003633*/
3634struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003635 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3636 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003637 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003638 u16 sharedMask; /* Mask of shared locks held */
3639 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003640#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003641 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003642#endif
3643};
3644
3645/*
drhd9e5c4f2010-05-12 18:01:39 +00003646** Constants used for locking
3647*/
drhbd9676c2010-06-23 17:58:38 +00003648#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003649#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003650
drhd9e5c4f2010-05-12 18:01:39 +00003651/*
drh73b64e42010-05-30 19:55:15 +00003652** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003653**
3654** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3655** otherwise.
3656*/
3657static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003658 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3659 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003660 int ofst, /* First byte of the locking range */
3661 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003662){
3663 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003664 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003665
drhd91c68f2010-05-14 14:52:25 +00003666 /* Access to the unixShmNode object is serialized by the caller */
3667 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003668
drh73b64e42010-05-30 19:55:15 +00003669 /* Shared locks never span more than one byte */
3670 assert( n==1 || lockType!=F_RDLCK );
3671
3672 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003673 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003674
drh3cb93392011-03-12 18:10:44 +00003675 if( pShmNode->h>=0 ){
3676 /* Initialize the locking parameters */
3677 memset(&f, 0, sizeof(f));
3678 f.l_type = lockType;
3679 f.l_whence = SEEK_SET;
3680 f.l_start = ofst;
3681 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003682
drh3cb93392011-03-12 18:10:44 +00003683 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3684 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3685 }
drhd9e5c4f2010-05-12 18:01:39 +00003686
3687 /* Update the global lock state and do debug tracing */
3688#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003689 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003690 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003691 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003692 if( rc==SQLITE_OK ){
3693 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003694 OSTRACE(("unlock %d ok", ofst));
3695 pShmNode->exclMask &= ~mask;
3696 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003697 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003698 OSTRACE(("read-lock %d ok", ofst));
3699 pShmNode->exclMask &= ~mask;
3700 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003701 }else{
3702 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003703 OSTRACE(("write-lock %d ok", ofst));
3704 pShmNode->exclMask |= mask;
3705 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003706 }
3707 }else{
3708 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003709 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003710 }else if( lockType==F_RDLCK ){
3711 OSTRACE(("read-lock failed"));
3712 }else{
3713 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003714 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003715 }
3716 }
drh20e1f082010-05-31 16:10:12 +00003717 OSTRACE((" - afterwards %03x,%03x\n",
3718 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003719 }
drhd9e5c4f2010-05-12 18:01:39 +00003720#endif
3721
3722 return rc;
3723}
3724
drhd9e5c4f2010-05-12 18:01:39 +00003725
3726/*
drhd91c68f2010-05-14 14:52:25 +00003727** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003728**
3729** This is not a VFS shared-memory method; it is a utility function called
3730** by VFS shared-memory methods.
3731*/
drhd91c68f2010-05-14 14:52:25 +00003732static void unixShmPurge(unixFile *pFd){
3733 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003734 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003735 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003736 int i;
drhd91c68f2010-05-14 14:52:25 +00003737 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003738 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003739 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003740 if( p->h>=0 ){
3741 munmap(p->apRegion[i], p->szRegion);
3742 }else{
3743 sqlite3_free(p->apRegion[i]);
3744 }
dan13a3cb82010-06-11 19:04:21 +00003745 }
dan18801912010-06-14 14:07:50 +00003746 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003747 if( p->h>=0 ){
3748 robust_close(pFd, p->h, __LINE__);
3749 p->h = -1;
3750 }
drhd91c68f2010-05-14 14:52:25 +00003751 p->pInode->pShmNode = 0;
3752 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003753 }
3754}
3755
3756/*
danda9fe0c2010-07-13 18:44:03 +00003757** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003758** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003759**
drh7234c6d2010-06-19 15:10:09 +00003760** The file used to implement shared-memory is in the same directory
3761** as the open database file and has the same name as the open database
3762** file with the "-shm" suffix added. For example, if the database file
3763** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003764** for shared memory will be called "/home/user1/config.db-shm".
3765**
3766** Another approach to is to use files in /dev/shm or /dev/tmp or an
3767** some other tmpfs mount. But if a file in a different directory
3768** from the database file is used, then differing access permissions
3769** or a chroot() might cause two different processes on the same
3770** database to end up using different files for shared memory -
3771** meaning that their memory would not really be shared - resulting
3772** in database corruption. Nevertheless, this tmpfs file usage
3773** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3774** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3775** option results in an incompatible build of SQLite; builds of SQLite
3776** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3777** same database file at the same time, database corruption will likely
3778** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3779** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003780**
3781** When opening a new shared-memory file, if no other instances of that
3782** file are currently open, in this process or in other processes, then
3783** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003784**
3785** If the original database file (pDbFd) is using the "unix-excl" VFS
3786** that means that an exclusive lock is held on the database file and
3787** that no other processes are able to read or write the database. In
3788** that case, we do not really need shared memory. No shared memory
3789** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003790*/
danda9fe0c2010-07-13 18:44:03 +00003791static int unixOpenSharedMemory(unixFile *pDbFd){
3792 struct unixShm *p = 0; /* The connection to be opened */
3793 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3794 int rc; /* Result code */
3795 unixInodeInfo *pInode; /* The inode of fd */
3796 char *zShmFilename; /* Name of the file used for SHM */
3797 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003798
danda9fe0c2010-07-13 18:44:03 +00003799 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003800 p = sqlite3_malloc( sizeof(*p) );
3801 if( p==0 ) return SQLITE_NOMEM;
3802 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003803 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003804
danda9fe0c2010-07-13 18:44:03 +00003805 /* Check to see if a unixShmNode object already exists. Reuse an existing
3806 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003807 */
3808 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003809 pInode = pDbFd->pInode;
3810 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003811 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003812 struct stat sStat; /* fstat() info for database file */
3813
3814 /* Call fstat() to figure out the permissions on the database file. If
3815 ** a new *-shm file is created, an attempt will be made to create it
3816 ** with the same permissions. The actual permissions the file is created
3817 ** with are subject to the current umask setting.
3818 */
drh3cb93392011-03-12 18:10:44 +00003819 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003820 rc = SQLITE_IOERR_FSTAT;
3821 goto shm_open_err;
3822 }
3823
drha4ced192010-07-15 18:32:40 +00003824#ifdef SQLITE_SHM_DIRECTORY
3825 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3826#else
drh7234c6d2010-06-19 15:10:09 +00003827 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003828#endif
drh7234c6d2010-06-19 15:10:09 +00003829 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003830 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003831 rc = SQLITE_NOMEM;
3832 goto shm_open_err;
3833 }
drhd91c68f2010-05-14 14:52:25 +00003834 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003835 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003836#ifdef SQLITE_SHM_DIRECTORY
3837 sqlite3_snprintf(nShmFilename, zShmFilename,
3838 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3839 (u32)sStat.st_ino, (u32)sStat.st_dev);
3840#else
drh7234c6d2010-06-19 15:10:09 +00003841 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003842 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003843#endif
drhd91c68f2010-05-14 14:52:25 +00003844 pShmNode->h = -1;
3845 pDbFd->pInode->pShmNode = pShmNode;
3846 pShmNode->pInode = pDbFd->pInode;
3847 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3848 if( pShmNode->mutex==0 ){
3849 rc = SQLITE_NOMEM;
3850 goto shm_open_err;
3851 }
drhd9e5c4f2010-05-12 18:01:39 +00003852
drh3cb93392011-03-12 18:10:44 +00003853 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003854 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3855 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003856 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003857 const char *zRO;
3858 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003859 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003860 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3861 (sStat.st_mode & 0777));
3862 pShmNode->isReadonly = 1;
3863 }
3864 if( pShmNode->h<0 ){
3865 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3866 goto shm_open_err;
3867 }
drhd9e5c4f2010-05-12 18:01:39 +00003868 }
drh3cb93392011-03-12 18:10:44 +00003869
3870 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003871 ** If not, truncate the file to zero length.
3872 */
3873 rc = SQLITE_OK;
3874 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3875 if( robust_ftruncate(pShmNode->h, 0) ){
3876 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003877 }
3878 }
drh66dfec8b2011-06-01 20:01:49 +00003879 if( rc==SQLITE_OK ){
3880 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3881 }
3882 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003883 }
drhd9e5c4f2010-05-12 18:01:39 +00003884 }
3885
drhd91c68f2010-05-14 14:52:25 +00003886 /* Make the new connection a child of the unixShmNode */
3887 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003888#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003889 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003890#endif
drhd91c68f2010-05-14 14:52:25 +00003891 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003892 pDbFd->pShm = p;
3893 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003894
3895 /* The reference count on pShmNode has already been incremented under
3896 ** the cover of the unixEnterMutex() mutex and the pointer from the
3897 ** new (struct unixShm) object to the pShmNode has been set. All that is
3898 ** left to do is to link the new object into the linked list starting
3899 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3900 ** mutex.
3901 */
3902 sqlite3_mutex_enter(pShmNode->mutex);
3903 p->pNext = pShmNode->pFirst;
3904 pShmNode->pFirst = p;
3905 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003906 return SQLITE_OK;
3907
3908 /* Jump here on any error */
3909shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003910 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003911 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003912 unixLeaveMutex();
3913 return rc;
3914}
3915
3916/*
danda9fe0c2010-07-13 18:44:03 +00003917** This function is called to obtain a pointer to region iRegion of the
3918** shared-memory associated with the database file fd. Shared-memory regions
3919** are numbered starting from zero. Each shared-memory region is szRegion
3920** bytes in size.
3921**
3922** If an error occurs, an error code is returned and *pp is set to NULL.
3923**
3924** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3925** region has not been allocated (by any client, including one running in a
3926** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3927** bExtend is non-zero and the requested shared-memory region has not yet
3928** been allocated, it is allocated by this function.
3929**
3930** If the shared-memory region has already been allocated or is allocated by
3931** this call as described above, then it is mapped into this processes
3932** address space (if it is not already), *pp is set to point to the mapped
3933** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003934*/
danda9fe0c2010-07-13 18:44:03 +00003935static int unixShmMap(
3936 sqlite3_file *fd, /* Handle open on database file */
3937 int iRegion, /* Region to retrieve */
3938 int szRegion, /* Size of regions */
3939 int bExtend, /* True to extend file if necessary */
3940 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003941){
danda9fe0c2010-07-13 18:44:03 +00003942 unixFile *pDbFd = (unixFile*)fd;
3943 unixShm *p;
3944 unixShmNode *pShmNode;
3945 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003946
danda9fe0c2010-07-13 18:44:03 +00003947 /* If the shared-memory file has not yet been opened, open it now. */
3948 if( pDbFd->pShm==0 ){
3949 rc = unixOpenSharedMemory(pDbFd);
3950 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003951 }
drhd9e5c4f2010-05-12 18:01:39 +00003952
danda9fe0c2010-07-13 18:44:03 +00003953 p = pDbFd->pShm;
3954 pShmNode = p->pShmNode;
3955 sqlite3_mutex_enter(pShmNode->mutex);
3956 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003957 assert( pShmNode->pInode==pDbFd->pInode );
3958 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3959 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003960
3961 if( pShmNode->nRegion<=iRegion ){
3962 char **apNew; /* New apRegion[] array */
3963 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3964 struct stat sStat; /* Used by fstat() */
3965
3966 pShmNode->szRegion = szRegion;
3967
drh3cb93392011-03-12 18:10:44 +00003968 if( pShmNode->h>=0 ){
3969 /* The requested region is not mapped into this processes address space.
3970 ** Check to see if it has been allocated (i.e. if the wal-index file is
3971 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003972 */
drh3cb93392011-03-12 18:10:44 +00003973 if( osFstat(pShmNode->h, &sStat) ){
3974 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003975 goto shmpage_out;
3976 }
drh3cb93392011-03-12 18:10:44 +00003977
3978 if( sStat.st_size<nByte ){
3979 /* The requested memory region does not exist. If bExtend is set to
3980 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3981 **
3982 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3983 ** the requested memory region.
3984 */
3985 if( !bExtend ) goto shmpage_out;
3986 if( robust_ftruncate(pShmNode->h, nByte) ){
3987 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3988 pShmNode->zFilename);
3989 goto shmpage_out;
3990 }
3991 }
danda9fe0c2010-07-13 18:44:03 +00003992 }
3993
3994 /* Map the requested memory region into this processes address space. */
3995 apNew = (char **)sqlite3_realloc(
3996 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3997 );
3998 if( !apNew ){
3999 rc = SQLITE_IOERR_NOMEM;
4000 goto shmpage_out;
4001 }
4002 pShmNode->apRegion = apNew;
4003 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004004 void *pMem;
4005 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004006 pMem = mmap(0, szRegion,
4007 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004008 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4009 );
4010 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004011 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004012 goto shmpage_out;
4013 }
4014 }else{
4015 pMem = sqlite3_malloc(szRegion);
4016 if( pMem==0 ){
4017 rc = SQLITE_NOMEM;
4018 goto shmpage_out;
4019 }
4020 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004021 }
4022 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4023 pShmNode->nRegion++;
4024 }
4025 }
4026
4027shmpage_out:
4028 if( pShmNode->nRegion>iRegion ){
4029 *pp = pShmNode->apRegion[iRegion];
4030 }else{
4031 *pp = 0;
4032 }
drh66dfec8b2011-06-01 20:01:49 +00004033 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004034 sqlite3_mutex_leave(pShmNode->mutex);
4035 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004036}
4037
4038/*
drhd9e5c4f2010-05-12 18:01:39 +00004039** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004040**
4041** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4042** different here than in posix. In xShmLock(), one can go from unlocked
4043** to shared and back or from unlocked to exclusive and back. But one may
4044** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004045*/
4046static int unixShmLock(
4047 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004048 int ofst, /* First lock to acquire or release */
4049 int n, /* Number of locks to acquire or release */
4050 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004051){
drh73b64e42010-05-30 19:55:15 +00004052 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4053 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4054 unixShm *pX; /* For looping over all siblings */
4055 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4056 int rc = SQLITE_OK; /* Result code */
4057 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004058
drhd91c68f2010-05-14 14:52:25 +00004059 assert( pShmNode==pDbFd->pInode->pShmNode );
4060 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004061 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004062 assert( n>=1 );
4063 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4064 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4065 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4066 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4067 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004068 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4069 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004070
drhc99597c2010-05-31 01:41:15 +00004071 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004072 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004073 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004074 if( flags & SQLITE_SHM_UNLOCK ){
4075 u16 allMask = 0; /* Mask of locks held by siblings */
4076
4077 /* See if any siblings hold this same lock */
4078 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4079 if( pX==p ) continue;
4080 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4081 allMask |= pX->sharedMask;
4082 }
4083
4084 /* Unlock the system-level locks */
4085 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004086 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004087 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004088 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004089 }
drh73b64e42010-05-30 19:55:15 +00004090
4091 /* Undo the local locks */
4092 if( rc==SQLITE_OK ){
4093 p->exclMask &= ~mask;
4094 p->sharedMask &= ~mask;
4095 }
4096 }else if( flags & SQLITE_SHM_SHARED ){
4097 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4098
4099 /* Find out which shared locks are already held by sibling connections.
4100 ** If any sibling already holds an exclusive lock, go ahead and return
4101 ** SQLITE_BUSY.
4102 */
4103 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004104 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004105 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004106 break;
4107 }
4108 allShared |= pX->sharedMask;
4109 }
4110
4111 /* Get shared locks at the system level, if necessary */
4112 if( rc==SQLITE_OK ){
4113 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004114 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004115 }else{
drh73b64e42010-05-30 19:55:15 +00004116 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004117 }
drhd9e5c4f2010-05-12 18:01:39 +00004118 }
drh73b64e42010-05-30 19:55:15 +00004119
4120 /* Get the local shared locks */
4121 if( rc==SQLITE_OK ){
4122 p->sharedMask |= mask;
4123 }
4124 }else{
4125 /* Make sure no sibling connections hold locks that will block this
4126 ** lock. If any do, return SQLITE_BUSY right away.
4127 */
4128 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004129 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4130 rc = SQLITE_BUSY;
4131 break;
4132 }
4133 }
4134
4135 /* Get the exclusive locks at the system level. Then if successful
4136 ** also mark the local connection as being locked.
4137 */
4138 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004139 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004140 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004141 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004142 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004143 }
drhd9e5c4f2010-05-12 18:01:39 +00004144 }
4145 }
drhd91c68f2010-05-14 14:52:25 +00004146 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004147 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4148 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004149 return rc;
4150}
4151
drh286a2882010-05-20 23:51:06 +00004152/*
4153** Implement a memory barrier or memory fence on shared memory.
4154**
4155** All loads and stores begun before the barrier must complete before
4156** any load or store begun after the barrier.
4157*/
4158static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004159 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004160){
drhff828942010-06-26 21:34:06 +00004161 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004162 unixEnterMutex();
4163 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004164}
4165
dan18801912010-06-14 14:07:50 +00004166/*
danda9fe0c2010-07-13 18:44:03 +00004167** Close a connection to shared-memory. Delete the underlying
4168** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004169**
4170** If there is no shared memory associated with the connection then this
4171** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004172*/
danda9fe0c2010-07-13 18:44:03 +00004173static int unixShmUnmap(
4174 sqlite3_file *fd, /* The underlying database file */
4175 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004176){
danda9fe0c2010-07-13 18:44:03 +00004177 unixShm *p; /* The connection to be closed */
4178 unixShmNode *pShmNode; /* The underlying shared-memory file */
4179 unixShm **pp; /* For looping over sibling connections */
4180 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004181
danda9fe0c2010-07-13 18:44:03 +00004182 pDbFd = (unixFile*)fd;
4183 p = pDbFd->pShm;
4184 if( p==0 ) return SQLITE_OK;
4185 pShmNode = p->pShmNode;
4186
4187 assert( pShmNode==pDbFd->pInode->pShmNode );
4188 assert( pShmNode->pInode==pDbFd->pInode );
4189
4190 /* Remove connection p from the set of connections associated
4191 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004192 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004193 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4194 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004195
danda9fe0c2010-07-13 18:44:03 +00004196 /* Free the connection p */
4197 sqlite3_free(p);
4198 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004199 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004200
4201 /* If pShmNode->nRef has reached 0, then close the underlying
4202 ** shared-memory file, too */
4203 unixEnterMutex();
4204 assert( pShmNode->nRef>0 );
4205 pShmNode->nRef--;
4206 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004207 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004208 unixShmPurge(pDbFd);
4209 }
4210 unixLeaveMutex();
4211
4212 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004213}
drh286a2882010-05-20 23:51:06 +00004214
danda9fe0c2010-07-13 18:44:03 +00004215
drhd9e5c4f2010-05-12 18:01:39 +00004216#else
drh6b017cc2010-06-14 18:01:46 +00004217# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004218# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004219# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004220# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004221#endif /* #ifndef SQLITE_OMIT_WAL */
4222
drh734c9862008-11-28 15:37:20 +00004223/*
4224** Here ends the implementation of all sqlite3_file methods.
4225**
4226********************** End sqlite3_file Methods *******************************
4227******************************************************************************/
4228
4229/*
drh6b9d6dd2008-12-03 19:34:47 +00004230** This division contains definitions of sqlite3_io_methods objects that
4231** implement various file locking strategies. It also contains definitions
4232** of "finder" functions. A finder-function is used to locate the appropriate
4233** sqlite3_io_methods object for a particular database file. The pAppData
4234** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4235** the correct finder-function for that VFS.
4236**
4237** Most finder functions return a pointer to a fixed sqlite3_io_methods
4238** object. The only interesting finder-function is autolockIoFinder, which
4239** looks at the filesystem type and tries to guess the best locking
4240** strategy from that.
4241**
drh1875f7a2008-12-08 18:19:17 +00004242** For finder-funtion F, two objects are created:
4243**
4244** (1) The real finder-function named "FImpt()".
4245**
dane946c392009-08-22 11:39:46 +00004246** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004247**
4248**
4249** A pointer to the F pointer is used as the pAppData value for VFS
4250** objects. We have to do this instead of letting pAppData point
4251** directly at the finder-function since C90 rules prevent a void*
4252** from be cast into a function pointer.
4253**
drh6b9d6dd2008-12-03 19:34:47 +00004254**
drh7708e972008-11-29 00:56:52 +00004255** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004256**
drh7708e972008-11-29 00:56:52 +00004257** * A constant sqlite3_io_methods object call METHOD that has locking
4258** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4259**
4260** * An I/O method finder function called FINDER that returns a pointer
4261** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004262*/
drhd9e5c4f2010-05-12 18:01:39 +00004263#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004264static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004265 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004266 CLOSE, /* xClose */ \
4267 unixRead, /* xRead */ \
4268 unixWrite, /* xWrite */ \
4269 unixTruncate, /* xTruncate */ \
4270 unixSync, /* xSync */ \
4271 unixFileSize, /* xFileSize */ \
4272 LOCK, /* xLock */ \
4273 UNLOCK, /* xUnlock */ \
4274 CKLOCK, /* xCheckReservedLock */ \
4275 unixFileControl, /* xFileControl */ \
4276 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004277 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004278 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004279 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004280 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004281 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004282}; \
drh0c2694b2009-09-03 16:23:44 +00004283static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4284 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004285 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004286} \
drh0c2694b2009-09-03 16:23:44 +00004287static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004288 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004289
4290/*
4291** Here are all of the sqlite3_io_methods objects for each of the
4292** locking strategies. Functions that return pointers to these methods
4293** are also created.
4294*/
4295IOMETHODS(
4296 posixIoFinder, /* Finder function name */
4297 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004298 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004299 unixClose, /* xClose method */
4300 unixLock, /* xLock method */
4301 unixUnlock, /* xUnlock method */
4302 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004303)
drh7708e972008-11-29 00:56:52 +00004304IOMETHODS(
4305 nolockIoFinder, /* Finder function name */
4306 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004307 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004308 nolockClose, /* xClose method */
4309 nolockLock, /* xLock method */
4310 nolockUnlock, /* xUnlock method */
4311 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004312)
drh7708e972008-11-29 00:56:52 +00004313IOMETHODS(
4314 dotlockIoFinder, /* Finder function name */
4315 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004316 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004317 dotlockClose, /* xClose method */
4318 dotlockLock, /* xLock method */
4319 dotlockUnlock, /* xUnlock method */
4320 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004321)
drh7708e972008-11-29 00:56:52 +00004322
chw78a13182009-04-07 05:35:03 +00004323#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004324IOMETHODS(
4325 flockIoFinder, /* Finder function name */
4326 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004327 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004328 flockClose, /* xClose method */
4329 flockLock, /* xLock method */
4330 flockUnlock, /* xUnlock method */
4331 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004332)
drh7708e972008-11-29 00:56:52 +00004333#endif
4334
drh6c7d5c52008-11-21 20:32:33 +00004335#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004336IOMETHODS(
4337 semIoFinder, /* Finder function name */
4338 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004339 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004340 semClose, /* xClose method */
4341 semLock, /* xLock method */
4342 semUnlock, /* xUnlock method */
4343 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004344)
aswiftaebf4132008-11-21 00:10:35 +00004345#endif
drh7708e972008-11-29 00:56:52 +00004346
drhd2cb50b2009-01-09 21:41:17 +00004347#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004348IOMETHODS(
4349 afpIoFinder, /* Finder function name */
4350 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004351 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004352 afpClose, /* xClose method */
4353 afpLock, /* xLock method */
4354 afpUnlock, /* xUnlock method */
4355 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004356)
drh715ff302008-12-03 22:32:44 +00004357#endif
4358
4359/*
4360** The proxy locking method is a "super-method" in the sense that it
4361** opens secondary file descriptors for the conch and lock files and
4362** it uses proxy, dot-file, AFP, and flock() locking methods on those
4363** secondary files. For this reason, the division that implements
4364** proxy locking is located much further down in the file. But we need
4365** to go ahead and define the sqlite3_io_methods and finder function
4366** for proxy locking here. So we forward declare the I/O methods.
4367*/
drhd2cb50b2009-01-09 21:41:17 +00004368#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004369static int proxyClose(sqlite3_file*);
4370static int proxyLock(sqlite3_file*, int);
4371static int proxyUnlock(sqlite3_file*, int);
4372static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004373IOMETHODS(
4374 proxyIoFinder, /* Finder function name */
4375 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004376 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004377 proxyClose, /* xClose method */
4378 proxyLock, /* xLock method */
4379 proxyUnlock, /* xUnlock method */
4380 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004381)
aswiftaebf4132008-11-21 00:10:35 +00004382#endif
drh7708e972008-11-29 00:56:52 +00004383
drh7ed97b92010-01-20 13:07:21 +00004384/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4385#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4386IOMETHODS(
4387 nfsIoFinder, /* Finder function name */
4388 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004389 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004390 unixClose, /* xClose method */
4391 unixLock, /* xLock method */
4392 nfsUnlock, /* xUnlock method */
4393 unixCheckReservedLock /* xCheckReservedLock method */
4394)
4395#endif
drh7708e972008-11-29 00:56:52 +00004396
drhd2cb50b2009-01-09 21:41:17 +00004397#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004398/*
drh6b9d6dd2008-12-03 19:34:47 +00004399** This "finder" function attempts to determine the best locking strategy
4400** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004401** object that implements that strategy.
4402**
4403** This is for MacOSX only.
4404*/
drh1875f7a2008-12-08 18:19:17 +00004405static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004406 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004407 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004408){
4409 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004410 const char *zFilesystem; /* Filesystem type name */
4411 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004412 } aMap[] = {
4413 { "hfs", &posixIoMethods },
4414 { "ufs", &posixIoMethods },
4415 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004416 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004417 { "webdav", &nolockIoMethods },
4418 { 0, 0 }
4419 };
4420 int i;
4421 struct statfs fsInfo;
4422 struct flock lockInfo;
4423
4424 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004425 /* If filePath==NULL that means we are dealing with a transient file
4426 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004427 return &nolockIoMethods;
4428 }
4429 if( statfs(filePath, &fsInfo) != -1 ){
4430 if( fsInfo.f_flags & MNT_RDONLY ){
4431 return &nolockIoMethods;
4432 }
4433 for(i=0; aMap[i].zFilesystem; i++){
4434 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4435 return aMap[i].pMethods;
4436 }
4437 }
4438 }
4439
4440 /* Default case. Handles, amongst others, "nfs".
4441 ** Test byte-range lock using fcntl(). If the call succeeds,
4442 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004443 */
drh7708e972008-11-29 00:56:52 +00004444 lockInfo.l_len = 1;
4445 lockInfo.l_start = 0;
4446 lockInfo.l_whence = SEEK_SET;
4447 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004448 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004449 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4450 return &nfsIoMethods;
4451 } else {
4452 return &posixIoMethods;
4453 }
drh7708e972008-11-29 00:56:52 +00004454 }else{
4455 return &dotlockIoMethods;
4456 }
4457}
drh0c2694b2009-09-03 16:23:44 +00004458static const sqlite3_io_methods
4459 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004460
drhd2cb50b2009-01-09 21:41:17 +00004461#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004462
chw78a13182009-04-07 05:35:03 +00004463#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4464/*
4465** This "finder" function attempts to determine the best locking strategy
4466** for the database file "filePath". It then returns the sqlite3_io_methods
4467** object that implements that strategy.
4468**
4469** This is for VXWorks only.
4470*/
4471static const sqlite3_io_methods *autolockIoFinderImpl(
4472 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004473 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004474){
4475 struct flock lockInfo;
4476
4477 if( !filePath ){
4478 /* If filePath==NULL that means we are dealing with a transient file
4479 ** that does not need to be locked. */
4480 return &nolockIoMethods;
4481 }
4482
4483 /* Test if fcntl() is supported and use POSIX style locks.
4484 ** Otherwise fall back to the named semaphore method.
4485 */
4486 lockInfo.l_len = 1;
4487 lockInfo.l_start = 0;
4488 lockInfo.l_whence = SEEK_SET;
4489 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004490 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004491 return &posixIoMethods;
4492 }else{
4493 return &semIoMethods;
4494 }
4495}
drh0c2694b2009-09-03 16:23:44 +00004496static const sqlite3_io_methods
4497 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004498
4499#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4500
drh7708e972008-11-29 00:56:52 +00004501/*
4502** An abstract type for a pointer to a IO method finder function:
4503*/
drh0c2694b2009-09-03 16:23:44 +00004504typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004505
aswiftaebf4132008-11-21 00:10:35 +00004506
drh734c9862008-11-28 15:37:20 +00004507/****************************************************************************
4508**************************** sqlite3_vfs methods ****************************
4509**
4510** This division contains the implementation of methods on the
4511** sqlite3_vfs object.
4512*/
4513
danielk1977a3d4c882007-03-23 10:08:38 +00004514/*
danielk1977e339d652008-06-28 11:23:00 +00004515** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004516*/
4517static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004518 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004519 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004520 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004521 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004522 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004523 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004524 int isDelete, /* Delete on close if true */
4525 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004526){
drh7708e972008-11-29 00:56:52 +00004527 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004528 unixFile *pNew = (unixFile *)pId;
4529 int rc = SQLITE_OK;
4530
drh8af6c222010-05-14 12:43:01 +00004531 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004532
dane946c392009-08-22 11:39:46 +00004533 /* Parameter isDelete is only used on vxworks. Express this explicitly
4534 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004535 */
drh7708e972008-11-29 00:56:52 +00004536 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004537
dan00157392010-10-05 11:33:15 +00004538 /* Usually the path zFilename should not be a relative pathname. The
4539 ** exception is when opening the proxy "conch" file in builds that
4540 ** include the special Apple locking styles.
4541 */
dan00157392010-10-05 11:33:15 +00004542#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004543 assert( zFilename==0 || zFilename[0]=='/'
4544 || pVfs->pAppData==(void*)&autolockIoFinder );
4545#else
4546 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004547#endif
dan00157392010-10-05 11:33:15 +00004548
drh308c2a52010-05-14 11:30:18 +00004549 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004550 pNew->h = h;
drhd9e5c4f2010-05-12 18:01:39 +00004551 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004552 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4553 pNew->ctrlFlags = UNIXFILE_EXCL;
4554 }else{
4555 pNew->ctrlFlags = 0;
4556 }
drh77197112011-03-15 19:08:48 +00004557 if( isReadOnly ){
4558 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4559 }
drh0059eae2011-08-08 23:48:40 +00004560 if( syncDir ){
4561 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4562 }
drh339eb0b2008-03-07 15:34:11 +00004563
drh6c7d5c52008-11-21 20:32:33 +00004564#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004565 pNew->pId = vxworksFindFileId(zFilename);
4566 if( pNew->pId==0 ){
4567 noLock = 1;
4568 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004569 }
4570#endif
4571
drhda0e7682008-07-30 15:27:54 +00004572 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004573 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004574 }else{
drh0c2694b2009-09-03 16:23:44 +00004575 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004576#if SQLITE_ENABLE_LOCKING_STYLE
4577 /* Cache zFilename in the locking context (AFP and dotlock override) for
4578 ** proxyLock activation is possible (remote proxy is based on db name)
4579 ** zFilename remains valid until file is closed, to support */
4580 pNew->lockingContext = (void*)zFilename;
4581#endif
drhda0e7682008-07-30 15:27:54 +00004582 }
danielk1977e339d652008-06-28 11:23:00 +00004583
drh7ed97b92010-01-20 13:07:21 +00004584 if( pLockingStyle == &posixIoMethods
4585#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4586 || pLockingStyle == &nfsIoMethods
4587#endif
4588 ){
drh7708e972008-11-29 00:56:52 +00004589 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004590 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004591 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004592 /* If an error occured in findInodeInfo(), close the file descriptor
4593 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004594 ** in two scenarios:
4595 **
4596 ** (a) A call to fstat() failed.
4597 ** (b) A malloc failed.
4598 **
4599 ** Scenario (b) may only occur if the process is holding no other
4600 ** file descriptors open on the same file. If there were other file
4601 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004602 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004603 ** handle h - as it is guaranteed that no posix locks will be released
4604 ** by doing so.
4605 **
4606 ** If scenario (a) caused the error then things are not so safe. The
4607 ** implicit assumption here is that if fstat() fails, things are in
4608 ** such bad shape that dropping a lock or two doesn't matter much.
4609 */
drh0e9365c2011-03-02 02:08:13 +00004610 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004611 h = -1;
4612 }
drh7708e972008-11-29 00:56:52 +00004613 unixLeaveMutex();
4614 }
danielk1977e339d652008-06-28 11:23:00 +00004615
drhd2cb50b2009-01-09 21:41:17 +00004616#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004617 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004618 /* AFP locking uses the file path so it needs to be included in
4619 ** the afpLockingContext.
4620 */
4621 afpLockingContext *pCtx;
4622 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4623 if( pCtx==0 ){
4624 rc = SQLITE_NOMEM;
4625 }else{
4626 /* NB: zFilename exists and remains valid until the file is closed
4627 ** according to requirement F11141. So we do not need to make a
4628 ** copy of the filename. */
4629 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004630 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004631 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004632 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004633 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004634 if( rc!=SQLITE_OK ){
4635 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004636 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004637 h = -1;
4638 }
drh7708e972008-11-29 00:56:52 +00004639 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004640 }
drh7708e972008-11-29 00:56:52 +00004641 }
4642#endif
danielk1977e339d652008-06-28 11:23:00 +00004643
drh7708e972008-11-29 00:56:52 +00004644 else if( pLockingStyle == &dotlockIoMethods ){
4645 /* Dotfile locking uses the file path so it needs to be included in
4646 ** the dotlockLockingContext
4647 */
4648 char *zLockFile;
4649 int nFilename;
drhea678832008-12-10 19:26:22 +00004650 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004651 zLockFile = (char *)sqlite3_malloc(nFilename);
4652 if( zLockFile==0 ){
4653 rc = SQLITE_NOMEM;
4654 }else{
4655 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004656 }
drh7708e972008-11-29 00:56:52 +00004657 pNew->lockingContext = zLockFile;
4658 }
danielk1977e339d652008-06-28 11:23:00 +00004659
drh6c7d5c52008-11-21 20:32:33 +00004660#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004661 else if( pLockingStyle == &semIoMethods ){
4662 /* Named semaphore locking uses the file path so it needs to be
4663 ** included in the semLockingContext
4664 */
4665 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004666 rc = findInodeInfo(pNew, &pNew->pInode);
4667 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4668 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004669 int n;
drh2238dcc2009-08-27 17:56:20 +00004670 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004671 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004672 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004673 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004674 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4675 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004676 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004677 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004678 }
chw97185482008-11-17 08:05:31 +00004679 }
drh7708e972008-11-29 00:56:52 +00004680 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004681 }
drh7708e972008-11-29 00:56:52 +00004682#endif
aswift5b1a2562008-08-22 00:22:35 +00004683
4684 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004685#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004686 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004687 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004688 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004689 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004690 isDelete = 0;
4691 }
4692 pNew->isDelete = isDelete;
4693#endif
danielk1977e339d652008-06-28 11:23:00 +00004694 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004695 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004696 }else{
drh7708e972008-11-29 00:56:52 +00004697 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004698 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004699 }
danielk1977e339d652008-06-28 11:23:00 +00004700 return rc;
drh054889e2005-11-30 03:20:31 +00004701}
drh9c06c952005-11-26 00:25:00 +00004702
danielk1977ad94b582007-08-20 06:44:22 +00004703/*
drh8b3cf822010-06-01 21:02:51 +00004704** Return the name of a directory in which to put temporary files.
4705** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004706*/
drh7234c6d2010-06-19 15:10:09 +00004707static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004708 static const char *azDirs[] = {
4709 0,
aswiftaebf4132008-11-21 00:10:35 +00004710 0,
danielk197717b90b52008-06-06 11:11:25 +00004711 "/var/tmp",
4712 "/usr/tmp",
4713 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004714 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004715 };
drh8b3cf822010-06-01 21:02:51 +00004716 unsigned int i;
4717 struct stat buf;
4718 const char *zDir = 0;
4719
4720 azDirs[0] = sqlite3_temp_directory;
4721 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004722 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004723 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004724 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004725 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004726 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004727 break;
4728 }
4729 return zDir;
4730}
4731
4732/*
4733** Create a temporary file name in zBuf. zBuf must be allocated
4734** by the calling process and must be big enough to hold at least
4735** pVfs->mxPathname bytes.
4736*/
4737static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004738 static const unsigned char zChars[] =
4739 "abcdefghijklmnopqrstuvwxyz"
4740 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4741 "0123456789";
drh41022642008-11-21 00:24:42 +00004742 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004743 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004744
4745 /* It's odd to simulate an io-error here, but really this is just
4746 ** using the io-error infrastructure to test that SQLite handles this
4747 ** function failing.
4748 */
4749 SimulateIOError( return SQLITE_IOERR );
4750
drh7234c6d2010-06-19 15:10:09 +00004751 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004752 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004753
4754 /* Check that the output buffer is large enough for the temporary file
4755 ** name. If it is not, return SQLITE_ERROR.
4756 */
danielk197700e13612008-11-17 19:18:54 +00004757 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004758 return SQLITE_ERROR;
4759 }
4760
4761 do{
4762 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004763 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004764 sqlite3_randomness(15, &zBuf[j]);
4765 for(i=0; i<15; i++, j++){
4766 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4767 }
4768 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004769 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004770 return SQLITE_OK;
4771}
4772
drhd2cb50b2009-01-09 21:41:17 +00004773#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004774/*
4775** Routine to transform a unixFile into a proxy-locking unixFile.
4776** Implementation in the proxy-lock division, but used by unixOpen()
4777** if SQLITE_PREFER_PROXY_LOCKING is defined.
4778*/
4779static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004780#endif
drhc66d5b62008-12-03 22:48:32 +00004781
dan08da86a2009-08-21 17:18:03 +00004782/*
4783** Search for an unused file descriptor that was opened on the database
4784** file (not a journal or master-journal file) identified by pathname
4785** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4786** argument to this function.
4787**
4788** Such a file descriptor may exist if a database connection was closed
4789** but the associated file descriptor could not be closed because some
4790** other file descriptor open on the same file is holding a file-lock.
4791** Refer to comments in the unixClose() function and the lengthy comment
4792** describing "Posix Advisory Locking" at the start of this file for
4793** further details. Also, ticket #4018.
4794**
4795** If a suitable file descriptor is found, then it is returned. If no
4796** such file descriptor is located, -1 is returned.
4797*/
dane946c392009-08-22 11:39:46 +00004798static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4799 UnixUnusedFd *pUnused = 0;
4800
4801 /* Do not search for an unused file descriptor on vxworks. Not because
4802 ** vxworks would not benefit from the change (it might, we're not sure),
4803 ** but because no way to test it is currently available. It is better
4804 ** not to risk breaking vxworks support for the sake of such an obscure
4805 ** feature. */
4806#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004807 struct stat sStat; /* Results of stat() call */
4808
4809 /* A stat() call may fail for various reasons. If this happens, it is
4810 ** almost certain that an open() call on the same path will also fail.
4811 ** For this reason, if an error occurs in the stat() call here, it is
4812 ** ignored and -1 is returned. The caller will try to open a new file
4813 ** descriptor on the same path, fail, and return an error to SQLite.
4814 **
4815 ** Even if a subsequent open() call does succeed, the consequences of
4816 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004817 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004818 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004819
4820 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004821 pInode = inodeList;
4822 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4823 || pInode->fileId.ino!=sStat.st_ino) ){
4824 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004825 }
drh8af6c222010-05-14 12:43:01 +00004826 if( pInode ){
dane946c392009-08-22 11:39:46 +00004827 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004828 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004829 pUnused = *pp;
4830 if( pUnused ){
4831 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004832 }
4833 }
4834 unixLeaveMutex();
4835 }
dane946c392009-08-22 11:39:46 +00004836#endif /* if !OS_VXWORKS */
4837 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004838}
danielk197717b90b52008-06-06 11:11:25 +00004839
4840/*
danddb0ac42010-07-14 14:48:58 +00004841** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004842** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004843** and a value suitable for passing as the third argument to open(2) is
4844** written to *pMode. If an IO error occurs, an SQLite error code is
4845** returned and the value of *pMode is not modified.
4846**
4847** If the file being opened is a temporary file, it is always created with
4848** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004849** is a database or master journal file, it is created with the permissions
4850** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004851**
drh8ab58662010-07-15 18:38:39 +00004852** Finally, if the file being opened is a WAL or regular journal file, then
4853** this function queries the file-system for the permissions on the
4854** corresponding database file and sets *pMode to this value. Whenever
4855** possible, WAL and journal files are created using the same permissions
4856** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004857**
4858** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4859** original filename is unavailable. But 8_3_NAMES is only used for
4860** FAT filesystems and permissions do not matter there, so just use
4861** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004862*/
4863static int findCreateFileMode(
4864 const char *zPath, /* Path of file (possibly) being created */
4865 int flags, /* Flags passed as 4th argument to xOpen() */
4866 mode_t *pMode /* OUT: Permissions to open file with */
4867){
4868 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004869 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004870 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004871 char zDb[MAX_PATHNAME+1]; /* Database file path */
4872 int nDb; /* Number of valid bytes in zDb */
4873 struct stat sStat; /* Output of stat() on database file */
4874
dana0c989d2010-11-05 18:07:37 +00004875 /* zPath is a path to a WAL or journal file. The following block derives
4876 ** the path to the associated database file from zPath. This block handles
4877 ** the following naming conventions:
4878 **
4879 ** "<path to db>-journal"
4880 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004881 ** "<path to db>-journalNN"
4882 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004883 **
drh81cc5162011-05-17 20:36:21 +00004884 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004885 ** used by the test_multiplex.c module.
4886 */
4887 nDb = sqlite3Strlen30(zPath) - 1;
drh81cc5162011-05-17 20:36:21 +00004888 while( nDb>0 && zPath[nDb]!='-' ) nDb--;
4889 if( nDb==0 ) return SQLITE_OK;
danddb0ac42010-07-14 14:48:58 +00004890 memcpy(zDb, zPath, nDb);
4891 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004892
drh58384f12011-07-28 00:14:45 +00004893 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004894 *pMode = sStat.st_mode & 0777;
4895 }else{
4896 rc = SQLITE_IOERR_FSTAT;
4897 }
4898 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4899 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004900 }
4901 return rc;
4902}
4903
4904/*
danielk1977ad94b582007-08-20 06:44:22 +00004905** Open the file zPath.
4906**
danielk1977b4b47412007-08-17 15:53:36 +00004907** Previously, the SQLite OS layer used three functions in place of this
4908** one:
4909**
4910** sqlite3OsOpenReadWrite();
4911** sqlite3OsOpenReadOnly();
4912** sqlite3OsOpenExclusive();
4913**
4914** These calls correspond to the following combinations of flags:
4915**
4916** ReadWrite() -> (READWRITE | CREATE)
4917** ReadOnly() -> (READONLY)
4918** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4919**
4920** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4921** true, the file was configured to be automatically deleted when the
4922** file handle closed. To achieve the same effect using this new
4923** interface, add the DELETEONCLOSE flag to those specified above for
4924** OpenExclusive().
4925*/
4926static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004927 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4928 const char *zPath, /* Pathname of file to be opened */
4929 sqlite3_file *pFile, /* The file descriptor to be filled in */
4930 int flags, /* Input flags to control the opening */
4931 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004932){
dan08da86a2009-08-21 17:18:03 +00004933 unixFile *p = (unixFile *)pFile;
4934 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004935 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004936 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004937 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004938 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004939
4940 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4941 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4942 int isCreate = (flags & SQLITE_OPEN_CREATE);
4943 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4944 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004945#if SQLITE_ENABLE_LOCKING_STYLE
4946 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4947#endif
danielk1977b4b47412007-08-17 15:53:36 +00004948
danielk1977fee2d252007-08-18 10:59:19 +00004949 /* If creating a master or main-file journal, this function will open
4950 ** a file-descriptor on the directory too. The first time unixSync()
4951 ** is called the directory file descriptor will be fsync()ed and close()d.
4952 */
drh0059eae2011-08-08 23:48:40 +00004953 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00004954 eType==SQLITE_OPEN_MASTER_JOURNAL
4955 || eType==SQLITE_OPEN_MAIN_JOURNAL
4956 || eType==SQLITE_OPEN_WAL
4957 ));
danielk1977fee2d252007-08-18 10:59:19 +00004958
danielk197717b90b52008-06-06 11:11:25 +00004959 /* If argument zPath is a NULL pointer, this function is required to open
4960 ** a temporary file. Use this buffer to store the file name in.
4961 */
4962 char zTmpname[MAX_PATHNAME+1];
4963 const char *zName = zPath;
4964
danielk1977fee2d252007-08-18 10:59:19 +00004965 /* Check the following statements are true:
4966 **
4967 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4968 ** (b) if CREATE is set, then READWRITE must also be set, and
4969 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004970 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004971 */
danielk1977b4b47412007-08-17 15:53:36 +00004972 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004973 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004974 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004975 assert(isDelete==0 || isCreate);
4976
danddb0ac42010-07-14 14:48:58 +00004977 /* The main DB, main journal, WAL file and master journal are never
4978 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004979 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4980 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4981 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004982 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004983
danielk1977fee2d252007-08-18 10:59:19 +00004984 /* Assert that the upper layer has set one of the "file-type" flags. */
4985 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4986 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4987 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004988 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004989 );
4990
dan08da86a2009-08-21 17:18:03 +00004991 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004992
dan08da86a2009-08-21 17:18:03 +00004993 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004994 UnixUnusedFd *pUnused;
4995 pUnused = findReusableFd(zName, flags);
4996 if( pUnused ){
4997 fd = pUnused->fd;
4998 }else{
dan6aa657f2009-08-24 18:57:58 +00004999 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005000 if( !pUnused ){
5001 return SQLITE_NOMEM;
5002 }
5003 }
5004 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00005005 }else if( !zName ){
5006 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005007 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00005008 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005009 if( rc!=SQLITE_OK ){
5010 return rc;
5011 }
5012 zName = zTmpname;
5013 }
5014
dan08da86a2009-08-21 17:18:03 +00005015 /* Determine the value of the flags parameter passed to POSIX function
5016 ** open(). These must be calculated even if open() is not called, as
5017 ** they may be stored as part of the file handle and used by the
5018 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005019 if( isReadonly ) openFlags |= O_RDONLY;
5020 if( isReadWrite ) openFlags |= O_RDWR;
5021 if( isCreate ) openFlags |= O_CREAT;
5022 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5023 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005024
danielk1977b4b47412007-08-17 15:53:36 +00005025 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005026 mode_t openMode; /* Permissions to create file with */
5027 rc = findCreateFileMode(zName, flags, &openMode);
5028 if( rc!=SQLITE_OK ){
5029 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005030 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005031 return rc;
5032 }
drhad4f1e52011-03-04 15:43:57 +00005033 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005034 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005035 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5036 /* Failed to open the file for read/write access. Try read-only. */
5037 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005038 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005039 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005040 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005041 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005042 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005043 }
5044 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005045 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005046 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005047 }
danielk1977b4b47412007-08-17 15:53:36 +00005048 }
dan08da86a2009-08-21 17:18:03 +00005049 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005050 if( pOutFlags ){
5051 *pOutFlags = flags;
5052 }
5053
dane946c392009-08-22 11:39:46 +00005054 if( p->pUnused ){
5055 p->pUnused->fd = fd;
5056 p->pUnused->flags = flags;
5057 }
5058
danielk1977b4b47412007-08-17 15:53:36 +00005059 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005060#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005061 zPath = zName;
5062#else
drh036ac7f2011-08-08 23:18:05 +00005063 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005064#endif
danielk1977b4b47412007-08-17 15:53:36 +00005065 }
drh41022642008-11-21 00:24:42 +00005066#if SQLITE_ENABLE_LOCKING_STYLE
5067 else{
dan08da86a2009-08-21 17:18:03 +00005068 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005069 }
5070#endif
5071
danielk1977e339d652008-06-28 11:23:00 +00005072#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005073 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005074#endif
5075
drhda0e7682008-07-30 15:27:54 +00005076 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005077
drh7ed97b92010-01-20 13:07:21 +00005078
5079#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5080 struct statfs fsInfo;
5081 if( fstatfs(fd, &fsInfo) == -1 ){
5082 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005083 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005084 return SQLITE_IOERR_ACCESS;
5085 }
5086 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5087 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5088 }
5089#endif
5090
5091#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005092#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005093 isAutoProxy = 1;
5094#endif
5095 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005096 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5097 int useProxy = 0;
5098
dan08da86a2009-08-21 17:18:03 +00005099 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5100 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005101 if( envforce!=NULL ){
5102 useProxy = atoi(envforce)>0;
5103 }else{
5104 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005105 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005106 /* In theory, the close(fd) call is sub-optimal. If the file opened
5107 ** with fd is a database file, and there are other connections open
5108 ** on that file that are currently holding advisory locks on it,
5109 ** then the call to close() will cancel those locks. In practice,
5110 ** we're assuming that statfs() doesn't fail very often. At least
5111 ** not while other file descriptors opened by the same process on
5112 ** the same file are working. */
5113 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005114 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005115 rc = SQLITE_IOERR_ACCESS;
5116 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005117 }
5118 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5119 }
5120 if( useProxy ){
drh0059eae2011-08-08 23:48:40 +00005121 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005122 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005123 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005124 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005125 if( rc!=SQLITE_OK ){
5126 /* Use unixClose to clean up the resources added in fillInUnixFile
5127 ** and clear all the structure's references. Specifically,
5128 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5129 */
5130 unixClose(pFile);
5131 return rc;
5132 }
aswiftaebf4132008-11-21 00:10:35 +00005133 }
dane946c392009-08-22 11:39:46 +00005134 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005135 }
5136 }
5137#endif
5138
drh0059eae2011-08-08 23:48:40 +00005139 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005140 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005141open_finished:
5142 if( rc!=SQLITE_OK ){
5143 sqlite3_free(p->pUnused);
5144 }
5145 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005146}
5147
dane946c392009-08-22 11:39:46 +00005148
danielk1977b4b47412007-08-17 15:53:36 +00005149/*
danielk1977fee2d252007-08-18 10:59:19 +00005150** Delete the file at zPath. If the dirSync argument is true, fsync()
5151** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005152*/
drh6b9d6dd2008-12-03 19:34:47 +00005153static int unixDelete(
5154 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5155 const char *zPath, /* Name of file to be deleted */
5156 int dirSync /* If true, fsync() directory after deleting file */
5157){
danielk1977fee2d252007-08-18 10:59:19 +00005158 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005159 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005160 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005161 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005162 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005163 }
danielk1977d39fa702008-10-16 13:27:40 +00005164#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005165 if( dirSync ){
5166 int fd;
drh90315a22011-08-10 01:52:12 +00005167 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005168 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005169#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005170 if( fsync(fd)==-1 )
5171#else
5172 if( fsync(fd) )
5173#endif
5174 {
dane18d4952011-02-21 11:46:24 +00005175 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005176 }
drh0e9365c2011-03-02 02:08:13 +00005177 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005178 }
5179 }
danielk1977d138dd82008-10-15 16:02:48 +00005180#endif
danielk1977fee2d252007-08-18 10:59:19 +00005181 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005182}
5183
danielk197790949c22007-08-17 16:50:38 +00005184/*
5185** Test the existance of or access permissions of file zPath. The
5186** test performed depends on the value of flags:
5187**
5188** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5189** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5190** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5191**
5192** Otherwise return 0.
5193*/
danielk1977861f7452008-06-05 11:39:11 +00005194static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005195 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5196 const char *zPath, /* Path of the file to examine */
5197 int flags, /* What do we want to learn about the zPath file? */
5198 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005199){
rse25c0d1a2007-09-20 08:38:14 +00005200 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005201 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005202 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005203 switch( flags ){
5204 case SQLITE_ACCESS_EXISTS:
5205 amode = F_OK;
5206 break;
5207 case SQLITE_ACCESS_READWRITE:
5208 amode = W_OK|R_OK;
5209 break;
drh50d3f902007-08-27 21:10:36 +00005210 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005211 amode = R_OK;
5212 break;
5213
5214 default:
5215 assert(!"Invalid flags argument");
5216 }
drh99ab3b12011-03-02 15:09:07 +00005217 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005218 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5219 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005220 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005221 *pResOut = 0;
5222 }
5223 }
danielk1977861f7452008-06-05 11:39:11 +00005224 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005225}
5226
danielk1977b4b47412007-08-17 15:53:36 +00005227
5228/*
5229** Turn a relative pathname into a full pathname. The relative path
5230** is stored as a nul-terminated string in the buffer pointed to by
5231** zPath.
5232**
5233** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5234** (in this case, MAX_PATHNAME bytes). The full-path is written to
5235** this buffer before returning.
5236*/
danielk1977adfb9b02007-09-17 07:02:56 +00005237static int unixFullPathname(
5238 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5239 const char *zPath, /* Possibly relative input path */
5240 int nOut, /* Size of output buffer in bytes */
5241 char *zOut /* Output buffer */
5242){
danielk1977843e65f2007-09-01 16:16:15 +00005243
5244 /* It's odd to simulate an io-error here, but really this is just
5245 ** using the io-error infrastructure to test that SQLite handles this
5246 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005247 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005248 */
5249 SimulateIOError( return SQLITE_ERROR );
5250
drh153c62c2007-08-24 03:51:33 +00005251 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005252 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005253
drh3c7f2dc2007-12-06 13:26:20 +00005254 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005255 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005256 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005257 }else{
5258 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005259 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005260 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005261 }
drhea678832008-12-10 19:26:22 +00005262 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005263 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005264 }
5265 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005266}
5267
drh0ccebe72005-06-07 22:22:50 +00005268
drh761df872006-12-21 01:29:22 +00005269#ifndef SQLITE_OMIT_LOAD_EXTENSION
5270/*
5271** Interfaces for opening a shared library, finding entry points
5272** within the shared library, and closing the shared library.
5273*/
5274#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005275static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5276 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005277 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5278}
danielk197795c8a542007-09-01 06:51:27 +00005279
5280/*
5281** SQLite calls this function immediately after a call to unixDlSym() or
5282** unixDlOpen() fails (returns a null pointer). If a more detailed error
5283** message is available, it is written to zBufOut. If no error message
5284** is available, zBufOut is left unmodified and SQLite uses a default
5285** error message.
5286*/
danielk1977397d65f2008-11-19 11:35:39 +00005287static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005288 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005289 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005290 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005291 zErr = dlerror();
5292 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005293 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005294 }
drh6c7d5c52008-11-21 20:32:33 +00005295 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005296}
drh1875f7a2008-12-08 18:19:17 +00005297static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5298 /*
5299 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5300 ** cast into a pointer to a function. And yet the library dlsym() routine
5301 ** returns a void* which is really a pointer to a function. So how do we
5302 ** use dlsym() with -pedantic-errors?
5303 **
5304 ** Variable x below is defined to be a pointer to a function taking
5305 ** parameters void* and const char* and returning a pointer to a function.
5306 ** We initialize x by assigning it a pointer to the dlsym() function.
5307 ** (That assignment requires a cast.) Then we call the function that
5308 ** x points to.
5309 **
5310 ** This work-around is unlikely to work correctly on any system where
5311 ** you really cannot cast a function pointer into void*. But then, on the
5312 ** other hand, dlsym() will not work on such a system either, so we have
5313 ** not really lost anything.
5314 */
5315 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005316 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005317 x = (void(*(*)(void*,const char*))(void))dlsym;
5318 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005319}
danielk1977397d65f2008-11-19 11:35:39 +00005320static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5321 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005322 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005323}
danielk1977b4b47412007-08-17 15:53:36 +00005324#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5325 #define unixDlOpen 0
5326 #define unixDlError 0
5327 #define unixDlSym 0
5328 #define unixDlClose 0
5329#endif
5330
5331/*
danielk197790949c22007-08-17 16:50:38 +00005332** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005333*/
danielk1977397d65f2008-11-19 11:35:39 +00005334static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5335 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005336 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005337
drhbbd42a62004-05-22 17:41:58 +00005338 /* We have to initialize zBuf to prevent valgrind from reporting
5339 ** errors. The reports issued by valgrind are incorrect - we would
5340 ** prefer that the randomness be increased by making use of the
5341 ** uninitialized space in zBuf - but valgrind errors tend to worry
5342 ** some users. Rather than argue, it seems easier just to initialize
5343 ** the whole array and silence valgrind, even if that means less randomness
5344 ** in the random seed.
5345 **
5346 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005347 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005348 ** tests repeatable.
5349 */
danielk1977b4b47412007-08-17 15:53:36 +00005350 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005351#if !defined(SQLITE_TEST)
5352 {
drh842b8642005-01-21 17:53:17 +00005353 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005354 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005355 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005356 time_t t;
5357 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005358 memcpy(zBuf, &t, sizeof(t));
5359 pid = getpid();
5360 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005361 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005362 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005363 }else{
drhe562be52011-03-02 18:01:10 +00005364 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005365 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005366 }
drhbbd42a62004-05-22 17:41:58 +00005367 }
5368#endif
drh72cbd072008-10-14 17:58:38 +00005369 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005370}
5371
danielk1977b4b47412007-08-17 15:53:36 +00005372
drhbbd42a62004-05-22 17:41:58 +00005373/*
5374** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005375** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005376** The return value is the number of microseconds of sleep actually
5377** requested from the underlying operating system, a number which
5378** might be greater than or equal to the argument, but not less
5379** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005380*/
danielk1977397d65f2008-11-19 11:35:39 +00005381static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005382#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005383 struct timespec sp;
5384
5385 sp.tv_sec = microseconds / 1000000;
5386 sp.tv_nsec = (microseconds % 1000000) * 1000;
5387 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005388 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005389 return microseconds;
5390#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005391 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005392 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005393 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005394#else
danielk1977b4b47412007-08-17 15:53:36 +00005395 int seconds = (microseconds+999999)/1000000;
5396 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005397 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005398 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005399#endif
drh88f474a2006-01-02 20:00:12 +00005400}
5401
5402/*
drh6b9d6dd2008-12-03 19:34:47 +00005403** The following variable, if set to a non-zero value, is interpreted as
5404** the number of seconds since 1970 and is used to set the result of
5405** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005406*/
5407#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005408int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005409#endif
5410
5411/*
drhb7e8ea22010-05-03 14:32:30 +00005412** Find the current time (in Universal Coordinated Time). Write into *piNow
5413** the current time and date as a Julian Day number times 86_400_000. In
5414** other words, write into *piNow the number of milliseconds since the Julian
5415** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5416** proleptic Gregorian calendar.
5417**
5418** On success, return 0. Return 1 if the time and date cannot be found.
5419*/
5420static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5421 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5422#if defined(NO_GETTOD)
5423 time_t t;
5424 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005425 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005426#elif OS_VXWORKS
5427 struct timespec sNow;
5428 clock_gettime(CLOCK_REALTIME, &sNow);
5429 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5430#else
5431 struct timeval sNow;
5432 gettimeofday(&sNow, 0);
5433 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5434#endif
5435
5436#ifdef SQLITE_TEST
5437 if( sqlite3_current_time ){
5438 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5439 }
5440#endif
5441 UNUSED_PARAMETER(NotUsed);
5442 return 0;
5443}
5444
5445/*
drhbbd42a62004-05-22 17:41:58 +00005446** Find the current time (in Universal Coordinated Time). Write the
5447** current time and date as a Julian Day number into *prNow and
5448** return 0. Return 1 if the time and date cannot be found.
5449*/
danielk1977397d65f2008-11-19 11:35:39 +00005450static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005451 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005452 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005453 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005454 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005455 return 0;
5456}
danielk1977b4b47412007-08-17 15:53:36 +00005457
drh6b9d6dd2008-12-03 19:34:47 +00005458/*
5459** We added the xGetLastError() method with the intention of providing
5460** better low-level error messages when operating-system problems come up
5461** during SQLite operation. But so far, none of that has been implemented
5462** in the core. So this routine is never called. For now, it is merely
5463** a place-holder.
5464*/
danielk1977397d65f2008-11-19 11:35:39 +00005465static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5466 UNUSED_PARAMETER(NotUsed);
5467 UNUSED_PARAMETER(NotUsed2);
5468 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005469 return 0;
5470}
5471
drhf2424c52010-04-26 00:04:55 +00005472
5473/*
drh734c9862008-11-28 15:37:20 +00005474************************ End of sqlite3_vfs methods ***************************
5475******************************************************************************/
5476
drh715ff302008-12-03 22:32:44 +00005477/******************************************************************************
5478************************** Begin Proxy Locking ********************************
5479**
5480** Proxy locking is a "uber-locking-method" in this sense: It uses the
5481** other locking methods on secondary lock files. Proxy locking is a
5482** meta-layer over top of the primitive locking implemented above. For
5483** this reason, the division that implements of proxy locking is deferred
5484** until late in the file (here) after all of the other I/O methods have
5485** been defined - so that the primitive locking methods are available
5486** as services to help with the implementation of proxy locking.
5487**
5488****
5489**
5490** The default locking schemes in SQLite use byte-range locks on the
5491** database file to coordinate safe, concurrent access by multiple readers
5492** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5493** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5494** as POSIX read & write locks over fixed set of locations (via fsctl),
5495** on AFP and SMB only exclusive byte-range locks are available via fsctl
5496** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5497** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5498** address in the shared range is taken for a SHARED lock, the entire
5499** shared range is taken for an EXCLUSIVE lock):
5500**
5501** PENDING_BYTE 0x40000000
5502** RESERVED_BYTE 0x40000001
5503** SHARED_RANGE 0x40000002 -> 0x40000200
5504**
5505** This works well on the local file system, but shows a nearly 100x
5506** slowdown in read performance on AFP because the AFP client disables
5507** the read cache when byte-range locks are present. Enabling the read
5508** cache exposes a cache coherency problem that is present on all OS X
5509** supported network file systems. NFS and AFP both observe the
5510** close-to-open semantics for ensuring cache coherency
5511** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5512** address the requirements for concurrent database access by multiple
5513** readers and writers
5514** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5515**
5516** To address the performance and cache coherency issues, proxy file locking
5517** changes the way database access is controlled by limiting access to a
5518** single host at a time and moving file locks off of the database file
5519** and onto a proxy file on the local file system.
5520**
5521**
5522** Using proxy locks
5523** -----------------
5524**
5525** C APIs
5526**
5527** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5528** <proxy_path> | ":auto:");
5529** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5530**
5531**
5532** SQL pragmas
5533**
5534** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5535** PRAGMA [database.]lock_proxy_file
5536**
5537** Specifying ":auto:" means that if there is a conch file with a matching
5538** host ID in it, the proxy path in the conch file will be used, otherwise
5539** a proxy path based on the user's temp dir
5540** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5541** actual proxy file name is generated from the name and path of the
5542** database file. For example:
5543**
5544** For database path "/Users/me/foo.db"
5545** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5546**
5547** Once a lock proxy is configured for a database connection, it can not
5548** be removed, however it may be switched to a different proxy path via
5549** the above APIs (assuming the conch file is not being held by another
5550** connection or process).
5551**
5552**
5553** How proxy locking works
5554** -----------------------
5555**
5556** Proxy file locking relies primarily on two new supporting files:
5557**
5558** * conch file to limit access to the database file to a single host
5559** at a time
5560**
5561** * proxy file to act as a proxy for the advisory locks normally
5562** taken on the database
5563**
5564** The conch file - to use a proxy file, sqlite must first "hold the conch"
5565** by taking an sqlite-style shared lock on the conch file, reading the
5566** contents and comparing the host's unique host ID (see below) and lock
5567** proxy path against the values stored in the conch. The conch file is
5568** stored in the same directory as the database file and the file name
5569** is patterned after the database file name as ".<databasename>-conch".
5570** If the conch file does not exist, or it's contents do not match the
5571** host ID and/or proxy path, then the lock is escalated to an exclusive
5572** lock and the conch file contents is updated with the host ID and proxy
5573** path and the lock is downgraded to a shared lock again. If the conch
5574** is held by another process (with a shared lock), the exclusive lock
5575** will fail and SQLITE_BUSY is returned.
5576**
5577** The proxy file - a single-byte file used for all advisory file locks
5578** normally taken on the database file. This allows for safe sharing
5579** of the database file for multiple readers and writers on the same
5580** host (the conch ensures that they all use the same local lock file).
5581**
drh715ff302008-12-03 22:32:44 +00005582** Requesting the lock proxy does not immediately take the conch, it is
5583** only taken when the first request to lock database file is made.
5584** This matches the semantics of the traditional locking behavior, where
5585** opening a connection to a database file does not take a lock on it.
5586** The shared lock and an open file descriptor are maintained until
5587** the connection to the database is closed.
5588**
5589** The proxy file and the lock file are never deleted so they only need
5590** to be created the first time they are used.
5591**
5592** Configuration options
5593** ---------------------
5594**
5595** SQLITE_PREFER_PROXY_LOCKING
5596**
5597** Database files accessed on non-local file systems are
5598** automatically configured for proxy locking, lock files are
5599** named automatically using the same logic as
5600** PRAGMA lock_proxy_file=":auto:"
5601**
5602** SQLITE_PROXY_DEBUG
5603**
5604** Enables the logging of error messages during host id file
5605** retrieval and creation
5606**
drh715ff302008-12-03 22:32:44 +00005607** LOCKPROXYDIR
5608**
5609** Overrides the default directory used for lock proxy files that
5610** are named automatically via the ":auto:" setting
5611**
5612** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5613**
5614** Permissions to use when creating a directory for storing the
5615** lock proxy files, only used when LOCKPROXYDIR is not set.
5616**
5617**
5618** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5619** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5620** force proxy locking to be used for every database file opened, and 0
5621** will force automatic proxy locking to be disabled for all database
5622** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5623** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5624*/
5625
5626/*
5627** Proxy locking is only available on MacOSX
5628*/
drhd2cb50b2009-01-09 21:41:17 +00005629#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005630
drh715ff302008-12-03 22:32:44 +00005631/*
5632** The proxyLockingContext has the path and file structures for the remote
5633** and local proxy files in it
5634*/
5635typedef struct proxyLockingContext proxyLockingContext;
5636struct proxyLockingContext {
5637 unixFile *conchFile; /* Open conch file */
5638 char *conchFilePath; /* Name of the conch file */
5639 unixFile *lockProxy; /* Open proxy lock file */
5640 char *lockProxyPath; /* Name of the proxy lock file */
5641 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005642 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005643 void *oldLockingContext; /* Original lockingcontext to restore on close */
5644 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5645};
5646
drh7ed97b92010-01-20 13:07:21 +00005647/*
5648** The proxy lock file path for the database at dbPath is written into lPath,
5649** which must point to valid, writable memory large enough for a maxLen length
5650** file path.
drh715ff302008-12-03 22:32:44 +00005651*/
drh715ff302008-12-03 22:32:44 +00005652static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5653 int len;
5654 int dbLen;
5655 int i;
5656
5657#ifdef LOCKPROXYDIR
5658 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5659#else
5660# ifdef _CS_DARWIN_USER_TEMP_DIR
5661 {
drh7ed97b92010-01-20 13:07:21 +00005662 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005663 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5664 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005665 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005666 }
drh7ed97b92010-01-20 13:07:21 +00005667 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005668 }
5669# else
5670 len = strlcpy(lPath, "/tmp/", maxLen);
5671# endif
5672#endif
5673
5674 if( lPath[len-1]!='/' ){
5675 len = strlcat(lPath, "/", maxLen);
5676 }
5677
5678 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005679 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005680 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005681 char c = dbPath[i];
5682 lPath[i+len] = (c=='/')?'_':c;
5683 }
5684 lPath[i+len]='\0';
5685 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005686 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005687 return SQLITE_OK;
5688}
5689
drh7ed97b92010-01-20 13:07:21 +00005690/*
5691 ** Creates the lock file and any missing directories in lockPath
5692 */
5693static int proxyCreateLockPath(const char *lockPath){
5694 int i, len;
5695 char buf[MAXPATHLEN];
5696 int start = 0;
5697
5698 assert(lockPath!=NULL);
5699 /* try to create all the intermediate directories */
5700 len = (int)strlen(lockPath);
5701 buf[0] = lockPath[0];
5702 for( i=1; i<len; i++ ){
5703 if( lockPath[i] == '/' && (i - start > 0) ){
5704 /* only mkdir if leaf dir != "." or "/" or ".." */
5705 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5706 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5707 buf[i]='\0';
5708 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5709 int err=errno;
5710 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005711 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005712 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005713 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005714 return err;
5715 }
5716 }
5717 }
5718 start=i+1;
5719 }
5720 buf[i] = lockPath[i];
5721 }
drh308c2a52010-05-14 11:30:18 +00005722 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005723 return 0;
5724}
5725
drh715ff302008-12-03 22:32:44 +00005726/*
5727** Create a new VFS file descriptor (stored in memory obtained from
5728** sqlite3_malloc) and open the file named "path" in the file descriptor.
5729**
5730** The caller is responsible not only for closing the file descriptor
5731** but also for freeing the memory associated with the file descriptor.
5732*/
drh7ed97b92010-01-20 13:07:21 +00005733static int proxyCreateUnixFile(
5734 const char *path, /* path for the new unixFile */
5735 unixFile **ppFile, /* unixFile created and returned by ref */
5736 int islockfile /* if non zero missing dirs will be created */
5737) {
5738 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005739 unixFile *pNew;
5740 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005741 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005742 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005743 int terrno = 0;
5744 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005745
drh7ed97b92010-01-20 13:07:21 +00005746 /* 1. first try to open/create the file
5747 ** 2. if that fails, and this is a lock file (not-conch), try creating
5748 ** the parent directories and then try again.
5749 ** 3. if that fails, try to open the file read-only
5750 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5751 */
5752 pUnused = findReusableFd(path, openFlags);
5753 if( pUnused ){
5754 fd = pUnused->fd;
5755 }else{
5756 pUnused = sqlite3_malloc(sizeof(*pUnused));
5757 if( !pUnused ){
5758 return SQLITE_NOMEM;
5759 }
5760 }
5761 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005762 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005763 terrno = errno;
5764 if( fd<0 && errno==ENOENT && islockfile ){
5765 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005766 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005767 }
5768 }
5769 }
5770 if( fd<0 ){
5771 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005772 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005773 terrno = errno;
5774 }
5775 if( fd<0 ){
5776 if( islockfile ){
5777 return SQLITE_BUSY;
5778 }
5779 switch (terrno) {
5780 case EACCES:
5781 return SQLITE_PERM;
5782 case EIO:
5783 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5784 default:
drh9978c972010-02-23 17:36:32 +00005785 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005786 }
5787 }
5788
5789 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5790 if( pNew==NULL ){
5791 rc = SQLITE_NOMEM;
5792 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005793 }
5794 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005795 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005796 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005797 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005798 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005799 pUnused->fd = fd;
5800 pUnused->flags = openFlags;
5801 pNew->pUnused = pUnused;
5802
drh0059eae2011-08-08 23:48:40 +00005803 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005804 if( rc==SQLITE_OK ){
5805 *ppFile = pNew;
5806 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005807 }
drh7ed97b92010-01-20 13:07:21 +00005808end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005809 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005810 sqlite3_free(pNew);
5811 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005812 return rc;
5813}
5814
drh7ed97b92010-01-20 13:07:21 +00005815#ifdef SQLITE_TEST
5816/* simulate multiple hosts by creating unique hostid file paths */
5817int sqlite3_hostid_num = 0;
5818#endif
5819
5820#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5821
drh0ab216a2010-07-02 17:10:40 +00005822/* Not always defined in the headers as it ought to be */
5823extern int gethostuuid(uuid_t id, const struct timespec *wait);
5824
drh7ed97b92010-01-20 13:07:21 +00005825/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5826** bytes of writable memory.
5827*/
5828static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005829 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5830 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005831#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5832 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005833 {
5834 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5835 if( gethostuuid(pHostID, &timeout) ){
5836 int err = errno;
5837 if( pError ){
5838 *pError = err;
5839 }
5840 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005841 }
drh7ed97b92010-01-20 13:07:21 +00005842 }
drhe8b0c9b2010-09-25 14:13:17 +00005843#endif
drh7ed97b92010-01-20 13:07:21 +00005844#ifdef SQLITE_TEST
5845 /* simulate multiple hosts by creating unique hostid file paths */
5846 if( sqlite3_hostid_num != 0){
5847 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5848 }
5849#endif
5850
5851 return SQLITE_OK;
5852}
5853
5854/* The conch file contains the header, host id and lock file path
5855 */
5856#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5857#define PROXY_HEADERLEN 1 /* conch file header length */
5858#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5859#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5860
5861/*
5862** Takes an open conch file, copies the contents to a new path and then moves
5863** it back. The newly created file's file descriptor is assigned to the
5864** conch file structure and finally the original conch file descriptor is
5865** closed. Returns zero if successful.
5866*/
5867static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5868 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5869 unixFile *conchFile = pCtx->conchFile;
5870 char tPath[MAXPATHLEN];
5871 char buf[PROXY_MAXCONCHLEN];
5872 char *cPath = pCtx->conchFilePath;
5873 size_t readLen = 0;
5874 size_t pathLen = 0;
5875 char errmsg[64] = "";
5876 int fd = -1;
5877 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005878 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005879
5880 /* create a new path by replace the trailing '-conch' with '-break' */
5881 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5882 if( pathLen>MAXPATHLEN || pathLen<6 ||
5883 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005884 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005885 goto end_breaklock;
5886 }
5887 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005888 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005889 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005890 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005891 goto end_breaklock;
5892 }
5893 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005894 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5895 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005896 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005897 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005898 goto end_breaklock;
5899 }
drhe562be52011-03-02 18:01:10 +00005900 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005901 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005902 goto end_breaklock;
5903 }
5904 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005905 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005906 goto end_breaklock;
5907 }
5908 rc = 0;
5909 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005910 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005911 conchFile->h = fd;
5912 conchFile->openFlags = O_RDWR | O_CREAT;
5913
5914end_breaklock:
5915 if( rc ){
5916 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005917 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005918 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005919 }
5920 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5921 }
5922 return rc;
5923}
5924
5925/* Take the requested lock on the conch file and break a stale lock if the
5926** host id matches.
5927*/
5928static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5929 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5930 unixFile *conchFile = pCtx->conchFile;
5931 int rc = SQLITE_OK;
5932 int nTries = 0;
5933 struct timespec conchModTime;
5934
5935 do {
5936 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5937 nTries ++;
5938 if( rc==SQLITE_BUSY ){
5939 /* If the lock failed (busy):
5940 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5941 * 2nd try: fail if the mod time changed or host id is different, wait
5942 * 10 sec and try again
5943 * 3rd try: break the lock unless the mod time has changed.
5944 */
5945 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005946 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005947 pFile->lastErrno = errno;
5948 return SQLITE_IOERR_LOCK;
5949 }
5950
5951 if( nTries==1 ){
5952 conchModTime = buf.st_mtimespec;
5953 usleep(500000); /* wait 0.5 sec and try the lock again*/
5954 continue;
5955 }
5956
5957 assert( nTries>1 );
5958 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5959 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5960 return SQLITE_BUSY;
5961 }
5962
5963 if( nTries==2 ){
5964 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005965 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005966 if( len<0 ){
5967 pFile->lastErrno = errno;
5968 return SQLITE_IOERR_LOCK;
5969 }
5970 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5971 /* don't break the lock if the host id doesn't match */
5972 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5973 return SQLITE_BUSY;
5974 }
5975 }else{
5976 /* don't break the lock on short read or a version mismatch */
5977 return SQLITE_BUSY;
5978 }
5979 usleep(10000000); /* wait 10 sec and try the lock again */
5980 continue;
5981 }
5982
5983 assert( nTries==3 );
5984 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5985 rc = SQLITE_OK;
5986 if( lockType==EXCLUSIVE_LOCK ){
5987 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5988 }
5989 if( !rc ){
5990 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5991 }
5992 }
5993 }
5994 } while( rc==SQLITE_BUSY && nTries<3 );
5995
5996 return rc;
5997}
5998
5999/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006000** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6001** lockPath means that the lockPath in the conch file will be used if the
6002** host IDs match, or a new lock path will be generated automatically
6003** and written to the conch file.
6004*/
6005static int proxyTakeConch(unixFile *pFile){
6006 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6007
drh7ed97b92010-01-20 13:07:21 +00006008 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006009 return SQLITE_OK;
6010 }else{
6011 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006012 uuid_t myHostID;
6013 int pError = 0;
6014 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006015 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006016 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006017 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006018 int createConch = 0;
6019 int hostIdMatch = 0;
6020 int readLen = 0;
6021 int tryOldLockPath = 0;
6022 int forceNewLockPath = 0;
6023
drh308c2a52010-05-14 11:30:18 +00006024 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6025 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006026
drh7ed97b92010-01-20 13:07:21 +00006027 rc = proxyGetHostID(myHostID, &pError);
6028 if( (rc&0xff)==SQLITE_IOERR ){
6029 pFile->lastErrno = pError;
6030 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006031 }
drh7ed97b92010-01-20 13:07:21 +00006032 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006033 if( rc!=SQLITE_OK ){
6034 goto end_takeconch;
6035 }
drh7ed97b92010-01-20 13:07:21 +00006036 /* read the existing conch file */
6037 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6038 if( readLen<0 ){
6039 /* I/O error: lastErrno set by seekAndRead */
6040 pFile->lastErrno = conchFile->lastErrno;
6041 rc = SQLITE_IOERR_READ;
6042 goto end_takeconch;
6043 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6044 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6045 /* a short read or version format mismatch means we need to create a new
6046 ** conch file.
6047 */
6048 createConch = 1;
6049 }
6050 /* if the host id matches and the lock path already exists in the conch
6051 ** we'll try to use the path there, if we can't open that path, we'll
6052 ** retry with a new auto-generated path
6053 */
6054 do { /* in case we need to try again for an :auto: named lock file */
6055
6056 if( !createConch && !forceNewLockPath ){
6057 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6058 PROXY_HOSTIDLEN);
6059 /* if the conch has data compare the contents */
6060 if( !pCtx->lockProxyPath ){
6061 /* for auto-named local lock file, just check the host ID and we'll
6062 ** use the local lock file path that's already in there
6063 */
6064 if( hostIdMatch ){
6065 size_t pathLen = (readLen - PROXY_PATHINDEX);
6066
6067 if( pathLen>=MAXPATHLEN ){
6068 pathLen=MAXPATHLEN-1;
6069 }
6070 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6071 lockPath[pathLen] = 0;
6072 tempLockPath = lockPath;
6073 tryOldLockPath = 1;
6074 /* create a copy of the lock path if the conch is taken */
6075 goto end_takeconch;
6076 }
6077 }else if( hostIdMatch
6078 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6079 readLen-PROXY_PATHINDEX)
6080 ){
6081 /* conch host and lock path match */
6082 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006083 }
drh7ed97b92010-01-20 13:07:21 +00006084 }
6085
6086 /* if the conch isn't writable and doesn't match, we can't take it */
6087 if( (conchFile->openFlags&O_RDWR) == 0 ){
6088 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006089 goto end_takeconch;
6090 }
drh7ed97b92010-01-20 13:07:21 +00006091
6092 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006093 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006094 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6095 tempLockPath = lockPath;
6096 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006097 }
drh7ed97b92010-01-20 13:07:21 +00006098
6099 /* update conch with host and path (this will fail if other process
6100 ** has a shared lock already), if the host id matches, use the big
6101 ** stick.
drh715ff302008-12-03 22:32:44 +00006102 */
drh7ed97b92010-01-20 13:07:21 +00006103 futimes(conchFile->h, NULL);
6104 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006105 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006106 /* We are trying for an exclusive lock but another thread in this
6107 ** same process is still holding a shared lock. */
6108 rc = SQLITE_BUSY;
6109 } else {
6110 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006111 }
drh715ff302008-12-03 22:32:44 +00006112 }else{
drh7ed97b92010-01-20 13:07:21 +00006113 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006114 }
drh7ed97b92010-01-20 13:07:21 +00006115 if( rc==SQLITE_OK ){
6116 char writeBuffer[PROXY_MAXCONCHLEN];
6117 int writeSize = 0;
6118
6119 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6120 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6121 if( pCtx->lockProxyPath!=NULL ){
6122 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6123 }else{
6124 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6125 }
6126 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006127 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006128 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6129 fsync(conchFile->h);
6130 /* If we created a new conch file (not just updated the contents of a
6131 ** valid conch file), try to match the permissions of the database
6132 */
6133 if( rc==SQLITE_OK && createConch ){
6134 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006135 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006136 if( err==0 ){
6137 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6138 S_IROTH|S_IWOTH);
6139 /* try to match the database file R/W permissions, ignore failure */
6140#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006141 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006142#else
drhff812312011-02-23 13:33:46 +00006143 do{
drhe562be52011-03-02 18:01:10 +00006144 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006145 }while( rc==(-1) && errno==EINTR );
6146 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006147 int code = errno;
6148 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6149 cmode, code, strerror(code));
6150 } else {
6151 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6152 }
6153 }else{
6154 int code = errno;
6155 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6156 err, code, strerror(code));
6157#endif
6158 }
drh715ff302008-12-03 22:32:44 +00006159 }
6160 }
drh7ed97b92010-01-20 13:07:21 +00006161 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6162
6163 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006164 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006165 if( rc==SQLITE_OK && pFile->openFlags ){
6166 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006167 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006168 }
6169 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006170 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006171 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006172 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006173 if( fd>=0 ){
6174 pFile->h = fd;
6175 }else{
drh9978c972010-02-23 17:36:32 +00006176 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006177 during locking */
6178 }
6179 }
6180 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6181 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6182 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6183 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6184 /* we couldn't create the proxy lock file with the old lock file path
6185 ** so try again via auto-naming
6186 */
6187 forceNewLockPath = 1;
6188 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006189 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006190 }
6191 }
6192 if( rc==SQLITE_OK ){
6193 /* Need to make a copy of path if we extracted the value
6194 ** from the conch file or the path was allocated on the stack
6195 */
6196 if( tempLockPath ){
6197 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6198 if( !pCtx->lockProxyPath ){
6199 rc = SQLITE_NOMEM;
6200 }
6201 }
6202 }
6203 if( rc==SQLITE_OK ){
6204 pCtx->conchHeld = 1;
6205
6206 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6207 afpLockingContext *afpCtx;
6208 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6209 afpCtx->dbPath = pCtx->lockProxyPath;
6210 }
6211 } else {
6212 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6213 }
drh308c2a52010-05-14 11:30:18 +00006214 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6215 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006216 return rc;
drh308c2a52010-05-14 11:30:18 +00006217 } while (1); /* in case we need to retry the :auto: lock file -
6218 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006219 }
6220}
6221
6222/*
6223** If pFile holds a lock on a conch file, then release that lock.
6224*/
6225static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006226 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006227 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6228 unixFile *conchFile; /* Name of the conch file */
6229
6230 pCtx = (proxyLockingContext *)pFile->lockingContext;
6231 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006232 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006233 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006234 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006235 if( pCtx->conchHeld>0 ){
6236 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6237 }
drh715ff302008-12-03 22:32:44 +00006238 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006239 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6240 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006241 return rc;
6242}
6243
6244/*
6245** Given the name of a database file, compute the name of its conch file.
6246** Store the conch filename in memory obtained from sqlite3_malloc().
6247** Make *pConchPath point to the new name. Return SQLITE_OK on success
6248** or SQLITE_NOMEM if unable to obtain memory.
6249**
6250** The caller is responsible for ensuring that the allocated memory
6251** space is eventually freed.
6252**
6253** *pConchPath is set to NULL if a memory allocation error occurs.
6254*/
6255static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6256 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006257 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006258 char *conchPath; /* buffer in which to construct conch name */
6259
6260 /* Allocate space for the conch filename and initialize the name to
6261 ** the name of the original database file. */
6262 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6263 if( conchPath==0 ){
6264 return SQLITE_NOMEM;
6265 }
6266 memcpy(conchPath, dbPath, len+1);
6267
6268 /* now insert a "." before the last / character */
6269 for( i=(len-1); i>=0; i-- ){
6270 if( conchPath[i]=='/' ){
6271 i++;
6272 break;
6273 }
6274 }
6275 conchPath[i]='.';
6276 while ( i<len ){
6277 conchPath[i+1]=dbPath[i];
6278 i++;
6279 }
6280
6281 /* append the "-conch" suffix to the file */
6282 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006283 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006284
6285 return SQLITE_OK;
6286}
6287
6288
6289/* Takes a fully configured proxy locking-style unix file and switches
6290** the local lock file path
6291*/
6292static int switchLockProxyPath(unixFile *pFile, const char *path) {
6293 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6294 char *oldPath = pCtx->lockProxyPath;
6295 int rc = SQLITE_OK;
6296
drh308c2a52010-05-14 11:30:18 +00006297 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006298 return SQLITE_BUSY;
6299 }
6300
6301 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6302 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6303 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6304 return SQLITE_OK;
6305 }else{
6306 unixFile *lockProxy = pCtx->lockProxy;
6307 pCtx->lockProxy=NULL;
6308 pCtx->conchHeld = 0;
6309 if( lockProxy!=NULL ){
6310 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6311 if( rc ) return rc;
6312 sqlite3_free(lockProxy);
6313 }
6314 sqlite3_free(oldPath);
6315 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6316 }
6317
6318 return rc;
6319}
6320
6321/*
6322** pFile is a file that has been opened by a prior xOpen call. dbPath
6323** is a string buffer at least MAXPATHLEN+1 characters in size.
6324**
6325** This routine find the filename associated with pFile and writes it
6326** int dbPath.
6327*/
6328static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006329#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006330 if( pFile->pMethod == &afpIoMethods ){
6331 /* afp style keeps a reference to the db path in the filePath field
6332 ** of the struct */
drhea678832008-12-10 19:26:22 +00006333 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006334 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6335 } else
drh715ff302008-12-03 22:32:44 +00006336#endif
6337 if( pFile->pMethod == &dotlockIoMethods ){
6338 /* dot lock style uses the locking context to store the dot lock
6339 ** file path */
6340 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6341 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6342 }else{
6343 /* all other styles use the locking context to store the db file path */
6344 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006345 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006346 }
6347 return SQLITE_OK;
6348}
6349
6350/*
6351** Takes an already filled in unix file and alters it so all file locking
6352** will be performed on the local proxy lock file. The following fields
6353** are preserved in the locking context so that they can be restored and
6354** the unix structure properly cleaned up at close time:
6355** ->lockingContext
6356** ->pMethod
6357*/
6358static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6359 proxyLockingContext *pCtx;
6360 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6361 char *lockPath=NULL;
6362 int rc = SQLITE_OK;
6363
drh308c2a52010-05-14 11:30:18 +00006364 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006365 return SQLITE_BUSY;
6366 }
6367 proxyGetDbPathForUnixFile(pFile, dbPath);
6368 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6369 lockPath=NULL;
6370 }else{
6371 lockPath=(char *)path;
6372 }
6373
drh308c2a52010-05-14 11:30:18 +00006374 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6375 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006376
6377 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6378 if( pCtx==0 ){
6379 return SQLITE_NOMEM;
6380 }
6381 memset(pCtx, 0, sizeof(*pCtx));
6382
6383 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6384 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006385 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6386 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6387 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6388 ** (c) the file system is read-only, then enable no-locking access.
6389 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6390 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6391 */
6392 struct statfs fsInfo;
6393 struct stat conchInfo;
6394 int goLockless = 0;
6395
drh99ab3b12011-03-02 15:09:07 +00006396 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006397 int err = errno;
6398 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6399 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6400 }
6401 }
6402 if( goLockless ){
6403 pCtx->conchHeld = -1; /* read only FS/ lockless */
6404 rc = SQLITE_OK;
6405 }
6406 }
drh715ff302008-12-03 22:32:44 +00006407 }
6408 if( rc==SQLITE_OK && lockPath ){
6409 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6410 }
6411
6412 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006413 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6414 if( pCtx->dbPath==NULL ){
6415 rc = SQLITE_NOMEM;
6416 }
6417 }
6418 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006419 /* all memory is allocated, proxys are created and assigned,
6420 ** switch the locking context and pMethod then return.
6421 */
drh715ff302008-12-03 22:32:44 +00006422 pCtx->oldLockingContext = pFile->lockingContext;
6423 pFile->lockingContext = pCtx;
6424 pCtx->pOldMethod = pFile->pMethod;
6425 pFile->pMethod = &proxyIoMethods;
6426 }else{
6427 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006428 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006429 sqlite3_free(pCtx->conchFile);
6430 }
drhd56b1212010-08-11 06:14:15 +00006431 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006432 sqlite3_free(pCtx->conchFilePath);
6433 sqlite3_free(pCtx);
6434 }
drh308c2a52010-05-14 11:30:18 +00006435 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6436 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006437 return rc;
6438}
6439
6440
6441/*
6442** This routine handles sqlite3_file_control() calls that are specific
6443** to proxy locking.
6444*/
6445static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6446 switch( op ){
6447 case SQLITE_GET_LOCKPROXYFILE: {
6448 unixFile *pFile = (unixFile*)id;
6449 if( pFile->pMethod == &proxyIoMethods ){
6450 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6451 proxyTakeConch(pFile);
6452 if( pCtx->lockProxyPath ){
6453 *(const char **)pArg = pCtx->lockProxyPath;
6454 }else{
6455 *(const char **)pArg = ":auto: (not held)";
6456 }
6457 } else {
6458 *(const char **)pArg = NULL;
6459 }
6460 return SQLITE_OK;
6461 }
6462 case SQLITE_SET_LOCKPROXYFILE: {
6463 unixFile *pFile = (unixFile*)id;
6464 int rc = SQLITE_OK;
6465 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6466 if( pArg==NULL || (const char *)pArg==0 ){
6467 if( isProxyStyle ){
6468 /* turn off proxy locking - not supported */
6469 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6470 }else{
6471 /* turn off proxy locking - already off - NOOP */
6472 rc = SQLITE_OK;
6473 }
6474 }else{
6475 const char *proxyPath = (const char *)pArg;
6476 if( isProxyStyle ){
6477 proxyLockingContext *pCtx =
6478 (proxyLockingContext*)pFile->lockingContext;
6479 if( !strcmp(pArg, ":auto:")
6480 || (pCtx->lockProxyPath &&
6481 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6482 ){
6483 rc = SQLITE_OK;
6484 }else{
6485 rc = switchLockProxyPath(pFile, proxyPath);
6486 }
6487 }else{
6488 /* turn on proxy file locking */
6489 rc = proxyTransformUnixFile(pFile, proxyPath);
6490 }
6491 }
6492 return rc;
6493 }
6494 default: {
6495 assert( 0 ); /* The call assures that only valid opcodes are sent */
6496 }
6497 }
6498 /*NOTREACHED*/
6499 return SQLITE_ERROR;
6500}
6501
6502/*
6503** Within this division (the proxying locking implementation) the procedures
6504** above this point are all utilities. The lock-related methods of the
6505** proxy-locking sqlite3_io_method object follow.
6506*/
6507
6508
6509/*
6510** This routine checks if there is a RESERVED lock held on the specified
6511** file by this or any other process. If such a lock is held, set *pResOut
6512** to a non-zero value otherwise *pResOut is set to zero. The return value
6513** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6514*/
6515static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6516 unixFile *pFile = (unixFile*)id;
6517 int rc = proxyTakeConch(pFile);
6518 if( rc==SQLITE_OK ){
6519 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006520 if( pCtx->conchHeld>0 ){
6521 unixFile *proxy = pCtx->lockProxy;
6522 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6523 }else{ /* conchHeld < 0 is lockless */
6524 pResOut=0;
6525 }
drh715ff302008-12-03 22:32:44 +00006526 }
6527 return rc;
6528}
6529
6530/*
drh308c2a52010-05-14 11:30:18 +00006531** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006532** of the following:
6533**
6534** (1) SHARED_LOCK
6535** (2) RESERVED_LOCK
6536** (3) PENDING_LOCK
6537** (4) EXCLUSIVE_LOCK
6538**
6539** Sometimes when requesting one lock state, additional lock states
6540** are inserted in between. The locking might fail on one of the later
6541** transitions leaving the lock state different from what it started but
6542** still short of its goal. The following chart shows the allowed
6543** transitions and the inserted intermediate states:
6544**
6545** UNLOCKED -> SHARED
6546** SHARED -> RESERVED
6547** SHARED -> (PENDING) -> EXCLUSIVE
6548** RESERVED -> (PENDING) -> EXCLUSIVE
6549** PENDING -> EXCLUSIVE
6550**
6551** This routine will only increase a lock. Use the sqlite3OsUnlock()
6552** routine to lower a locking level.
6553*/
drh308c2a52010-05-14 11:30:18 +00006554static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006555 unixFile *pFile = (unixFile*)id;
6556 int rc = proxyTakeConch(pFile);
6557 if( rc==SQLITE_OK ){
6558 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006559 if( pCtx->conchHeld>0 ){
6560 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006561 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6562 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006563 }else{
6564 /* conchHeld < 0 is lockless */
6565 }
drh715ff302008-12-03 22:32:44 +00006566 }
6567 return rc;
6568}
6569
6570
6571/*
drh308c2a52010-05-14 11:30:18 +00006572** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006573** must be either NO_LOCK or SHARED_LOCK.
6574**
6575** If the locking level of the file descriptor is already at or below
6576** the requested locking level, this routine is a no-op.
6577*/
drh308c2a52010-05-14 11:30:18 +00006578static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006579 unixFile *pFile = (unixFile*)id;
6580 int rc = proxyTakeConch(pFile);
6581 if( rc==SQLITE_OK ){
6582 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006583 if( pCtx->conchHeld>0 ){
6584 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006585 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6586 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006587 }else{
6588 /* conchHeld < 0 is lockless */
6589 }
drh715ff302008-12-03 22:32:44 +00006590 }
6591 return rc;
6592}
6593
6594/*
6595** Close a file that uses proxy locks.
6596*/
6597static int proxyClose(sqlite3_file *id) {
6598 if( id ){
6599 unixFile *pFile = (unixFile*)id;
6600 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6601 unixFile *lockProxy = pCtx->lockProxy;
6602 unixFile *conchFile = pCtx->conchFile;
6603 int rc = SQLITE_OK;
6604
6605 if( lockProxy ){
6606 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6607 if( rc ) return rc;
6608 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6609 if( rc ) return rc;
6610 sqlite3_free(lockProxy);
6611 pCtx->lockProxy = 0;
6612 }
6613 if( conchFile ){
6614 if( pCtx->conchHeld ){
6615 rc = proxyReleaseConch(pFile);
6616 if( rc ) return rc;
6617 }
6618 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6619 if( rc ) return rc;
6620 sqlite3_free(conchFile);
6621 }
drhd56b1212010-08-11 06:14:15 +00006622 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006623 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006624 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006625 /* restore the original locking context and pMethod then close it */
6626 pFile->lockingContext = pCtx->oldLockingContext;
6627 pFile->pMethod = pCtx->pOldMethod;
6628 sqlite3_free(pCtx);
6629 return pFile->pMethod->xClose(id);
6630 }
6631 return SQLITE_OK;
6632}
6633
6634
6635
drhd2cb50b2009-01-09 21:41:17 +00006636#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006637/*
6638** The proxy locking style is intended for use with AFP filesystems.
6639** And since AFP is only supported on MacOSX, the proxy locking is also
6640** restricted to MacOSX.
6641**
6642**
6643******************* End of the proxy lock implementation **********************
6644******************************************************************************/
6645
drh734c9862008-11-28 15:37:20 +00006646/*
danielk1977e339d652008-06-28 11:23:00 +00006647** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006648**
6649** This routine registers all VFS implementations for unix-like operating
6650** systems. This routine, and the sqlite3_os_end() routine that follows,
6651** should be the only routines in this file that are visible from other
6652** files.
drh6b9d6dd2008-12-03 19:34:47 +00006653**
6654** This routine is called once during SQLite initialization and by a
6655** single thread. The memory allocation and mutex subsystems have not
6656** necessarily been initialized when this routine is called, and so they
6657** should not be used.
drh153c62c2007-08-24 03:51:33 +00006658*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006659int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006660 /*
6661 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006662 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6663 ** to the "finder" function. (pAppData is a pointer to a pointer because
6664 ** silly C90 rules prohibit a void* from being cast to a function pointer
6665 ** and so we have to go through the intermediate pointer to avoid problems
6666 ** when compiling with -pedantic-errors on GCC.)
6667 **
6668 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006669 ** finder-function. The finder-function returns a pointer to the
6670 ** sqlite_io_methods object that implements the desired locking
6671 ** behaviors. See the division above that contains the IOMETHODS
6672 ** macro for addition information on finder-functions.
6673 **
6674 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6675 ** object. But the "autolockIoFinder" available on MacOSX does a little
6676 ** more than that; it looks at the filesystem type that hosts the
6677 ** database file and tries to choose an locking method appropriate for
6678 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006679 */
drh7708e972008-11-29 00:56:52 +00006680 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006681 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006682 sizeof(unixFile), /* szOsFile */ \
6683 MAX_PATHNAME, /* mxPathname */ \
6684 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006685 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006686 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006687 unixOpen, /* xOpen */ \
6688 unixDelete, /* xDelete */ \
6689 unixAccess, /* xAccess */ \
6690 unixFullPathname, /* xFullPathname */ \
6691 unixDlOpen, /* xDlOpen */ \
6692 unixDlError, /* xDlError */ \
6693 unixDlSym, /* xDlSym */ \
6694 unixDlClose, /* xDlClose */ \
6695 unixRandomness, /* xRandomness */ \
6696 unixSleep, /* xSleep */ \
6697 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006698 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006699 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006700 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006701 unixGetSystemCall, /* xGetSystemCall */ \
6702 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006703 }
6704
drh6b9d6dd2008-12-03 19:34:47 +00006705 /*
6706 ** All default VFSes for unix are contained in the following array.
6707 **
6708 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6709 ** by the SQLite core when the VFS is registered. So the following
6710 ** array cannot be const.
6711 */
danielk1977e339d652008-06-28 11:23:00 +00006712 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006713#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006714 UNIXVFS("unix", autolockIoFinder ),
6715#else
6716 UNIXVFS("unix", posixIoFinder ),
6717#endif
6718 UNIXVFS("unix-none", nolockIoFinder ),
6719 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006720 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006721#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006722 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006723#endif
6724#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006725 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006726#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006727 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006728#endif
chw78a13182009-04-07 05:35:03 +00006729#endif
drhd2cb50b2009-01-09 21:41:17 +00006730#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006731 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006732 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006733 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006734#endif
drh153c62c2007-08-24 03:51:33 +00006735 };
drh6b9d6dd2008-12-03 19:34:47 +00006736 unsigned int i; /* Loop counter */
6737
drh2aa5a002011-04-13 13:42:25 +00006738 /* Double-check that the aSyscall[] array has been constructed
6739 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh90315a22011-08-10 01:52:12 +00006740 assert( ArraySize(aSyscall)==18 );
drh2aa5a002011-04-13 13:42:25 +00006741
drh6b9d6dd2008-12-03 19:34:47 +00006742 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006743 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006744 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006745 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006746 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006747}
danielk1977e339d652008-06-28 11:23:00 +00006748
6749/*
drh6b9d6dd2008-12-03 19:34:47 +00006750** Shutdown the operating system interface.
6751**
6752** Some operating systems might need to do some cleanup in this routine,
6753** to release dynamically allocated objects. But not on unix.
6754** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006755*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006756int sqlite3_os_end(void){
6757 return SQLITE_OK;
6758}
drhdce8bdb2007-08-16 13:01:44 +00006759
danielk197729bafea2008-06-26 10:41:19 +00006760#endif /* SQLITE_OS_UNIX */