blob: dce13e5365388b7e95033cc9f47224fe7ebde0c2 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drhdbe4b882011-06-20 18:00:17 +0000141#ifdef HAVE_UTIME
142# include <utime.h>
143#endif
144
drh9cbe6352005-11-29 03:13:21 +0000145/*
drh7ed97b92010-01-20 13:07:21 +0000146** Allowed values of unixFile.fsFlags
147*/
148#define SQLITE_FSFLAGS_IS_MSDOS 0x1
149
150/*
drhf1a221e2006-01-15 17:27:17 +0000151** If we are to be thread-safe, include the pthreads header and define
152** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000153*/
drhd677b3d2007-08-20 22:48:41 +0000154#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000155# include <pthread.h>
156# define SQLITE_UNIX_THREADS 1
157#endif
158
159/*
160** Default permissions when creating a new file
161*/
162#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
163# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
164#endif
165
danielk1977b4b47412007-08-17 15:53:36 +0000166/*
aswiftaebf4132008-11-21 00:10:35 +0000167 ** Default permissions when creating auto proxy dir
168 */
169#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
170# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
171#endif
172
173/*
danielk1977b4b47412007-08-17 15:53:36 +0000174** Maximum supported path-length.
175*/
176#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000177
drh734c9862008-11-28 15:37:20 +0000178/*
drh734c9862008-11-28 15:37:20 +0000179** Only set the lastErrno if the error code is a real error and not
180** a normal expected return code of SQLITE_BUSY or SQLITE_OK
181*/
182#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
183
drhd91c68f2010-05-14 14:52:25 +0000184/* Forward references */
185typedef struct unixShm unixShm; /* Connection shared memory */
186typedef struct unixShmNode unixShmNode; /* Shared memory instance */
187typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
188typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000189
190/*
dane946c392009-08-22 11:39:46 +0000191** Sometimes, after a file handle is closed by SQLite, the file descriptor
192** cannot be closed immediately. In these cases, instances of the following
193** structure are used to store the file descriptor while waiting for an
194** opportunity to either close or reuse it.
195*/
dane946c392009-08-22 11:39:46 +0000196struct UnixUnusedFd {
197 int fd; /* File descriptor to close */
198 int flags; /* Flags this file descriptor was opened with */
199 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
200};
201
202/*
drh9b35ea62008-11-29 02:20:26 +0000203** The unixFile structure is subclass of sqlite3_file specific to the unix
204** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000205*/
drh054889e2005-11-30 03:20:31 +0000206typedef struct unixFile unixFile;
207struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000208 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000209 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000210 int h; /* The file descriptor */
211 int dirfd; /* File descriptor for the directory */
212 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000213 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000214 int lastErrno; /* The unix errno from last I/O error */
215 void *lockingContext; /* Locking style specific state */
216 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000217 const char *zPath; /* Name of the file */
218 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000219 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000220#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000221 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000222#endif
drh7ed97b92010-01-20 13:07:21 +0000223#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000224 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
226#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000227 int isDelete; /* Delete on close if true */
228 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000229#endif
drh8f941bc2009-01-14 23:03:40 +0000230#ifndef NDEBUG
231 /* The next group of variables are used to track whether or not the
232 ** transaction counter in bytes 24-27 of database files are updated
233 ** whenever any part of the database changes. An assertion fault will
234 ** occur if a file is updated without also updating the transaction
235 ** counter. This test is made to avoid new problems similar to the
236 ** one described by ticket #3584.
237 */
238 unsigned char transCntrChng; /* True if the transaction counter changed */
239 unsigned char dbUpdate; /* True if any part of database file changed */
240 unsigned char inNormalWrite; /* True if in a normal write operation */
241#endif
danielk1977967a4a12007-08-20 14:23:44 +0000242#ifdef SQLITE_TEST
243 /* In test mode, increase the size of this structure a bit so that
244 ** it is larger than the struct CrashFile defined in test6.c.
245 */
246 char aPadding[32];
247#endif
drh9cbe6352005-11-29 03:13:21 +0000248};
249
drh0ccebe72005-06-07 22:22:50 +0000250/*
drha7e61d82011-03-12 17:02:57 +0000251** Allowed values for the unixFile.ctrlFlags bitmask:
252*/
253#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
drh77197112011-03-15 19:08:48 +0000254#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
drha7e61d82011-03-12 17:02:57 +0000255
256/*
drh198bf392006-01-06 21:52:49 +0000257** Include code that is common to all os_*.c files
258*/
259#include "os_common.h"
260
261/*
drh0ccebe72005-06-07 22:22:50 +0000262** Define various macros that are missing from some systems.
263*/
drhbbd42a62004-05-22 17:41:58 +0000264#ifndef O_LARGEFILE
265# define O_LARGEFILE 0
266#endif
267#ifdef SQLITE_DISABLE_LFS
268# undef O_LARGEFILE
269# define O_LARGEFILE 0
270#endif
271#ifndef O_NOFOLLOW
272# define O_NOFOLLOW 0
273#endif
274#ifndef O_BINARY
275# define O_BINARY 0
276#endif
277
278/*
drh2b4b5962005-06-15 17:47:55 +0000279** The threadid macro resolves to the thread-id or to 0. Used for
280** testing and debugging only.
281*/
drhd677b3d2007-08-20 22:48:41 +0000282#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000283#define threadid pthread_self()
284#else
285#define threadid 0
286#endif
287
drh99ab3b12011-03-02 15:09:07 +0000288/*
drh9a3baf12011-04-25 18:01:27 +0000289** Different Unix systems declare open() in different ways. Same use
290** open(const char*,int,mode_t). Others use open(const char*,int,...).
291** The difference is important when using a pointer to the function.
292**
293** The safest way to deal with the problem is to always use this wrapper
294** which always has the same well-defined interface.
295*/
296static int posixOpen(const char *zFile, int flags, int mode){
297 return open(zFile, flags, mode);
298}
299
300/*
drh99ab3b12011-03-02 15:09:07 +0000301** Many system calls are accessed through pointer-to-functions so that
302** they may be overridden at runtime to facilitate fault injection during
303** testing and sandboxing. The following array holds the names and pointers
304** to all overrideable system calls.
305*/
306static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000307 const char *zName; /* Name of the sytem call */
308 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
309 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000310} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000311 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
312#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000313
drh58ad5802011-03-23 22:02:23 +0000314 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000315#define osClose ((int(*)(int))aSyscall[1].pCurrent)
316
drh58ad5802011-03-23 22:02:23 +0000317 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000318#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
319
drh58ad5802011-03-23 22:02:23 +0000320 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000321#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
322
drh58ad5802011-03-23 22:02:23 +0000323 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000324#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
325
326/*
327** The DJGPP compiler environment looks mostly like Unix, but it
328** lacks the fcntl() system call. So redefine fcntl() to be something
329** that always succeeds. This means that locking does not occur under
330** DJGPP. But it is DOS - what did you expect?
331*/
332#ifdef __DJGPP__
333 { "fstat", 0, 0 },
334#define osFstat(a,b,c) 0
335#else
drh58ad5802011-03-23 22:02:23 +0000336 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000337#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
338#endif
339
drh58ad5802011-03-23 22:02:23 +0000340 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000341#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
342
drh58ad5802011-03-23 22:02:23 +0000343 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000344#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000345
drh58ad5802011-03-23 22:02:23 +0000346 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000347#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
348
drhd4a80312011-04-15 14:33:20 +0000349#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000350 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000351#else
drh58ad5802011-03-23 22:02:23 +0000352 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000353#endif
354#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
355
356#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000357 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000358#else
drh58ad5802011-03-23 22:02:23 +0000359 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000360#endif
361#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
362
drh58ad5802011-03-23 22:02:23 +0000363 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000364#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
365
drhd4a80312011-04-15 14:33:20 +0000366#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000367 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000368#else
drh58ad5802011-03-23 22:02:23 +0000369 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000370#endif
371#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
372 aSyscall[12].pCurrent)
373
374#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000375 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000376#else
drh58ad5802011-03-23 22:02:23 +0000377 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000378#endif
379#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
380 aSyscall[13].pCurrent)
381
drha6c47492011-04-11 18:35:09 +0000382#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000383 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000384#else
385 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000386#endif
drh2aa5a002011-04-13 13:42:25 +0000387#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000388
389#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000390 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000391#else
drh58ad5802011-03-23 22:02:23 +0000392 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000393#endif
dan0fd7d862011-03-29 10:04:23 +0000394#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000395
396}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000397
398/*
399** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000400** "unix" VFSes. Return SQLITE_OK opon successfully updating the
401** system call pointer, or SQLITE_NOTFOUND if there is no configurable
402** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000403*/
404static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000405 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
406 const char *zName, /* Name of system call to override */
407 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000408){
drh58ad5802011-03-23 22:02:23 +0000409 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000410 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000411
412 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000413 if( zName==0 ){
414 /* If no zName is given, restore all system calls to their default
415 ** settings and return NULL
416 */
dan51438a72011-04-02 17:00:47 +0000417 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000418 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
419 if( aSyscall[i].pDefault ){
420 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000421 }
422 }
423 }else{
424 /* If zName is specified, operate on only the one system call
425 ** specified.
426 */
427 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
428 if( strcmp(zName, aSyscall[i].zName)==0 ){
429 if( aSyscall[i].pDefault==0 ){
430 aSyscall[i].pDefault = aSyscall[i].pCurrent;
431 }
drh1df30962011-03-02 19:06:42 +0000432 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000433 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
434 aSyscall[i].pCurrent = pNewFunc;
435 break;
436 }
437 }
438 }
439 return rc;
440}
441
drh1df30962011-03-02 19:06:42 +0000442/*
443** Return the value of a system call. Return NULL if zName is not a
444** recognized system call name. NULL is also returned if the system call
445** is currently undefined.
446*/
drh58ad5802011-03-23 22:02:23 +0000447static sqlite3_syscall_ptr unixGetSystemCall(
448 sqlite3_vfs *pNotUsed,
449 const char *zName
450){
451 unsigned int i;
452
453 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000454 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
455 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
456 }
457 return 0;
458}
459
460/*
461** Return the name of the first system call after zName. If zName==NULL
462** then return the name of the first system call. Return NULL if zName
463** is the last system call or if zName is not the name of a valid
464** system call.
465*/
466static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000467 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000468
469 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000470 if( zName ){
471 for(i=0; i<ArraySize(aSyscall)-1; i++){
472 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000473 }
474 }
dan0fd7d862011-03-29 10:04:23 +0000475 for(i++; i<ArraySize(aSyscall); i++){
476 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000477 }
478 return 0;
479}
480
drhad4f1e52011-03-04 15:43:57 +0000481/*
482** Retry open() calls that fail due to EINTR
483*/
484static int robust_open(const char *z, int f, int m){
485 int rc;
486 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
487 return rc;
488}
danielk197713adf8a2004-06-03 16:08:41 +0000489
drh107886a2008-11-21 22:21:50 +0000490/*
dan9359c7b2009-08-21 08:29:10 +0000491** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000492** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000493** vxworksFileId objects used by this file, all of which may be
494** shared by multiple threads.
495**
496** Function unixMutexHeld() is used to assert() that the global mutex
497** is held when required. This function is only used as part of assert()
498** statements. e.g.
499**
500** unixEnterMutex()
501** assert( unixMutexHeld() );
502** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000503*/
504static void unixEnterMutex(void){
505 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
506}
507static void unixLeaveMutex(void){
508 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
509}
dan9359c7b2009-08-21 08:29:10 +0000510#ifdef SQLITE_DEBUG
511static int unixMutexHeld(void) {
512 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
513}
514#endif
drh107886a2008-11-21 22:21:50 +0000515
drh734c9862008-11-28 15:37:20 +0000516
517#ifdef SQLITE_DEBUG
518/*
519** Helper function for printing out trace information from debugging
520** binaries. This returns the string represetation of the supplied
521** integer lock-type.
522*/
drh308c2a52010-05-14 11:30:18 +0000523static const char *azFileLock(int eFileLock){
524 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000525 case NO_LOCK: return "NONE";
526 case SHARED_LOCK: return "SHARED";
527 case RESERVED_LOCK: return "RESERVED";
528 case PENDING_LOCK: return "PENDING";
529 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000530 }
531 return "ERROR";
532}
533#endif
534
535#ifdef SQLITE_LOCK_TRACE
536/*
537** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000538**
drh734c9862008-11-28 15:37:20 +0000539** This routine is used for troubleshooting locks on multithreaded
540** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
541** command-line option on the compiler. This code is normally
542** turned off.
543*/
544static int lockTrace(int fd, int op, struct flock *p){
545 char *zOpName, *zType;
546 int s;
547 int savedErrno;
548 if( op==F_GETLK ){
549 zOpName = "GETLK";
550 }else if( op==F_SETLK ){
551 zOpName = "SETLK";
552 }else{
drh99ab3b12011-03-02 15:09:07 +0000553 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000554 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
555 return s;
556 }
557 if( p->l_type==F_RDLCK ){
558 zType = "RDLCK";
559 }else if( p->l_type==F_WRLCK ){
560 zType = "WRLCK";
561 }else if( p->l_type==F_UNLCK ){
562 zType = "UNLCK";
563 }else{
564 assert( 0 );
565 }
566 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000567 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000568 savedErrno = errno;
569 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
570 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
571 (int)p->l_pid, s);
572 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
573 struct flock l2;
574 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000575 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000576 if( l2.l_type==F_RDLCK ){
577 zType = "RDLCK";
578 }else if( l2.l_type==F_WRLCK ){
579 zType = "WRLCK";
580 }else if( l2.l_type==F_UNLCK ){
581 zType = "UNLCK";
582 }else{
583 assert( 0 );
584 }
585 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
586 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
587 }
588 errno = savedErrno;
589 return s;
590}
drh99ab3b12011-03-02 15:09:07 +0000591#undef osFcntl
592#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000593#endif /* SQLITE_LOCK_TRACE */
594
drhff812312011-02-23 13:33:46 +0000595/*
596** Retry ftruncate() calls that fail due to EINTR
597*/
drhff812312011-02-23 13:33:46 +0000598static int robust_ftruncate(int h, sqlite3_int64 sz){
599 int rc;
drh99ab3b12011-03-02 15:09:07 +0000600 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000601 return rc;
602}
drh734c9862008-11-28 15:37:20 +0000603
604/*
605** This routine translates a standard POSIX errno code into something
606** useful to the clients of the sqlite3 functions. Specifically, it is
607** intended to translate a variety of "try again" errors into SQLITE_BUSY
608** and a variety of "please close the file descriptor NOW" errors into
609** SQLITE_IOERR
610**
611** Errors during initialization of locks, or file system support for locks,
612** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
613*/
614static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
615 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000616#if 0
617 /* At one point this code was not commented out. In theory, this branch
618 ** should never be hit, as this function should only be called after
619 ** a locking-related function (i.e. fcntl()) has returned non-zero with
620 ** the value of errno as the first argument. Since a system call has failed,
621 ** errno should be non-zero.
622 **
623 ** Despite this, if errno really is zero, we still don't want to return
624 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
625 ** propagated back to the caller. Commenting this branch out means errno==0
626 ** will be handled by the "default:" case below.
627 */
drh734c9862008-11-28 15:37:20 +0000628 case 0:
629 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000630#endif
631
drh734c9862008-11-28 15:37:20 +0000632 case EAGAIN:
633 case ETIMEDOUT:
634 case EBUSY:
635 case EINTR:
636 case ENOLCK:
637 /* random NFS retry error, unless during file system support
638 * introspection, in which it actually means what it says */
639 return SQLITE_BUSY;
640
641 case EACCES:
642 /* EACCES is like EAGAIN during locking operations, but not any other time*/
643 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
644 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
645 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
646 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
647 return SQLITE_BUSY;
648 }
649 /* else fall through */
650 case EPERM:
651 return SQLITE_PERM;
652
danea83bc62011-04-01 11:56:32 +0000653 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
654 ** this module never makes such a call. And the code in SQLite itself
655 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
656 ** this case is also commented out. If the system does set errno to EDEADLK,
657 ** the default SQLITE_IOERR_XXX code will be returned. */
658#if 0
drh734c9862008-11-28 15:37:20 +0000659 case EDEADLK:
660 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000661#endif
drh734c9862008-11-28 15:37:20 +0000662
663#if EOPNOTSUPP!=ENOTSUP
664 case EOPNOTSUPP:
665 /* something went terribly awry, unless during file system support
666 * introspection, in which it actually means what it says */
667#endif
668#ifdef ENOTSUP
669 case ENOTSUP:
670 /* invalid fd, unless during file system support introspection, in which
671 * it actually means what it says */
672#endif
673 case EIO:
674 case EBADF:
675 case EINVAL:
676 case ENOTCONN:
677 case ENODEV:
678 case ENXIO:
679 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000680#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000681 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000682#endif
drh734c9862008-11-28 15:37:20 +0000683 case ENOSYS:
684 /* these should force the client to close the file and reconnect */
685
686 default:
687 return sqliteIOErr;
688 }
689}
690
691
692
693/******************************************************************************
694****************** Begin Unique File ID Utility Used By VxWorks ***************
695**
696** On most versions of unix, we can get a unique ID for a file by concatenating
697** the device number and the inode number. But this does not work on VxWorks.
698** On VxWorks, a unique file id must be based on the canonical filename.
699**
700** A pointer to an instance of the following structure can be used as a
701** unique file ID in VxWorks. Each instance of this structure contains
702** a copy of the canonical filename. There is also a reference count.
703** The structure is reclaimed when the number of pointers to it drops to
704** zero.
705**
706** There are never very many files open at one time and lookups are not
707** a performance-critical path, so it is sufficient to put these
708** structures on a linked list.
709*/
710struct vxworksFileId {
711 struct vxworksFileId *pNext; /* Next in a list of them all */
712 int nRef; /* Number of references to this one */
713 int nName; /* Length of the zCanonicalName[] string */
714 char *zCanonicalName; /* Canonical filename */
715};
716
717#if OS_VXWORKS
718/*
drh9b35ea62008-11-29 02:20:26 +0000719** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000720** variable:
721*/
722static struct vxworksFileId *vxworksFileList = 0;
723
724/*
725** Simplify a filename into its canonical form
726** by making the following changes:
727**
728** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000729** * convert /./ into just /
730** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000731**
732** Changes are made in-place. Return the new name length.
733**
734** The original filename is in z[0..n-1]. Return the number of
735** characters in the simplified name.
736*/
737static int vxworksSimplifyName(char *z, int n){
738 int i, j;
739 while( n>1 && z[n-1]=='/' ){ n--; }
740 for(i=j=0; i<n; i++){
741 if( z[i]=='/' ){
742 if( z[i+1]=='/' ) continue;
743 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
744 i += 1;
745 continue;
746 }
747 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
748 while( j>0 && z[j-1]!='/' ){ j--; }
749 if( j>0 ){ j--; }
750 i += 2;
751 continue;
752 }
753 }
754 z[j++] = z[i];
755 }
756 z[j] = 0;
757 return j;
758}
759
760/*
761** Find a unique file ID for the given absolute pathname. Return
762** a pointer to the vxworksFileId object. This pointer is the unique
763** file ID.
764**
765** The nRef field of the vxworksFileId object is incremented before
766** the object is returned. A new vxworksFileId object is created
767** and added to the global list if necessary.
768**
769** If a memory allocation error occurs, return NULL.
770*/
771static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
772 struct vxworksFileId *pNew; /* search key and new file ID */
773 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
774 int n; /* Length of zAbsoluteName string */
775
776 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000777 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000778 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
779 if( pNew==0 ) return 0;
780 pNew->zCanonicalName = (char*)&pNew[1];
781 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
782 n = vxworksSimplifyName(pNew->zCanonicalName, n);
783
784 /* Search for an existing entry that matching the canonical name.
785 ** If found, increment the reference count and return a pointer to
786 ** the existing file ID.
787 */
788 unixEnterMutex();
789 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
790 if( pCandidate->nName==n
791 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
792 ){
793 sqlite3_free(pNew);
794 pCandidate->nRef++;
795 unixLeaveMutex();
796 return pCandidate;
797 }
798 }
799
800 /* No match was found. We will make a new file ID */
801 pNew->nRef = 1;
802 pNew->nName = n;
803 pNew->pNext = vxworksFileList;
804 vxworksFileList = pNew;
805 unixLeaveMutex();
806 return pNew;
807}
808
809/*
810** Decrement the reference count on a vxworksFileId object. Free
811** the object when the reference count reaches zero.
812*/
813static void vxworksReleaseFileId(struct vxworksFileId *pId){
814 unixEnterMutex();
815 assert( pId->nRef>0 );
816 pId->nRef--;
817 if( pId->nRef==0 ){
818 struct vxworksFileId **pp;
819 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
820 assert( *pp==pId );
821 *pp = pId->pNext;
822 sqlite3_free(pId);
823 }
824 unixLeaveMutex();
825}
826#endif /* OS_VXWORKS */
827/*************** End of Unique File ID Utility Used By VxWorks ****************
828******************************************************************************/
829
830
831/******************************************************************************
832*************************** Posix Advisory Locking ****************************
833**
drh9b35ea62008-11-29 02:20:26 +0000834** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000835** section 6.5.2.2 lines 483 through 490 specify that when a process
836** sets or clears a lock, that operation overrides any prior locks set
837** by the same process. It does not explicitly say so, but this implies
838** that it overrides locks set by the same process using a different
839** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000840**
841** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000842** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
843**
844** Suppose ./file1 and ./file2 are really the same file (because
845** one is a hard or symbolic link to the other) then if you set
846** an exclusive lock on fd1, then try to get an exclusive lock
847** on fd2, it works. I would have expected the second lock to
848** fail since there was already a lock on the file due to fd1.
849** But not so. Since both locks came from the same process, the
850** second overrides the first, even though they were on different
851** file descriptors opened on different file names.
852**
drh734c9862008-11-28 15:37:20 +0000853** This means that we cannot use POSIX locks to synchronize file access
854** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000855** to synchronize access for threads in separate processes, but not
856** threads within the same process.
857**
858** To work around the problem, SQLite has to manage file locks internally
859** on its own. Whenever a new database is opened, we have to find the
860** specific inode of the database file (the inode is determined by the
861** st_dev and st_ino fields of the stat structure that fstat() fills in)
862** and check for locks already existing on that inode. When locks are
863** created or removed, we have to look at our own internal record of the
864** locks to see if another thread has previously set a lock on that same
865** inode.
866**
drh9b35ea62008-11-29 02:20:26 +0000867** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
868** For VxWorks, we have to use the alternative unique ID system based on
869** canonical filename and implemented in the previous division.)
870**
danielk1977ad94b582007-08-20 06:44:22 +0000871** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000872** descriptor. It is now a structure that holds the integer file
873** descriptor and a pointer to a structure that describes the internal
874** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000875** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000876** point to the same locking structure. The locking structure keeps
877** a reference count (so we will know when to delete it) and a "cnt"
878** field that tells us its internal lock status. cnt==0 means the
879** file is unlocked. cnt==-1 means the file has an exclusive lock.
880** cnt>0 means there are cnt shared locks on the file.
881**
882** Any attempt to lock or unlock a file first checks the locking
883** structure. The fcntl() system call is only invoked to set a
884** POSIX lock if the internal lock structure transitions between
885** a locked and an unlocked state.
886**
drh734c9862008-11-28 15:37:20 +0000887** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000888**
889** If you close a file descriptor that points to a file that has locks,
890** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000891** released. To work around this problem, each unixInodeInfo object
892** maintains a count of the number of pending locks on tha inode.
893** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000894** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000895** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000896** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000897** be closed and that list is walked (and cleared) when the last lock
898** clears.
899**
drh9b35ea62008-11-29 02:20:26 +0000900** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000901**
drh9b35ea62008-11-29 02:20:26 +0000902** Many older versions of linux use the LinuxThreads library which is
903** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000904** A cannot be modified or overridden by a different thread B.
905** Only thread A can modify the lock. Locking behavior is correct
906** if the appliation uses the newer Native Posix Thread Library (NPTL)
907** on linux - with NPTL a lock created by thread A can override locks
908** in thread B. But there is no way to know at compile-time which
909** threading library is being used. So there is no way to know at
910** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000911** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000912** current process.
drh5fdae772004-06-29 03:29:00 +0000913**
drh8af6c222010-05-14 12:43:01 +0000914** SQLite used to support LinuxThreads. But support for LinuxThreads
915** was dropped beginning with version 3.7.0. SQLite will still work with
916** LinuxThreads provided that (1) there is no more than one connection
917** per database file in the same process and (2) database connections
918** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000919*/
920
921/*
922** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000923** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000924*/
925struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000926 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000927#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000928 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000929#else
drh107886a2008-11-21 22:21:50 +0000930 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000931#endif
932};
933
934/*
drhbbd42a62004-05-22 17:41:58 +0000935** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000936** inode. Or, on LinuxThreads, there is one of these structures for
937** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000938**
danielk1977ad94b582007-08-20 06:44:22 +0000939** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000940** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000941** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000942*/
drh8af6c222010-05-14 12:43:01 +0000943struct unixInodeInfo {
944 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000945 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000946 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
947 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000948 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000949 unixShmNode *pShmNode; /* Shared memory associated with this inode */
950 int nLock; /* Number of outstanding file locks */
951 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
952 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
953 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000954#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000955 unsigned long long sharedByte; /* for AFP simulated shared lock */
956#endif
drh6c7d5c52008-11-21 20:32:33 +0000957#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000958 sem_t *pSem; /* Named POSIX semaphore */
959 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000960#endif
drhbbd42a62004-05-22 17:41:58 +0000961};
962
drhda0e7682008-07-30 15:27:54 +0000963/*
drh8af6c222010-05-14 12:43:01 +0000964** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000965*/
drhd91c68f2010-05-14 14:52:25 +0000966static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000967
drh5fdae772004-06-29 03:29:00 +0000968/*
dane18d4952011-02-21 11:46:24 +0000969**
970** This function - unixLogError_x(), is only ever called via the macro
971** unixLogError().
972**
973** It is invoked after an error occurs in an OS function and errno has been
974** set. It logs a message using sqlite3_log() containing the current value of
975** errno and, if possible, the human-readable equivalent from strerror() or
976** strerror_r().
977**
978** The first argument passed to the macro should be the error code that
979** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
980** The two subsequent arguments should be the name of the OS function that
981** failed (e.g. "unlink", "open") and the the associated file-system path,
982** if any.
983*/
drh0e9365c2011-03-02 02:08:13 +0000984#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
985static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000986 int errcode, /* SQLite error code */
987 const char *zFunc, /* Name of OS function that failed */
988 const char *zPath, /* File path associated with error */
989 int iLine /* Source line number where error occurred */
990){
991 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000992 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000993
994 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
995 ** the strerror() function to obtain the human-readable error message
996 ** equivalent to errno. Otherwise, use strerror_r().
997 */
998#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
999 char aErr[80];
1000 memset(aErr, 0, sizeof(aErr));
1001 zErr = aErr;
1002
1003 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1004 ** assume that the system provides the the GNU version of strerror_r() that
1005 ** returns a pointer to a buffer containing the error message. That pointer
1006 ** may point to aErr[], or it may point to some static storage somewhere.
1007 ** Otherwise, assume that the system provides the POSIX version of
1008 ** strerror_r(), which always writes an error message into aErr[].
1009 **
1010 ** If the code incorrectly assumes that it is the POSIX version that is
1011 ** available, the error message will often be an empty string. Not a
1012 ** huge problem. Incorrectly concluding that the GNU version is available
1013 ** could lead to a segfault though.
1014 */
1015#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1016 zErr =
1017# endif
drh0e9365c2011-03-02 02:08:13 +00001018 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001019
1020#elif SQLITE_THREADSAFE
1021 /* This is a threadsafe build, but strerror_r() is not available. */
1022 zErr = "";
1023#else
1024 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001025 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001026#endif
1027
1028 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001029 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001030 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001031 "os_unix.c:%d: (%d) %s(%s) - %s",
1032 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001033 );
1034
1035 return errcode;
1036}
1037
drh0e9365c2011-03-02 02:08:13 +00001038/*
1039** Close a file descriptor.
1040**
1041** We assume that close() almost always works, since it is only in a
1042** very sick application or on a very sick platform that it might fail.
1043** If it does fail, simply leak the file descriptor, but do log the
1044** error.
1045**
1046** Note that it is not safe to retry close() after EINTR since the
1047** file descriptor might have already been reused by another thread.
1048** So we don't even try to recover from an EINTR. Just log the error
1049** and move on.
1050*/
1051static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001052 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001053 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1054 pFile ? pFile->zPath : 0, lineno);
1055 }
1056}
dane18d4952011-02-21 11:46:24 +00001057
1058/*
danb0ac3e32010-06-16 10:55:42 +00001059** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001060*/
drh0e9365c2011-03-02 02:08:13 +00001061static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001062 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001063 UnixUnusedFd *p;
1064 UnixUnusedFd *pNext;
1065 for(p=pInode->pUnused; p; p=pNext){
1066 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001067 robust_close(pFile, p->fd, __LINE__);
1068 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001069 }
drh0e9365c2011-03-02 02:08:13 +00001070 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001071}
1072
1073/*
drh8af6c222010-05-14 12:43:01 +00001074** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001075**
1076** The mutex entered using the unixEnterMutex() function must be held
1077** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001078*/
danb0ac3e32010-06-16 10:55:42 +00001079static void releaseInodeInfo(unixFile *pFile){
1080 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001081 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001082 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001083 pInode->nRef--;
1084 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001085 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001086 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001087 if( pInode->pPrev ){
1088 assert( pInode->pPrev->pNext==pInode );
1089 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001090 }else{
drh8af6c222010-05-14 12:43:01 +00001091 assert( inodeList==pInode );
1092 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001093 }
drh8af6c222010-05-14 12:43:01 +00001094 if( pInode->pNext ){
1095 assert( pInode->pNext->pPrev==pInode );
1096 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001097 }
drh8af6c222010-05-14 12:43:01 +00001098 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001099 }
drhbbd42a62004-05-22 17:41:58 +00001100 }
1101}
1102
1103/*
drh8af6c222010-05-14 12:43:01 +00001104** Given a file descriptor, locate the unixInodeInfo object that
1105** describes that file descriptor. Create a new one if necessary. The
1106** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001107**
dan9359c7b2009-08-21 08:29:10 +00001108** The mutex entered using the unixEnterMutex() function must be held
1109** when this function is called.
1110**
drh6c7d5c52008-11-21 20:32:33 +00001111** Return an appropriate error code.
1112*/
drh8af6c222010-05-14 12:43:01 +00001113static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001114 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001115 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001116){
1117 int rc; /* System call return code */
1118 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001119 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1120 struct stat statbuf; /* Low-level file information */
1121 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001122
dan9359c7b2009-08-21 08:29:10 +00001123 assert( unixMutexHeld() );
1124
drh6c7d5c52008-11-21 20:32:33 +00001125 /* Get low-level information about the file that we can used to
1126 ** create a unique name for the file.
1127 */
1128 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001129 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001130 if( rc!=0 ){
1131 pFile->lastErrno = errno;
1132#ifdef EOVERFLOW
1133 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1134#endif
1135 return SQLITE_IOERR;
1136 }
1137
drheb0d74f2009-02-03 15:27:02 +00001138#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001139 /* On OS X on an msdos filesystem, the inode number is reported
1140 ** incorrectly for zero-size files. See ticket #3260. To work
1141 ** around this problem (we consider it a bug in OS X, not SQLite)
1142 ** we always increase the file size to 1 by writing a single byte
1143 ** prior to accessing the inode number. The one byte written is
1144 ** an ASCII 'S' character which also happens to be the first byte
1145 ** in the header of every SQLite database. In this way, if there
1146 ** is a race condition such that another thread has already populated
1147 ** the first page of the database, no damage is done.
1148 */
drh7ed97b92010-01-20 13:07:21 +00001149 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001150 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001151 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001152 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001153 return SQLITE_IOERR;
1154 }
drh99ab3b12011-03-02 15:09:07 +00001155 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001156 if( rc!=0 ){
1157 pFile->lastErrno = errno;
1158 return SQLITE_IOERR;
1159 }
1160 }
drheb0d74f2009-02-03 15:27:02 +00001161#endif
drh6c7d5c52008-11-21 20:32:33 +00001162
drh8af6c222010-05-14 12:43:01 +00001163 memset(&fileId, 0, sizeof(fileId));
1164 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001165#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001166 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001167#else
drh8af6c222010-05-14 12:43:01 +00001168 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001169#endif
drh8af6c222010-05-14 12:43:01 +00001170 pInode = inodeList;
1171 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1172 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001173 }
drh8af6c222010-05-14 12:43:01 +00001174 if( pInode==0 ){
1175 pInode = sqlite3_malloc( sizeof(*pInode) );
1176 if( pInode==0 ){
1177 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001178 }
drh8af6c222010-05-14 12:43:01 +00001179 memset(pInode, 0, sizeof(*pInode));
1180 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1181 pInode->nRef = 1;
1182 pInode->pNext = inodeList;
1183 pInode->pPrev = 0;
1184 if( inodeList ) inodeList->pPrev = pInode;
1185 inodeList = pInode;
1186 }else{
1187 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001188 }
drh8af6c222010-05-14 12:43:01 +00001189 *ppInode = pInode;
1190 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001191}
drh6c7d5c52008-11-21 20:32:33 +00001192
aswift5b1a2562008-08-22 00:22:35 +00001193
1194/*
danielk197713adf8a2004-06-03 16:08:41 +00001195** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001196** file by this or any other process. If such a lock is held, set *pResOut
1197** to a non-zero value otherwise *pResOut is set to zero. The return value
1198** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001199*/
danielk1977861f7452008-06-05 11:39:11 +00001200static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001201 int rc = SQLITE_OK;
1202 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001203 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001204
danielk1977861f7452008-06-05 11:39:11 +00001205 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1206
drh054889e2005-11-30 03:20:31 +00001207 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001208 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001209
1210 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001211 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001212 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001213 }
1214
drh2ac3ee92004-06-07 16:27:46 +00001215 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001216 */
danielk197709480a92009-02-09 05:32:32 +00001217#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001218 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001219 struct flock lock;
1220 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001221 lock.l_start = RESERVED_BYTE;
1222 lock.l_len = 1;
1223 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001224 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1225 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1226 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001227 } else if( lock.l_type!=F_UNLCK ){
1228 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001229 }
1230 }
danielk197709480a92009-02-09 05:32:32 +00001231#endif
danielk197713adf8a2004-06-03 16:08:41 +00001232
drh6c7d5c52008-11-21 20:32:33 +00001233 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001234 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001235
aswift5b1a2562008-08-22 00:22:35 +00001236 *pResOut = reserved;
1237 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001238}
1239
1240/*
drha7e61d82011-03-12 17:02:57 +00001241** Attempt to set a system-lock on the file pFile. The lock is
1242** described by pLock.
1243**
drh77197112011-03-15 19:08:48 +00001244** If the pFile was opened read/write from unix-excl, then the only lock
1245** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001246** the first time any lock is attempted. All subsequent system locking
1247** operations become no-ops. Locking operations still happen internally,
1248** in order to coordinate access between separate database connections
1249** within this process, but all of that is handled in memory and the
1250** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001251**
1252** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1253** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1254** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001255**
1256** Zero is returned if the call completes successfully, or -1 if a call
1257** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001258*/
1259static int unixFileLock(unixFile *pFile, struct flock *pLock){
1260 int rc;
drh3cb93392011-03-12 18:10:44 +00001261 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001262 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001263 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001264 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1265 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1266 ){
drh3cb93392011-03-12 18:10:44 +00001267 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001268 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001269 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001270 lock.l_whence = SEEK_SET;
1271 lock.l_start = SHARED_FIRST;
1272 lock.l_len = SHARED_SIZE;
1273 lock.l_type = F_WRLCK;
1274 rc = osFcntl(pFile->h, F_SETLK, &lock);
1275 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001276 pInode->bProcessLock = 1;
1277 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001278 }else{
1279 rc = 0;
1280 }
1281 }else{
1282 rc = osFcntl(pFile->h, F_SETLK, pLock);
1283 }
1284 return rc;
1285}
1286
1287/*
drh308c2a52010-05-14 11:30:18 +00001288** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001289** of the following:
1290**
drh2ac3ee92004-06-07 16:27:46 +00001291** (1) SHARED_LOCK
1292** (2) RESERVED_LOCK
1293** (3) PENDING_LOCK
1294** (4) EXCLUSIVE_LOCK
1295**
drhb3e04342004-06-08 00:47:47 +00001296** Sometimes when requesting one lock state, additional lock states
1297** are inserted in between. The locking might fail on one of the later
1298** transitions leaving the lock state different from what it started but
1299** still short of its goal. The following chart shows the allowed
1300** transitions and the inserted intermediate states:
1301**
1302** UNLOCKED -> SHARED
1303** SHARED -> RESERVED
1304** SHARED -> (PENDING) -> EXCLUSIVE
1305** RESERVED -> (PENDING) -> EXCLUSIVE
1306** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001307**
drha6abd042004-06-09 17:37:22 +00001308** This routine will only increase a lock. Use the sqlite3OsUnlock()
1309** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001310*/
drh308c2a52010-05-14 11:30:18 +00001311static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001312 /* The following describes the implementation of the various locks and
1313 ** lock transitions in terms of the POSIX advisory shared and exclusive
1314 ** lock primitives (called read-locks and write-locks below, to avoid
1315 ** confusion with SQLite lock names). The algorithms are complicated
1316 ** slightly in order to be compatible with windows systems simultaneously
1317 ** accessing the same database file, in case that is ever required.
1318 **
1319 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1320 ** byte', each single bytes at well known offsets, and the 'shared byte
1321 ** range', a range of 510 bytes at a well known offset.
1322 **
1323 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1324 ** byte'. If this is successful, a random byte from the 'shared byte
1325 ** range' is read-locked and the lock on the 'pending byte' released.
1326 **
danielk197790ba3bd2004-06-25 08:32:25 +00001327 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1328 ** A RESERVED lock is implemented by grabbing a write-lock on the
1329 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001330 **
1331 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001332 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1333 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1334 ** obtained, but existing SHARED locks are allowed to persist. A process
1335 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1336 ** This property is used by the algorithm for rolling back a journal file
1337 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001338 **
danielk197790ba3bd2004-06-25 08:32:25 +00001339 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1340 ** implemented by obtaining a write-lock on the entire 'shared byte
1341 ** range'. Since all other locks require a read-lock on one of the bytes
1342 ** within this range, this ensures that no other locks are held on the
1343 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001344 **
1345 ** The reason a single byte cannot be used instead of the 'shared byte
1346 ** range' is that some versions of windows do not support read-locks. By
1347 ** locking a random byte from a range, concurrent SHARED locks may exist
1348 ** even if the locking primitive used is always a write-lock.
1349 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001350 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001351 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001352 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001353 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001354 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001355
drh054889e2005-11-30 03:20:31 +00001356 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001357 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1358 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001359 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001360
1361 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001362 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001363 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001364 */
drh308c2a52010-05-14 11:30:18 +00001365 if( pFile->eFileLock>=eFileLock ){
1366 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1367 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001368 return SQLITE_OK;
1369 }
1370
drh0c2694b2009-09-03 16:23:44 +00001371 /* Make sure the locking sequence is correct.
1372 ** (1) We never move from unlocked to anything higher than shared lock.
1373 ** (2) SQLite never explicitly requests a pendig lock.
1374 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001375 */
drh308c2a52010-05-14 11:30:18 +00001376 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1377 assert( eFileLock!=PENDING_LOCK );
1378 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001379
drh8af6c222010-05-14 12:43:01 +00001380 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001381 */
drh6c7d5c52008-11-21 20:32:33 +00001382 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001383 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001384
danielk1977ad94b582007-08-20 06:44:22 +00001385 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001386 ** handle that precludes the requested lock, return BUSY.
1387 */
drh8af6c222010-05-14 12:43:01 +00001388 if( (pFile->eFileLock!=pInode->eFileLock &&
1389 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001390 ){
1391 rc = SQLITE_BUSY;
1392 goto end_lock;
1393 }
1394
1395 /* If a SHARED lock is requested, and some thread using this PID already
1396 ** has a SHARED or RESERVED lock, then increment reference counts and
1397 ** return SQLITE_OK.
1398 */
drh308c2a52010-05-14 11:30:18 +00001399 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001400 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001401 assert( eFileLock==SHARED_LOCK );
1402 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001403 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001404 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001405 pInode->nShared++;
1406 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001407 goto end_lock;
1408 }
1409
danielk19779a1d0ab2004-06-01 14:09:28 +00001410
drh3cde3bb2004-06-12 02:17:14 +00001411 /* A PENDING lock is needed before acquiring a SHARED lock and before
1412 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1413 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001414 */
drh0c2694b2009-09-03 16:23:44 +00001415 lock.l_len = 1L;
1416 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001417 if( eFileLock==SHARED_LOCK
1418 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001419 ){
drh308c2a52010-05-14 11:30:18 +00001420 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001421 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001422 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001423 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001424 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001425 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001426 pFile->lastErrno = tErrno;
1427 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001428 goto end_lock;
1429 }
drh3cde3bb2004-06-12 02:17:14 +00001430 }
1431
1432
1433 /* If control gets to this point, then actually go ahead and make
1434 ** operating system calls for the specified lock.
1435 */
drh308c2a52010-05-14 11:30:18 +00001436 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001437 assert( pInode->nShared==0 );
1438 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001439 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001440
drh2ac3ee92004-06-07 16:27:46 +00001441 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001442 lock.l_start = SHARED_FIRST;
1443 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001444 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001445 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001446 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001447 }
dan661d71a2011-03-30 19:08:03 +00001448
drh2ac3ee92004-06-07 16:27:46 +00001449 /* Drop the temporary PENDING lock */
1450 lock.l_start = PENDING_BYTE;
1451 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001452 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001453 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1454 /* This could happen with a network mount */
1455 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001456 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001457 }
dan661d71a2011-03-30 19:08:03 +00001458
1459 if( rc ){
1460 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001461 pFile->lastErrno = tErrno;
1462 }
dan661d71a2011-03-30 19:08:03 +00001463 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001464 }else{
drh308c2a52010-05-14 11:30:18 +00001465 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001466 pInode->nLock++;
1467 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001468 }
drh8af6c222010-05-14 12:43:01 +00001469 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001470 /* We are trying for an exclusive lock but another thread in this
1471 ** same process is still holding a shared lock. */
1472 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001473 }else{
drh3cde3bb2004-06-12 02:17:14 +00001474 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001475 ** assumed that there is a SHARED or greater lock on the file
1476 ** already.
1477 */
drh308c2a52010-05-14 11:30:18 +00001478 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001479 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001480
1481 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1482 if( eFileLock==RESERVED_LOCK ){
1483 lock.l_start = RESERVED_BYTE;
1484 lock.l_len = 1L;
1485 }else{
1486 lock.l_start = SHARED_FIRST;
1487 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001488 }
dan661d71a2011-03-30 19:08:03 +00001489
1490 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001491 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001492 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001493 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001494 pFile->lastErrno = tErrno;
1495 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001496 }
drhbbd42a62004-05-22 17:41:58 +00001497 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001498
drh8f941bc2009-01-14 23:03:40 +00001499
1500#ifndef NDEBUG
1501 /* Set up the transaction-counter change checking flags when
1502 ** transitioning from a SHARED to a RESERVED lock. The change
1503 ** from SHARED to RESERVED marks the beginning of a normal
1504 ** write operation (not a hot journal rollback).
1505 */
1506 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001507 && pFile->eFileLock<=SHARED_LOCK
1508 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001509 ){
1510 pFile->transCntrChng = 0;
1511 pFile->dbUpdate = 0;
1512 pFile->inNormalWrite = 1;
1513 }
1514#endif
1515
1516
danielk1977ecb2a962004-06-02 06:30:16 +00001517 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001518 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001519 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001520 }else if( eFileLock==EXCLUSIVE_LOCK ){
1521 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001522 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001523 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001524
1525end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001526 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001527 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1528 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001529 return rc;
1530}
1531
1532/*
dan08da86a2009-08-21 17:18:03 +00001533** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001534** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001535*/
1536static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001537 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001538 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001539 p->pNext = pInode->pUnused;
1540 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001541 pFile->h = -1;
1542 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001543}
1544
1545/*
drh308c2a52010-05-14 11:30:18 +00001546** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001547** must be either NO_LOCK or SHARED_LOCK.
1548**
1549** If the locking level of the file descriptor is already at or below
1550** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001551**
1552** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1553** the byte range is divided into 2 parts and the first part is unlocked then
1554** set to a read lock, then the other part is simply unlocked. This works
1555** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1556** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001557*/
drha7e61d82011-03-12 17:02:57 +00001558static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001559 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001560 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001561 struct flock lock;
1562 int rc = SQLITE_OK;
1563 int h;
drha6abd042004-06-09 17:37:22 +00001564
drh054889e2005-11-30 03:20:31 +00001565 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001566 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001567 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001568 getpid()));
drha6abd042004-06-09 17:37:22 +00001569
drh308c2a52010-05-14 11:30:18 +00001570 assert( eFileLock<=SHARED_LOCK );
1571 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001572 return SQLITE_OK;
1573 }
drh6c7d5c52008-11-21 20:32:33 +00001574 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001575 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001576 pInode = pFile->pInode;
1577 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001578 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001579 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001580 SimulateIOErrorBenign(1);
1581 SimulateIOError( h=(-1) )
1582 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001583
1584#ifndef NDEBUG
1585 /* When reducing a lock such that other processes can start
1586 ** reading the database file again, make sure that the
1587 ** transaction counter was updated if any part of the database
1588 ** file changed. If the transaction counter is not updated,
1589 ** other connections to the same file might not realize that
1590 ** the file has changed and hence might not know to flush their
1591 ** cache. The use of a stale cache can lead to database corruption.
1592 */
dan7c246102010-04-12 19:00:29 +00001593#if 0
drh8f941bc2009-01-14 23:03:40 +00001594 assert( pFile->inNormalWrite==0
1595 || pFile->dbUpdate==0
1596 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001597#endif
drh8f941bc2009-01-14 23:03:40 +00001598 pFile->inNormalWrite = 0;
1599#endif
1600
drh7ed97b92010-01-20 13:07:21 +00001601 /* downgrading to a shared lock on NFS involves clearing the write lock
1602 ** before establishing the readlock - to avoid a race condition we downgrade
1603 ** the lock in 2 blocks, so that part of the range will be covered by a
1604 ** write lock until the rest is covered by a read lock:
1605 ** 1: [WWWWW]
1606 ** 2: [....W]
1607 ** 3: [RRRRW]
1608 ** 4: [RRRR.]
1609 */
drh308c2a52010-05-14 11:30:18 +00001610 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001611
1612#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001613 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001614 assert( handleNFSUnlock==0 );
1615#endif
1616#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001617 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001618 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001619 off_t divSize = SHARED_SIZE - 1;
1620
1621 lock.l_type = F_UNLCK;
1622 lock.l_whence = SEEK_SET;
1623 lock.l_start = SHARED_FIRST;
1624 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001625 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001626 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001627 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001628 if( IS_LOCK_ERROR(rc) ){
1629 pFile->lastErrno = tErrno;
1630 }
1631 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001632 }
drh7ed97b92010-01-20 13:07:21 +00001633 lock.l_type = F_RDLCK;
1634 lock.l_whence = SEEK_SET;
1635 lock.l_start = SHARED_FIRST;
1636 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001637 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001638 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001639 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1640 if( IS_LOCK_ERROR(rc) ){
1641 pFile->lastErrno = tErrno;
1642 }
1643 goto end_unlock;
1644 }
1645 lock.l_type = F_UNLCK;
1646 lock.l_whence = SEEK_SET;
1647 lock.l_start = SHARED_FIRST+divSize;
1648 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001649 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001650 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001651 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001652 if( IS_LOCK_ERROR(rc) ){
1653 pFile->lastErrno = tErrno;
1654 }
1655 goto end_unlock;
1656 }
drh30f776f2011-02-25 03:25:07 +00001657 }else
1658#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1659 {
drh7ed97b92010-01-20 13:07:21 +00001660 lock.l_type = F_RDLCK;
1661 lock.l_whence = SEEK_SET;
1662 lock.l_start = SHARED_FIRST;
1663 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001664 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001665 /* In theory, the call to unixFileLock() cannot fail because another
1666 ** process is holding an incompatible lock. If it does, this
1667 ** indicates that the other process is not following the locking
1668 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1669 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1670 ** an assert to fail). */
1671 rc = SQLITE_IOERR_RDLOCK;
1672 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001673 goto end_unlock;
1674 }
drh9c105bb2004-10-02 20:38:28 +00001675 }
1676 }
drhbbd42a62004-05-22 17:41:58 +00001677 lock.l_type = F_UNLCK;
1678 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001679 lock.l_start = PENDING_BYTE;
1680 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001681 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001682 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001683 }else{
danea83bc62011-04-01 11:56:32 +00001684 rc = SQLITE_IOERR_UNLOCK;
1685 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001686 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001687 }
drhbbd42a62004-05-22 17:41:58 +00001688 }
drh308c2a52010-05-14 11:30:18 +00001689 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001690 /* Decrement the shared lock counter. Release the lock using an
1691 ** OS call only when all threads in this same process have released
1692 ** the lock.
1693 */
drh8af6c222010-05-14 12:43:01 +00001694 pInode->nShared--;
1695 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001696 lock.l_type = F_UNLCK;
1697 lock.l_whence = SEEK_SET;
1698 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001699 SimulateIOErrorBenign(1);
1700 SimulateIOError( h=(-1) )
1701 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001702 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001703 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001704 }else{
danea83bc62011-04-01 11:56:32 +00001705 rc = SQLITE_IOERR_UNLOCK;
1706 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001707 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001708 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001709 }
drha6abd042004-06-09 17:37:22 +00001710 }
1711
drhbbd42a62004-05-22 17:41:58 +00001712 /* Decrement the count of locks against this same file. When the
1713 ** count reaches zero, close any other file descriptors whose close
1714 ** was deferred because of outstanding locks.
1715 */
drh8af6c222010-05-14 12:43:01 +00001716 pInode->nLock--;
1717 assert( pInode->nLock>=0 );
1718 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001719 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001720 }
1721 }
aswift5b1a2562008-08-22 00:22:35 +00001722
1723end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001724 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001725 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001726 return rc;
drhbbd42a62004-05-22 17:41:58 +00001727}
1728
1729/*
drh308c2a52010-05-14 11:30:18 +00001730** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001731** must be either NO_LOCK or SHARED_LOCK.
1732**
1733** If the locking level of the file descriptor is already at or below
1734** the requested locking level, this routine is a no-op.
1735*/
drh308c2a52010-05-14 11:30:18 +00001736static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001737 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001738}
1739
1740/*
danielk1977e339d652008-06-28 11:23:00 +00001741** This function performs the parts of the "close file" operation
1742** common to all locking schemes. It closes the directory and file
1743** handles, if they are valid, and sets all fields of the unixFile
1744** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001745**
1746** It is *not* necessary to hold the mutex when this routine is called,
1747** even on VxWorks. A mutex will be acquired on VxWorks by the
1748** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001749*/
1750static int closeUnixFile(sqlite3_file *id){
1751 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001752 if( pFile->dirfd>=0 ){
1753 robust_close(pFile, pFile->dirfd, __LINE__);
1754 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001755 }
dan661d71a2011-03-30 19:08:03 +00001756 if( pFile->h>=0 ){
1757 robust_close(pFile, pFile->h, __LINE__);
1758 pFile->h = -1;
1759 }
1760#if OS_VXWORKS
1761 if( pFile->pId ){
1762 if( pFile->isDelete ){
1763 unlink(pFile->pId->zCanonicalName);
1764 }
1765 vxworksReleaseFileId(pFile->pId);
1766 pFile->pId = 0;
1767 }
1768#endif
1769 OSTRACE(("CLOSE %-3d\n", pFile->h));
1770 OpenCounter(-1);
1771 sqlite3_free(pFile->pUnused);
1772 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001773 return SQLITE_OK;
1774}
1775
1776/*
danielk1977e3026632004-06-22 11:29:02 +00001777** Close a file.
1778*/
danielk197762079062007-08-15 17:08:46 +00001779static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001780 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001781 unixFile *pFile = (unixFile *)id;
1782 unixUnlock(id, NO_LOCK);
1783 unixEnterMutex();
1784
1785 /* unixFile.pInode is always valid here. Otherwise, a different close
1786 ** routine (e.g. nolockClose()) would be called instead.
1787 */
1788 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1789 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1790 /* If there are outstanding locks, do not actually close the file just
1791 ** yet because that would clear those locks. Instead, add the file
1792 ** descriptor to pInode->pUnused list. It will be automatically closed
1793 ** when the last lock is cleared.
1794 */
1795 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001796 }
dan661d71a2011-03-30 19:08:03 +00001797 releaseInodeInfo(pFile);
1798 rc = closeUnixFile(id);
1799 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001800 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001801}
1802
drh734c9862008-11-28 15:37:20 +00001803/************** End of the posix advisory lock implementation *****************
1804******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001805
drh734c9862008-11-28 15:37:20 +00001806/******************************************************************************
1807****************************** No-op Locking **********************************
1808**
1809** Of the various locking implementations available, this is by far the
1810** simplest: locking is ignored. No attempt is made to lock the database
1811** file for reading or writing.
1812**
1813** This locking mode is appropriate for use on read-only databases
1814** (ex: databases that are burned into CD-ROM, for example.) It can
1815** also be used if the application employs some external mechanism to
1816** prevent simultaneous access of the same database by two or more
1817** database connections. But there is a serious risk of database
1818** corruption if this locking mode is used in situations where multiple
1819** database connections are accessing the same database file at the same
1820** time and one or more of those connections are writing.
1821*/
drhbfe66312006-10-03 17:40:40 +00001822
drh734c9862008-11-28 15:37:20 +00001823static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1824 UNUSED_PARAMETER(NotUsed);
1825 *pResOut = 0;
1826 return SQLITE_OK;
1827}
drh734c9862008-11-28 15:37:20 +00001828static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1829 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1830 return SQLITE_OK;
1831}
drh734c9862008-11-28 15:37:20 +00001832static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1833 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1834 return SQLITE_OK;
1835}
1836
1837/*
drh9b35ea62008-11-29 02:20:26 +00001838** Close the file.
drh734c9862008-11-28 15:37:20 +00001839*/
1840static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001841 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001842}
1843
1844/******************* End of the no-op lock implementation *********************
1845******************************************************************************/
1846
1847/******************************************************************************
1848************************* Begin dot-file Locking ******************************
1849**
drh0c2694b2009-09-03 16:23:44 +00001850** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001851** files in order to control access to the database. This works on just
1852** about every filesystem imaginable. But there are serious downsides:
1853**
1854** (1) There is zero concurrency. A single reader blocks all other
1855** connections from reading or writing the database.
1856**
1857** (2) An application crash or power loss can leave stale lock files
1858** sitting around that need to be cleared manually.
1859**
1860** Nevertheless, a dotlock is an appropriate locking mode for use if no
1861** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001862**
1863** Dotfile locking works by creating a file in the same directory as the
1864** database and with the same name but with a ".lock" extension added.
1865** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1866** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001867*/
1868
1869/*
1870** The file suffix added to the data base filename in order to create the
1871** lock file.
1872*/
1873#define DOTLOCK_SUFFIX ".lock"
1874
drh7708e972008-11-29 00:56:52 +00001875/*
1876** This routine checks if there is a RESERVED lock held on the specified
1877** file by this or any other process. If such a lock is held, set *pResOut
1878** to a non-zero value otherwise *pResOut is set to zero. The return value
1879** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1880**
1881** In dotfile locking, either a lock exists or it does not. So in this
1882** variation of CheckReservedLock(), *pResOut is set to true if any lock
1883** is held on the file and false if the file is unlocked.
1884*/
drh734c9862008-11-28 15:37:20 +00001885static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1886 int rc = SQLITE_OK;
1887 int reserved = 0;
1888 unixFile *pFile = (unixFile*)id;
1889
1890 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1891
1892 assert( pFile );
1893
1894 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001895 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001896 /* Either this connection or some other connection in the same process
1897 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001898 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001899 }else{
1900 /* The lock is held if and only if the lockfile exists */
1901 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001902 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001903 }
drh308c2a52010-05-14 11:30:18 +00001904 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001905 *pResOut = reserved;
1906 return rc;
1907}
1908
drh7708e972008-11-29 00:56:52 +00001909/*
drh308c2a52010-05-14 11:30:18 +00001910** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001911** of the following:
1912**
1913** (1) SHARED_LOCK
1914** (2) RESERVED_LOCK
1915** (3) PENDING_LOCK
1916** (4) EXCLUSIVE_LOCK
1917**
1918** Sometimes when requesting one lock state, additional lock states
1919** are inserted in between. The locking might fail on one of the later
1920** transitions leaving the lock state different from what it started but
1921** still short of its goal. The following chart shows the allowed
1922** transitions and the inserted intermediate states:
1923**
1924** UNLOCKED -> SHARED
1925** SHARED -> RESERVED
1926** SHARED -> (PENDING) -> EXCLUSIVE
1927** RESERVED -> (PENDING) -> EXCLUSIVE
1928** PENDING -> EXCLUSIVE
1929**
1930** This routine will only increase a lock. Use the sqlite3OsUnlock()
1931** routine to lower a locking level.
1932**
1933** With dotfile locking, we really only support state (4): EXCLUSIVE.
1934** But we track the other locking levels internally.
1935*/
drh308c2a52010-05-14 11:30:18 +00001936static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001937 unixFile *pFile = (unixFile*)id;
1938 int fd;
1939 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001940 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001941
drh7708e972008-11-29 00:56:52 +00001942
1943 /* If we have any lock, then the lock file already exists. All we have
1944 ** to do is adjust our internal record of the lock level.
1945 */
drh308c2a52010-05-14 11:30:18 +00001946 if( pFile->eFileLock > NO_LOCK ){
1947 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001948 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001949#ifdef HAVE_UTIME
1950 utime(zLockFile, NULL);
1951#else
drh734c9862008-11-28 15:37:20 +00001952 utimes(zLockFile, NULL);
1953#endif
drh7708e972008-11-29 00:56:52 +00001954 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001955 }
1956
1957 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001958 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001959 if( fd<0 ){
1960 /* failed to open/create the file, someone else may have stolen the lock */
1961 int tErrno = errno;
1962 if( EEXIST == tErrno ){
1963 rc = SQLITE_BUSY;
1964 } else {
1965 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1966 if( IS_LOCK_ERROR(rc) ){
1967 pFile->lastErrno = tErrno;
1968 }
1969 }
drh7708e972008-11-29 00:56:52 +00001970 return rc;
drh734c9862008-11-28 15:37:20 +00001971 }
drh0e9365c2011-03-02 02:08:13 +00001972 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001973
1974 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001975 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001976 return rc;
1977}
1978
drh7708e972008-11-29 00:56:52 +00001979/*
drh308c2a52010-05-14 11:30:18 +00001980** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001981** must be either NO_LOCK or SHARED_LOCK.
1982**
1983** If the locking level of the file descriptor is already at or below
1984** the requested locking level, this routine is a no-op.
1985**
1986** When the locking level reaches NO_LOCK, delete the lock file.
1987*/
drh308c2a52010-05-14 11:30:18 +00001988static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001989 unixFile *pFile = (unixFile*)id;
1990 char *zLockFile = (char *)pFile->lockingContext;
1991
1992 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001993 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1994 pFile->eFileLock, getpid()));
1995 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001996
1997 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001998 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001999 return SQLITE_OK;
2000 }
drh7708e972008-11-29 00:56:52 +00002001
2002 /* To downgrade to shared, simply update our internal notion of the
2003 ** lock state. No need to mess with the file on disk.
2004 */
drh308c2a52010-05-14 11:30:18 +00002005 if( eFileLock==SHARED_LOCK ){
2006 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002007 return SQLITE_OK;
2008 }
2009
drh7708e972008-11-29 00:56:52 +00002010 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002011 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00002012 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00002013 int rc = 0;
2014 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002015 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002016 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002017 }
2018 if( IS_LOCK_ERROR(rc) ){
2019 pFile->lastErrno = tErrno;
2020 }
2021 return rc;
2022 }
drh308c2a52010-05-14 11:30:18 +00002023 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002024 return SQLITE_OK;
2025}
2026
2027/*
drh9b35ea62008-11-29 02:20:26 +00002028** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002029*/
2030static int dotlockClose(sqlite3_file *id) {
2031 int rc;
2032 if( id ){
2033 unixFile *pFile = (unixFile*)id;
2034 dotlockUnlock(id, NO_LOCK);
2035 sqlite3_free(pFile->lockingContext);
2036 }
drh734c9862008-11-28 15:37:20 +00002037 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002038 return rc;
2039}
2040/****************** End of the dot-file lock implementation *******************
2041******************************************************************************/
2042
2043/******************************************************************************
2044************************** Begin flock Locking ********************************
2045**
2046** Use the flock() system call to do file locking.
2047**
drh6b9d6dd2008-12-03 19:34:47 +00002048** flock() locking is like dot-file locking in that the various
2049** fine-grain locking levels supported by SQLite are collapsed into
2050** a single exclusive lock. In other words, SHARED, RESERVED, and
2051** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2052** still works when you do this, but concurrency is reduced since
2053** only a single process can be reading the database at a time.
2054**
drh734c9862008-11-28 15:37:20 +00002055** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2056** compiling for VXWORKS.
2057*/
2058#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002059
drh6b9d6dd2008-12-03 19:34:47 +00002060/*
drhff812312011-02-23 13:33:46 +00002061** Retry flock() calls that fail with EINTR
2062*/
2063#ifdef EINTR
2064static int robust_flock(int fd, int op){
2065 int rc;
2066 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2067 return rc;
2068}
2069#else
drh5c819272011-02-23 14:00:12 +00002070# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002071#endif
2072
2073
2074/*
drh6b9d6dd2008-12-03 19:34:47 +00002075** This routine checks if there is a RESERVED lock held on the specified
2076** file by this or any other process. If such a lock is held, set *pResOut
2077** to a non-zero value otherwise *pResOut is set to zero. The return value
2078** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2079*/
drh734c9862008-11-28 15:37:20 +00002080static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2081 int rc = SQLITE_OK;
2082 int reserved = 0;
2083 unixFile *pFile = (unixFile*)id;
2084
2085 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2086
2087 assert( pFile );
2088
2089 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002090 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002091 reserved = 1;
2092 }
2093
2094 /* Otherwise see if some other process holds it. */
2095 if( !reserved ){
2096 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002097 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002098 if( !lrc ){
2099 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002100 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002101 if ( lrc ) {
2102 int tErrno = errno;
2103 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002104 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002105 if( IS_LOCK_ERROR(lrc) ){
2106 pFile->lastErrno = tErrno;
2107 rc = lrc;
2108 }
2109 }
2110 } else {
2111 int tErrno = errno;
2112 reserved = 1;
2113 /* someone else might have it reserved */
2114 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2115 if( IS_LOCK_ERROR(lrc) ){
2116 pFile->lastErrno = tErrno;
2117 rc = lrc;
2118 }
2119 }
2120 }
drh308c2a52010-05-14 11:30:18 +00002121 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002122
2123#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2124 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2125 rc = SQLITE_OK;
2126 reserved=1;
2127 }
2128#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2129 *pResOut = reserved;
2130 return rc;
2131}
2132
drh6b9d6dd2008-12-03 19:34:47 +00002133/*
drh308c2a52010-05-14 11:30:18 +00002134** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002135** of the following:
2136**
2137** (1) SHARED_LOCK
2138** (2) RESERVED_LOCK
2139** (3) PENDING_LOCK
2140** (4) EXCLUSIVE_LOCK
2141**
2142** Sometimes when requesting one lock state, additional lock states
2143** are inserted in between. The locking might fail on one of the later
2144** transitions leaving the lock state different from what it started but
2145** still short of its goal. The following chart shows the allowed
2146** transitions and the inserted intermediate states:
2147**
2148** UNLOCKED -> SHARED
2149** SHARED -> RESERVED
2150** SHARED -> (PENDING) -> EXCLUSIVE
2151** RESERVED -> (PENDING) -> EXCLUSIVE
2152** PENDING -> EXCLUSIVE
2153**
2154** flock() only really support EXCLUSIVE locks. We track intermediate
2155** lock states in the sqlite3_file structure, but all locks SHARED or
2156** above are really EXCLUSIVE locks and exclude all other processes from
2157** access the file.
2158**
2159** This routine will only increase a lock. Use the sqlite3OsUnlock()
2160** routine to lower a locking level.
2161*/
drh308c2a52010-05-14 11:30:18 +00002162static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002163 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002164 unixFile *pFile = (unixFile*)id;
2165
2166 assert( pFile );
2167
2168 /* if we already have a lock, it is exclusive.
2169 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002170 if (pFile->eFileLock > NO_LOCK) {
2171 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002172 return SQLITE_OK;
2173 }
2174
2175 /* grab an exclusive lock */
2176
drhff812312011-02-23 13:33:46 +00002177 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002178 int tErrno = errno;
2179 /* didn't get, must be busy */
2180 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2181 if( IS_LOCK_ERROR(rc) ){
2182 pFile->lastErrno = tErrno;
2183 }
2184 } else {
2185 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002186 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002187 }
drh308c2a52010-05-14 11:30:18 +00002188 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2189 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002190#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2191 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2192 rc = SQLITE_BUSY;
2193 }
2194#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2195 return rc;
2196}
2197
drh6b9d6dd2008-12-03 19:34:47 +00002198
2199/*
drh308c2a52010-05-14 11:30:18 +00002200** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002201** must be either NO_LOCK or SHARED_LOCK.
2202**
2203** If the locking level of the file descriptor is already at or below
2204** the requested locking level, this routine is a no-op.
2205*/
drh308c2a52010-05-14 11:30:18 +00002206static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002207 unixFile *pFile = (unixFile*)id;
2208
2209 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002210 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2211 pFile->eFileLock, getpid()));
2212 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002213
2214 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002215 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002216 return SQLITE_OK;
2217 }
2218
2219 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002220 if (eFileLock==SHARED_LOCK) {
2221 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002222 return SQLITE_OK;
2223 }
2224
2225 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002226 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002227#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002228 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002229#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002230 return SQLITE_IOERR_UNLOCK;
2231 }else{
drh308c2a52010-05-14 11:30:18 +00002232 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002233 return SQLITE_OK;
2234 }
2235}
2236
2237/*
2238** Close a file.
2239*/
2240static int flockClose(sqlite3_file *id) {
2241 if( id ){
2242 flockUnlock(id, NO_LOCK);
2243 }
2244 return closeUnixFile(id);
2245}
2246
2247#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2248
2249/******************* End of the flock lock implementation *********************
2250******************************************************************************/
2251
2252/******************************************************************************
2253************************ Begin Named Semaphore Locking ************************
2254**
2255** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002256**
2257** Semaphore locking is like dot-lock and flock in that it really only
2258** supports EXCLUSIVE locking. Only a single process can read or write
2259** the database file at a time. This reduces potential concurrency, but
2260** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002261*/
2262#if OS_VXWORKS
2263
drh6b9d6dd2008-12-03 19:34:47 +00002264/*
2265** This routine checks if there is a RESERVED lock held on the specified
2266** file by this or any other process. If such a lock is held, set *pResOut
2267** to a non-zero value otherwise *pResOut is set to zero. The return value
2268** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2269*/
drh734c9862008-11-28 15:37:20 +00002270static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2271 int rc = SQLITE_OK;
2272 int reserved = 0;
2273 unixFile *pFile = (unixFile*)id;
2274
2275 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2276
2277 assert( pFile );
2278
2279 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002280 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002281 reserved = 1;
2282 }
2283
2284 /* Otherwise see if some other process holds it. */
2285 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002286 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002287 struct stat statBuf;
2288
2289 if( sem_trywait(pSem)==-1 ){
2290 int tErrno = errno;
2291 if( EAGAIN != tErrno ){
2292 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2293 pFile->lastErrno = tErrno;
2294 } else {
2295 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002296 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002297 }
2298 }else{
2299 /* we could have it if we want it */
2300 sem_post(pSem);
2301 }
2302 }
drh308c2a52010-05-14 11:30:18 +00002303 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002304
2305 *pResOut = reserved;
2306 return rc;
2307}
2308
drh6b9d6dd2008-12-03 19:34:47 +00002309/*
drh308c2a52010-05-14 11:30:18 +00002310** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002311** of the following:
2312**
2313** (1) SHARED_LOCK
2314** (2) RESERVED_LOCK
2315** (3) PENDING_LOCK
2316** (4) EXCLUSIVE_LOCK
2317**
2318** Sometimes when requesting one lock state, additional lock states
2319** are inserted in between. The locking might fail on one of the later
2320** transitions leaving the lock state different from what it started but
2321** still short of its goal. The following chart shows the allowed
2322** transitions and the inserted intermediate states:
2323**
2324** UNLOCKED -> SHARED
2325** SHARED -> RESERVED
2326** SHARED -> (PENDING) -> EXCLUSIVE
2327** RESERVED -> (PENDING) -> EXCLUSIVE
2328** PENDING -> EXCLUSIVE
2329**
2330** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2331** lock states in the sqlite3_file structure, but all locks SHARED or
2332** above are really EXCLUSIVE locks and exclude all other processes from
2333** access the file.
2334**
2335** This routine will only increase a lock. Use the sqlite3OsUnlock()
2336** routine to lower a locking level.
2337*/
drh308c2a52010-05-14 11:30:18 +00002338static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002339 unixFile *pFile = (unixFile*)id;
2340 int fd;
drh8af6c222010-05-14 12:43:01 +00002341 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002342 int rc = SQLITE_OK;
2343
2344 /* if we already have a lock, it is exclusive.
2345 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002346 if (pFile->eFileLock > NO_LOCK) {
2347 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002348 rc = SQLITE_OK;
2349 goto sem_end_lock;
2350 }
2351
2352 /* lock semaphore now but bail out when already locked. */
2353 if( sem_trywait(pSem)==-1 ){
2354 rc = SQLITE_BUSY;
2355 goto sem_end_lock;
2356 }
2357
2358 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002359 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002360
2361 sem_end_lock:
2362 return rc;
2363}
2364
drh6b9d6dd2008-12-03 19:34:47 +00002365/*
drh308c2a52010-05-14 11:30:18 +00002366** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002367** must be either NO_LOCK or SHARED_LOCK.
2368**
2369** If the locking level of the file descriptor is already at or below
2370** the requested locking level, this routine is a no-op.
2371*/
drh308c2a52010-05-14 11:30:18 +00002372static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002373 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002374 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002375
2376 assert( pFile );
2377 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002378 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2379 pFile->eFileLock, getpid()));
2380 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002381
2382 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002383 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002384 return SQLITE_OK;
2385 }
2386
2387 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002388 if (eFileLock==SHARED_LOCK) {
2389 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002390 return SQLITE_OK;
2391 }
2392
2393 /* no, really unlock. */
2394 if ( sem_post(pSem)==-1 ) {
2395 int rc, tErrno = errno;
2396 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2397 if( IS_LOCK_ERROR(rc) ){
2398 pFile->lastErrno = tErrno;
2399 }
2400 return rc;
2401 }
drh308c2a52010-05-14 11:30:18 +00002402 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002403 return SQLITE_OK;
2404}
2405
2406/*
2407 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002408 */
drh734c9862008-11-28 15:37:20 +00002409static int semClose(sqlite3_file *id) {
2410 if( id ){
2411 unixFile *pFile = (unixFile*)id;
2412 semUnlock(id, NO_LOCK);
2413 assert( pFile );
2414 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002415 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002416 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002417 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002418 }
2419 return SQLITE_OK;
2420}
2421
2422#endif /* OS_VXWORKS */
2423/*
2424** Named semaphore locking is only available on VxWorks.
2425**
2426*************** End of the named semaphore lock implementation ****************
2427******************************************************************************/
2428
2429
2430/******************************************************************************
2431*************************** Begin AFP Locking *********************************
2432**
2433** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2434** on Apple Macintosh computers - both OS9 and OSX.
2435**
2436** Third-party implementations of AFP are available. But this code here
2437** only works on OSX.
2438*/
2439
drhd2cb50b2009-01-09 21:41:17 +00002440#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002441/*
2442** The afpLockingContext structure contains all afp lock specific state
2443*/
drhbfe66312006-10-03 17:40:40 +00002444typedef struct afpLockingContext afpLockingContext;
2445struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002446 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002447 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002448};
2449
2450struct ByteRangeLockPB2
2451{
2452 unsigned long long offset; /* offset to first byte to lock */
2453 unsigned long long length; /* nbr of bytes to lock */
2454 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2455 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2456 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2457 int fd; /* file desc to assoc this lock with */
2458};
2459
drhfd131da2007-08-07 17:13:03 +00002460#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002461
drh6b9d6dd2008-12-03 19:34:47 +00002462/*
2463** This is a utility for setting or clearing a bit-range lock on an
2464** AFP filesystem.
2465**
2466** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2467*/
2468static int afpSetLock(
2469 const char *path, /* Name of the file to be locked or unlocked */
2470 unixFile *pFile, /* Open file descriptor on path */
2471 unsigned long long offset, /* First byte to be locked */
2472 unsigned long long length, /* Number of bytes to lock */
2473 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002474){
drh6b9d6dd2008-12-03 19:34:47 +00002475 struct ByteRangeLockPB2 pb;
2476 int err;
drhbfe66312006-10-03 17:40:40 +00002477
2478 pb.unLockFlag = setLockFlag ? 0 : 1;
2479 pb.startEndFlag = 0;
2480 pb.offset = offset;
2481 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002482 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002483
drh308c2a52010-05-14 11:30:18 +00002484 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002485 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002486 offset, length));
drhbfe66312006-10-03 17:40:40 +00002487 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2488 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002489 int rc;
2490 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002491 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2492 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002493#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2494 rc = SQLITE_BUSY;
2495#else
drh734c9862008-11-28 15:37:20 +00002496 rc = sqliteErrorFromPosixError(tErrno,
2497 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002498#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002499 if( IS_LOCK_ERROR(rc) ){
2500 pFile->lastErrno = tErrno;
2501 }
2502 return rc;
drhbfe66312006-10-03 17:40:40 +00002503 } else {
aswift5b1a2562008-08-22 00:22:35 +00002504 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002505 }
2506}
2507
drh6b9d6dd2008-12-03 19:34:47 +00002508/*
2509** This routine checks if there is a RESERVED lock held on the specified
2510** file by this or any other process. If such a lock is held, set *pResOut
2511** to a non-zero value otherwise *pResOut is set to zero. The return value
2512** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2513*/
danielk1977e339d652008-06-28 11:23:00 +00002514static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002515 int rc = SQLITE_OK;
2516 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002517 unixFile *pFile = (unixFile*)id;
2518
aswift5b1a2562008-08-22 00:22:35 +00002519 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2520
2521 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002522 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002523 if( context->reserved ){
2524 *pResOut = 1;
2525 return SQLITE_OK;
2526 }
drh8af6c222010-05-14 12:43:01 +00002527 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002528
2529 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002530 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002531 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002532 }
2533
2534 /* Otherwise see if some other process holds it.
2535 */
aswift5b1a2562008-08-22 00:22:35 +00002536 if( !reserved ){
2537 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002538 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002539 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002540 /* if we succeeded in taking the reserved lock, unlock it to restore
2541 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002542 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002543 } else {
2544 /* if we failed to get the lock then someone else must have it */
2545 reserved = 1;
2546 }
2547 if( IS_LOCK_ERROR(lrc) ){
2548 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002549 }
2550 }
drhbfe66312006-10-03 17:40:40 +00002551
drh7ed97b92010-01-20 13:07:21 +00002552 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002553 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002554
2555 *pResOut = reserved;
2556 return rc;
drhbfe66312006-10-03 17:40:40 +00002557}
2558
drh6b9d6dd2008-12-03 19:34:47 +00002559/*
drh308c2a52010-05-14 11:30:18 +00002560** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002561** of the following:
2562**
2563** (1) SHARED_LOCK
2564** (2) RESERVED_LOCK
2565** (3) PENDING_LOCK
2566** (4) EXCLUSIVE_LOCK
2567**
2568** Sometimes when requesting one lock state, additional lock states
2569** are inserted in between. The locking might fail on one of the later
2570** transitions leaving the lock state different from what it started but
2571** still short of its goal. The following chart shows the allowed
2572** transitions and the inserted intermediate states:
2573**
2574** UNLOCKED -> SHARED
2575** SHARED -> RESERVED
2576** SHARED -> (PENDING) -> EXCLUSIVE
2577** RESERVED -> (PENDING) -> EXCLUSIVE
2578** PENDING -> EXCLUSIVE
2579**
2580** This routine will only increase a lock. Use the sqlite3OsUnlock()
2581** routine to lower a locking level.
2582*/
drh308c2a52010-05-14 11:30:18 +00002583static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002584 int rc = SQLITE_OK;
2585 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002586 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002587 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002588
2589 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002590 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2591 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002592 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002593
drhbfe66312006-10-03 17:40:40 +00002594 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002595 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002596 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002597 */
drh308c2a52010-05-14 11:30:18 +00002598 if( pFile->eFileLock>=eFileLock ){
2599 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2600 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002601 return SQLITE_OK;
2602 }
2603
2604 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002605 ** (1) We never move from unlocked to anything higher than shared lock.
2606 ** (2) SQLite never explicitly requests a pendig lock.
2607 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002608 */
drh308c2a52010-05-14 11:30:18 +00002609 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2610 assert( eFileLock!=PENDING_LOCK );
2611 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002612
drh8af6c222010-05-14 12:43:01 +00002613 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002614 */
drh6c7d5c52008-11-21 20:32:33 +00002615 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002616 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002617
2618 /* If some thread using this PID has a lock via a different unixFile*
2619 ** handle that precludes the requested lock, return BUSY.
2620 */
drh8af6c222010-05-14 12:43:01 +00002621 if( (pFile->eFileLock!=pInode->eFileLock &&
2622 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002623 ){
2624 rc = SQLITE_BUSY;
2625 goto afp_end_lock;
2626 }
2627
2628 /* If a SHARED lock is requested, and some thread using this PID already
2629 ** has a SHARED or RESERVED lock, then increment reference counts and
2630 ** return SQLITE_OK.
2631 */
drh308c2a52010-05-14 11:30:18 +00002632 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002633 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002634 assert( eFileLock==SHARED_LOCK );
2635 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002636 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002637 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002638 pInode->nShared++;
2639 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002640 goto afp_end_lock;
2641 }
drhbfe66312006-10-03 17:40:40 +00002642
2643 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002644 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2645 ** be released.
2646 */
drh308c2a52010-05-14 11:30:18 +00002647 if( eFileLock==SHARED_LOCK
2648 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002649 ){
2650 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002651 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002652 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002653 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002654 goto afp_end_lock;
2655 }
2656 }
2657
2658 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002659 ** operating system calls for the specified lock.
2660 */
drh308c2a52010-05-14 11:30:18 +00002661 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002662 int lrc1, lrc2, lrc1Errno;
2663 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002664
drh8af6c222010-05-14 12:43:01 +00002665 assert( pInode->nShared==0 );
2666 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002667
2668 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002669 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002670 /* note that the quality of the randomness doesn't matter that much */
2671 lk = random();
drh8af6c222010-05-14 12:43:01 +00002672 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002673 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002674 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002675 if( IS_LOCK_ERROR(lrc1) ){
2676 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002677 }
aswift5b1a2562008-08-22 00:22:35 +00002678 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002679 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002680
aswift5b1a2562008-08-22 00:22:35 +00002681 if( IS_LOCK_ERROR(lrc1) ) {
2682 pFile->lastErrno = lrc1Errno;
2683 rc = lrc1;
2684 goto afp_end_lock;
2685 } else if( IS_LOCK_ERROR(lrc2) ){
2686 rc = lrc2;
2687 goto afp_end_lock;
2688 } else if( lrc1 != SQLITE_OK ) {
2689 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002690 } else {
drh308c2a52010-05-14 11:30:18 +00002691 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002692 pInode->nLock++;
2693 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002694 }
drh8af6c222010-05-14 12:43:01 +00002695 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002696 /* We are trying for an exclusive lock but another thread in this
2697 ** same process is still holding a shared lock. */
2698 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002699 }else{
2700 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2701 ** assumed that there is a SHARED or greater lock on the file
2702 ** already.
2703 */
2704 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002705 assert( 0!=pFile->eFileLock );
2706 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002707 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002708 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002709 if( !failed ){
2710 context->reserved = 1;
2711 }
drhbfe66312006-10-03 17:40:40 +00002712 }
drh308c2a52010-05-14 11:30:18 +00002713 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002714 /* Acquire an EXCLUSIVE lock */
2715
2716 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002717 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002718 */
drh6b9d6dd2008-12-03 19:34:47 +00002719 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002720 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002721 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002722 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002723 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002724 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002725 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002726 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002727 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2728 ** a critical I/O error
2729 */
2730 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2731 SQLITE_IOERR_LOCK;
2732 goto afp_end_lock;
2733 }
2734 }else{
aswift5b1a2562008-08-22 00:22:35 +00002735 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002736 }
2737 }
aswift5b1a2562008-08-22 00:22:35 +00002738 if( failed ){
2739 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002740 }
2741 }
2742
2743 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002744 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002745 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002746 }else if( eFileLock==EXCLUSIVE_LOCK ){
2747 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002748 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002749 }
2750
2751afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002752 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002753 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2754 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002755 return rc;
2756}
2757
2758/*
drh308c2a52010-05-14 11:30:18 +00002759** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002760** must be either NO_LOCK or SHARED_LOCK.
2761**
2762** If the locking level of the file descriptor is already at or below
2763** the requested locking level, this routine is a no-op.
2764*/
drh308c2a52010-05-14 11:30:18 +00002765static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002766 int rc = SQLITE_OK;
2767 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002768 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002769 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2770 int skipShared = 0;
2771#ifdef SQLITE_TEST
2772 int h = pFile->h;
2773#endif
drhbfe66312006-10-03 17:40:40 +00002774
2775 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002776 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002777 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002778 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002779
drh308c2a52010-05-14 11:30:18 +00002780 assert( eFileLock<=SHARED_LOCK );
2781 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002782 return SQLITE_OK;
2783 }
drh6c7d5c52008-11-21 20:32:33 +00002784 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002785 pInode = pFile->pInode;
2786 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002787 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002788 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002789 SimulateIOErrorBenign(1);
2790 SimulateIOError( h=(-1) )
2791 SimulateIOErrorBenign(0);
2792
2793#ifndef NDEBUG
2794 /* When reducing a lock such that other processes can start
2795 ** reading the database file again, make sure that the
2796 ** transaction counter was updated if any part of the database
2797 ** file changed. If the transaction counter is not updated,
2798 ** other connections to the same file might not realize that
2799 ** the file has changed and hence might not know to flush their
2800 ** cache. The use of a stale cache can lead to database corruption.
2801 */
2802 assert( pFile->inNormalWrite==0
2803 || pFile->dbUpdate==0
2804 || pFile->transCntrChng==1 );
2805 pFile->inNormalWrite = 0;
2806#endif
aswiftaebf4132008-11-21 00:10:35 +00002807
drh308c2a52010-05-14 11:30:18 +00002808 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002809 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002810 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002811 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002812 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002813 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2814 } else {
2815 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002816 }
2817 }
drh308c2a52010-05-14 11:30:18 +00002818 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002819 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002820 }
drh308c2a52010-05-14 11:30:18 +00002821 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002822 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2823 if( !rc ){
2824 context->reserved = 0;
2825 }
aswiftaebf4132008-11-21 00:10:35 +00002826 }
drh8af6c222010-05-14 12:43:01 +00002827 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2828 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002829 }
aswiftaebf4132008-11-21 00:10:35 +00002830 }
drh308c2a52010-05-14 11:30:18 +00002831 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002832
drh7ed97b92010-01-20 13:07:21 +00002833 /* Decrement the shared lock counter. Release the lock using an
2834 ** OS call only when all threads in this same process have released
2835 ** the lock.
2836 */
drh8af6c222010-05-14 12:43:01 +00002837 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2838 pInode->nShared--;
2839 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002840 SimulateIOErrorBenign(1);
2841 SimulateIOError( h=(-1) )
2842 SimulateIOErrorBenign(0);
2843 if( !skipShared ){
2844 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2845 }
2846 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002847 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002848 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002849 }
2850 }
2851 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002852 pInode->nLock--;
2853 assert( pInode->nLock>=0 );
2854 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002855 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002856 }
2857 }
drhbfe66312006-10-03 17:40:40 +00002858 }
drh7ed97b92010-01-20 13:07:21 +00002859
drh6c7d5c52008-11-21 20:32:33 +00002860 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002861 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002862 return rc;
2863}
2864
2865/*
drh339eb0b2008-03-07 15:34:11 +00002866** Close a file & cleanup AFP specific locking context
2867*/
danielk1977e339d652008-06-28 11:23:00 +00002868static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002869 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002870 if( id ){
2871 unixFile *pFile = (unixFile*)id;
2872 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002873 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002874 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002875 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002876 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002877 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002878 ** the last lock is cleared.
2879 */
dan08da86a2009-08-21 17:18:03 +00002880 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002881 }
danb0ac3e32010-06-16 10:55:42 +00002882 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002883 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002884 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002885 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002886 }
drh7ed97b92010-01-20 13:07:21 +00002887 return rc;
drhbfe66312006-10-03 17:40:40 +00002888}
2889
drhd2cb50b2009-01-09 21:41:17 +00002890#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002891/*
2892** The code above is the AFP lock implementation. The code is specific
2893** to MacOSX and does not work on other unix platforms. No alternative
2894** is available. If you don't compile for a mac, then the "unix-afp"
2895** VFS is not available.
2896**
2897********************* End of the AFP lock implementation **********************
2898******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002899
drh7ed97b92010-01-20 13:07:21 +00002900/******************************************************************************
2901*************************** Begin NFS Locking ********************************/
2902
2903#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2904/*
drh308c2a52010-05-14 11:30:18 +00002905 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002906 ** must be either NO_LOCK or SHARED_LOCK.
2907 **
2908 ** If the locking level of the file descriptor is already at or below
2909 ** the requested locking level, this routine is a no-op.
2910 */
drh308c2a52010-05-14 11:30:18 +00002911static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002912 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002913}
2914
2915#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2916/*
2917** The code above is the NFS lock implementation. The code is specific
2918** to MacOSX and does not work on other unix platforms. No alternative
2919** is available.
2920**
2921********************* End of the NFS lock implementation **********************
2922******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002923
2924/******************************************************************************
2925**************** Non-locking sqlite3_file methods *****************************
2926**
2927** The next division contains implementations for all methods of the
2928** sqlite3_file object other than the locking methods. The locking
2929** methods were defined in divisions above (one locking method per
2930** division). Those methods that are common to all locking modes
2931** are gather together into this division.
2932*/
drhbfe66312006-10-03 17:40:40 +00002933
2934/*
drh734c9862008-11-28 15:37:20 +00002935** Seek to the offset passed as the second argument, then read cnt
2936** bytes into pBuf. Return the number of bytes actually read.
2937**
2938** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2939** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2940** one system to another. Since SQLite does not define USE_PREAD
2941** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2942** See tickets #2741 and #2681.
2943**
2944** To avoid stomping the errno value on a failed read the lastErrno value
2945** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002946*/
drh734c9862008-11-28 15:37:20 +00002947static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2948 int got;
drh7ed97b92010-01-20 13:07:21 +00002949#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002950 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002951#endif
drh734c9862008-11-28 15:37:20 +00002952 TIMER_START;
2953#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002954 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002955 SimulateIOError( got = -1 );
2956#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002957 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002958 SimulateIOError( got = -1 );
2959#else
2960 newOffset = lseek(id->h, offset, SEEK_SET);
2961 SimulateIOError( newOffset-- );
2962 if( newOffset!=offset ){
2963 if( newOffset == -1 ){
2964 ((unixFile*)id)->lastErrno = errno;
2965 }else{
2966 ((unixFile*)id)->lastErrno = 0;
2967 }
2968 return -1;
2969 }
drhe562be52011-03-02 18:01:10 +00002970 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002971#endif
2972 TIMER_END;
2973 if( got<0 ){
2974 ((unixFile*)id)->lastErrno = errno;
2975 }
drh308c2a52010-05-14 11:30:18 +00002976 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002977 return got;
drhbfe66312006-10-03 17:40:40 +00002978}
2979
2980/*
drh734c9862008-11-28 15:37:20 +00002981** Read data from a file into a buffer. Return SQLITE_OK if all
2982** bytes were read successfully and SQLITE_IOERR if anything goes
2983** wrong.
drh339eb0b2008-03-07 15:34:11 +00002984*/
drh734c9862008-11-28 15:37:20 +00002985static int unixRead(
2986 sqlite3_file *id,
2987 void *pBuf,
2988 int amt,
2989 sqlite3_int64 offset
2990){
dan08da86a2009-08-21 17:18:03 +00002991 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002992 int got;
2993 assert( id );
drh08c6d442009-02-09 17:34:07 +00002994
dan08da86a2009-08-21 17:18:03 +00002995 /* If this is a database file (not a journal, master-journal or temp
2996 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002997#if 0
dane946c392009-08-22 11:39:46 +00002998 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002999 || offset>=PENDING_BYTE+512
3000 || offset+amt<=PENDING_BYTE
3001 );
dan7c246102010-04-12 19:00:29 +00003002#endif
drh08c6d442009-02-09 17:34:07 +00003003
dan08da86a2009-08-21 17:18:03 +00003004 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003005 if( got==amt ){
3006 return SQLITE_OK;
3007 }else if( got<0 ){
3008 /* lastErrno set by seekAndRead */
3009 return SQLITE_IOERR_READ;
3010 }else{
dan08da86a2009-08-21 17:18:03 +00003011 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003012 /* Unread parts of the buffer must be zero-filled */
3013 memset(&((char*)pBuf)[got], 0, amt-got);
3014 return SQLITE_IOERR_SHORT_READ;
3015 }
3016}
3017
3018/*
3019** Seek to the offset in id->offset then read cnt bytes into pBuf.
3020** Return the number of bytes actually read. Update the offset.
3021**
3022** To avoid stomping the errno value on a failed write the lastErrno value
3023** is set before returning.
3024*/
3025static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3026 int got;
drh7ed97b92010-01-20 13:07:21 +00003027#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003028 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003029#endif
drh734c9862008-11-28 15:37:20 +00003030 TIMER_START;
3031#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003032 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003033#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003034 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003035#else
3036 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003037 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003038 if( newOffset!=offset ){
3039 if( newOffset == -1 ){
3040 ((unixFile*)id)->lastErrno = errno;
3041 }else{
3042 ((unixFile*)id)->lastErrno = 0;
3043 }
3044 return -1;
3045 }
drhe562be52011-03-02 18:01:10 +00003046 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003047#endif
3048 TIMER_END;
3049 if( got<0 ){
3050 ((unixFile*)id)->lastErrno = errno;
3051 }
3052
drh308c2a52010-05-14 11:30:18 +00003053 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003054 return got;
3055}
3056
3057
3058/*
3059** Write data from a buffer into a file. Return SQLITE_OK on success
3060** or some other error code on failure.
3061*/
3062static int unixWrite(
3063 sqlite3_file *id,
3064 const void *pBuf,
3065 int amt,
3066 sqlite3_int64 offset
3067){
dan08da86a2009-08-21 17:18:03 +00003068 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003069 int wrote = 0;
3070 assert( id );
3071 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003072
dan08da86a2009-08-21 17:18:03 +00003073 /* If this is a database file (not a journal, master-journal or temp
3074 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003075#if 0
dane946c392009-08-22 11:39:46 +00003076 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003077 || offset>=PENDING_BYTE+512
3078 || offset+amt<=PENDING_BYTE
3079 );
dan7c246102010-04-12 19:00:29 +00003080#endif
drh08c6d442009-02-09 17:34:07 +00003081
drh8f941bc2009-01-14 23:03:40 +00003082#ifndef NDEBUG
3083 /* If we are doing a normal write to a database file (as opposed to
3084 ** doing a hot-journal rollback or a write to some file other than a
3085 ** normal database file) then record the fact that the database
3086 ** has changed. If the transaction counter is modified, record that
3087 ** fact too.
3088 */
dan08da86a2009-08-21 17:18:03 +00003089 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003090 pFile->dbUpdate = 1; /* The database has been modified */
3091 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003092 int rc;
drh8f941bc2009-01-14 23:03:40 +00003093 char oldCntr[4];
3094 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003095 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003096 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003097 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003098 pFile->transCntrChng = 1; /* The transaction counter has changed */
3099 }
3100 }
3101 }
3102#endif
3103
dan08da86a2009-08-21 17:18:03 +00003104 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003105 amt -= wrote;
3106 offset += wrote;
3107 pBuf = &((char*)pBuf)[wrote];
3108 }
3109 SimulateIOError(( wrote=(-1), amt=1 ));
3110 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003111
drh734c9862008-11-28 15:37:20 +00003112 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003113 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003114 /* lastErrno set by seekAndWrite */
3115 return SQLITE_IOERR_WRITE;
3116 }else{
dan08da86a2009-08-21 17:18:03 +00003117 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003118 return SQLITE_FULL;
3119 }
3120 }
dan6e09d692010-07-27 18:34:15 +00003121
drh734c9862008-11-28 15:37:20 +00003122 return SQLITE_OK;
3123}
3124
3125#ifdef SQLITE_TEST
3126/*
3127** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003128** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003129*/
3130int sqlite3_sync_count = 0;
3131int sqlite3_fullsync_count = 0;
3132#endif
3133
3134/*
drh89240432009-03-25 01:06:01 +00003135** We do not trust systems to provide a working fdatasync(). Some do.
3136** Others do no. To be safe, we will stick with the (slower) fsync().
3137** If you know that your system does support fdatasync() correctly,
3138** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003139*/
drh89240432009-03-25 01:06:01 +00003140#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003141# define fdatasync fsync
3142#endif
3143
3144/*
3145** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3146** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3147** only available on Mac OS X. But that could change.
3148*/
3149#ifdef F_FULLFSYNC
3150# define HAVE_FULLFSYNC 1
3151#else
3152# define HAVE_FULLFSYNC 0
3153#endif
3154
3155
3156/*
3157** The fsync() system call does not work as advertised on many
3158** unix systems. The following procedure is an attempt to make
3159** it work better.
3160**
3161** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3162** for testing when we want to run through the test suite quickly.
3163** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3164** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3165** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003166**
3167** SQLite sets the dataOnly flag if the size of the file is unchanged.
3168** The idea behind dataOnly is that it should only write the file content
3169** to disk, not the inode. We only set dataOnly if the file size is
3170** unchanged since the file size is part of the inode. However,
3171** Ted Ts'o tells us that fdatasync() will also write the inode if the
3172** file size has changed. The only real difference between fdatasync()
3173** and fsync(), Ted tells us, is that fdatasync() will not flush the
3174** inode if the mtime or owner or other inode attributes have changed.
3175** We only care about the file size, not the other file attributes, so
3176** as far as SQLite is concerned, an fdatasync() is always adequate.
3177** So, we always use fdatasync() if it is available, regardless of
3178** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003179*/
3180static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003181 int rc;
drh734c9862008-11-28 15:37:20 +00003182
3183 /* The following "ifdef/elif/else/" block has the same structure as
3184 ** the one below. It is replicated here solely to avoid cluttering
3185 ** up the real code with the UNUSED_PARAMETER() macros.
3186 */
3187#ifdef SQLITE_NO_SYNC
3188 UNUSED_PARAMETER(fd);
3189 UNUSED_PARAMETER(fullSync);
3190 UNUSED_PARAMETER(dataOnly);
3191#elif HAVE_FULLFSYNC
3192 UNUSED_PARAMETER(dataOnly);
3193#else
3194 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003195 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003196#endif
3197
3198 /* Record the number of times that we do a normal fsync() and
3199 ** FULLSYNC. This is used during testing to verify that this procedure
3200 ** gets called with the correct arguments.
3201 */
3202#ifdef SQLITE_TEST
3203 if( fullSync ) sqlite3_fullsync_count++;
3204 sqlite3_sync_count++;
3205#endif
3206
3207 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3208 ** no-op
3209 */
3210#ifdef SQLITE_NO_SYNC
3211 rc = SQLITE_OK;
3212#elif HAVE_FULLFSYNC
3213 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003214 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003215 }else{
3216 rc = 1;
3217 }
3218 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003219 ** It shouldn't be possible for fullfsync to fail on the local
3220 ** file system (on OSX), so failure indicates that FULLFSYNC
3221 ** isn't supported for this file system. So, attempt an fsync
3222 ** and (for now) ignore the overhead of a superfluous fcntl call.
3223 ** It'd be better to detect fullfsync support once and avoid
3224 ** the fcntl call every time sync is called.
3225 */
drh734c9862008-11-28 15:37:20 +00003226 if( rc ) rc = fsync(fd);
3227
drh7ed97b92010-01-20 13:07:21 +00003228#elif defined(__APPLE__)
3229 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3230 ** so currently we default to the macro that redefines fdatasync to fsync
3231 */
3232 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003233#else
drh0b647ff2009-03-21 14:41:04 +00003234 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003235#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003236 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003237 rc = fsync(fd);
3238 }
drh0b647ff2009-03-21 14:41:04 +00003239#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003240#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3241
3242 if( OS_VXWORKS && rc!= -1 ){
3243 rc = 0;
3244 }
chw97185482008-11-17 08:05:31 +00003245 return rc;
drhbfe66312006-10-03 17:40:40 +00003246}
3247
drh734c9862008-11-28 15:37:20 +00003248/*
3249** Make sure all writes to a particular file are committed to disk.
3250**
3251** If dataOnly==0 then both the file itself and its metadata (file
3252** size, access time, etc) are synced. If dataOnly!=0 then only the
3253** file data is synced.
3254**
3255** Under Unix, also make sure that the directory entry for the file
3256** has been created by fsync-ing the directory that contains the file.
3257** If we do not do this and we encounter a power failure, the directory
3258** entry for the journal might not exist after we reboot. The next
3259** SQLite to access the file will not know that the journal exists (because
3260** the directory entry for the journal was never created) and the transaction
3261** will not roll back - possibly leading to database corruption.
3262*/
3263static int unixSync(sqlite3_file *id, int flags){
3264 int rc;
3265 unixFile *pFile = (unixFile*)id;
3266
3267 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3268 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3269
3270 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3271 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3272 || (flags&0x0F)==SQLITE_SYNC_FULL
3273 );
3274
3275 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3276 ** line is to test that doing so does not cause any problems.
3277 */
3278 SimulateDiskfullError( return SQLITE_FULL );
3279
3280 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003281 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003282 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3283 SimulateIOError( rc=1 );
3284 if( rc ){
3285 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003286 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003287 }
3288 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003289 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3290 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003291#ifndef SQLITE_DISABLE_DIRSYNC
3292 /* The directory sync is only attempted if full_fsync is
3293 ** turned off or unavailable. If a full_fsync occurred above,
3294 ** then the directory sync is superfluous.
3295 */
3296 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3297 /*
3298 ** We have received multiple reports of fsync() returning
3299 ** errors when applied to directories on certain file systems.
3300 ** A failed directory sync is not a big deal. So it seems
3301 ** better to ignore the error. Ticket #1657
3302 */
3303 /* pFile->lastErrno = errno; */
3304 /* return SQLITE_IOERR; */
3305 }
3306#endif
drh0e9365c2011-03-02 02:08:13 +00003307 /* Only need to sync once, so close the directory when we are done */
3308 robust_close(pFile, pFile->dirfd, __LINE__);
3309 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003310 }
3311 return rc;
3312}
3313
3314/*
3315** Truncate an open file to a specified size
3316*/
3317static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003318 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003319 int rc;
dan6e09d692010-07-27 18:34:15 +00003320 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003321 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003322
3323 /* If the user has configured a chunk-size for this file, truncate the
3324 ** file so that it consists of an integer number of chunks (i.e. the
3325 ** actual file size after the operation may be larger than the requested
3326 ** size).
3327 */
3328 if( pFile->szChunk ){
3329 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3330 }
3331
drhff812312011-02-23 13:33:46 +00003332 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003333 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003334 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003335 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003336 }else{
drh3313b142009-11-06 04:13:18 +00003337#ifndef NDEBUG
3338 /* If we are doing a normal write to a database file (as opposed to
3339 ** doing a hot-journal rollback or a write to some file other than a
3340 ** normal database file) and we truncate the file to zero length,
3341 ** that effectively updates the change counter. This might happen
3342 ** when restoring a database using the backup API from a zero-length
3343 ** source.
3344 */
dan6e09d692010-07-27 18:34:15 +00003345 if( pFile->inNormalWrite && nByte==0 ){
3346 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003347 }
3348#endif
3349
drh734c9862008-11-28 15:37:20 +00003350 return SQLITE_OK;
3351 }
3352}
3353
3354/*
3355** Determine the current size of a file in bytes
3356*/
3357static int unixFileSize(sqlite3_file *id, i64 *pSize){
3358 int rc;
3359 struct stat buf;
3360 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003361 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003362 SimulateIOError( rc=1 );
3363 if( rc!=0 ){
3364 ((unixFile*)id)->lastErrno = errno;
3365 return SQLITE_IOERR_FSTAT;
3366 }
3367 *pSize = buf.st_size;
3368
drh8af6c222010-05-14 12:43:01 +00003369 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003370 ** writes a single byte into that file in order to work around a bug
3371 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3372 ** layers, we need to report this file size as zero even though it is
3373 ** really 1. Ticket #3260.
3374 */
3375 if( *pSize==1 ) *pSize = 0;
3376
3377
3378 return SQLITE_OK;
3379}
3380
drhd2cb50b2009-01-09 21:41:17 +00003381#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003382/*
3383** Handler for proxy-locking file-control verbs. Defined below in the
3384** proxying locking division.
3385*/
3386static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003387#endif
drh715ff302008-12-03 22:32:44 +00003388
dan502019c2010-07-28 14:26:17 +00003389/*
3390** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3391** file-control operation.
3392**
3393** If the user has configured a chunk-size for this file, it could be
3394** that the file needs to be extended at this point. Otherwise, the
3395** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3396*/
3397static int fcntlSizeHint(unixFile *pFile, i64 nByte){
drh7d2dc712011-07-25 23:25:47 +00003398 { /* preserve indentation of removed "if" */
dan502019c2010-07-28 14:26:17 +00003399 i64 nSize; /* Required file size */
drh7d2dc712011-07-25 23:25:47 +00003400 i64 szChunk; /* Chunk size */
dan502019c2010-07-28 14:26:17 +00003401 struct stat buf; /* Used to hold return values of fstat() */
3402
drh99ab3b12011-03-02 15:09:07 +00003403 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003404
drh7d2dc712011-07-25 23:25:47 +00003405 szChunk = pFile->szChunk;
3406 if( szChunk==0 ){
3407 nSize = nByte;
3408 }else{
3409 nSize = ((nByte+szChunk-1) / szChunk) * szChunk;
3410 }
dan502019c2010-07-28 14:26:17 +00003411 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003412
dan502019c2010-07-28 14:26:17 +00003413#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003414 /* The code below is handling the return value of osFallocate()
3415 ** correctly. posix_fallocate() is defined to "returns zero on success,
3416 ** or an error number on failure". See the manpage for details. */
3417 int err;
drhff812312011-02-23 13:33:46 +00003418 do{
dan661d71a2011-03-30 19:08:03 +00003419 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3420 }while( err==EINTR );
3421 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003422#else
3423 /* If the OS does not have posix_fallocate(), fake it. First use
3424 ** ftruncate() to set the file size, then write a single byte to
3425 ** the last byte in each block within the extended region. This
3426 ** is the same technique used by glibc to implement posix_fallocate()
3427 ** on systems that do not have a real fallocate() system call.
3428 */
3429 int nBlk = buf.st_blksize; /* File-system block size */
3430 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003431
drhff812312011-02-23 13:33:46 +00003432 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003433 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003434 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003435 }
3436 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003437 while( iWrite<nSize ){
3438 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3439 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003440 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003441 }
dan502019c2010-07-28 14:26:17 +00003442#endif
3443 }
3444 }
3445
3446 return SQLITE_OK;
3447}
danielk1977ad94b582007-08-20 06:44:22 +00003448
danielk1977e3026632004-06-22 11:29:02 +00003449/*
drh9e33c2c2007-08-31 18:34:59 +00003450** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003451*/
drhcc6bb3e2007-08-31 16:11:35 +00003452static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003453 switch( op ){
3454 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003455 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003456 return SQLITE_OK;
3457 }
drh7708e972008-11-29 00:56:52 +00003458 case SQLITE_LAST_ERRNO: {
3459 *(int*)pArg = ((unixFile*)id)->lastErrno;
3460 return SQLITE_OK;
3461 }
dan6e09d692010-07-27 18:34:15 +00003462 case SQLITE_FCNTL_CHUNK_SIZE: {
3463 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003464 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003465 }
drh9ff27ec2010-05-19 19:26:05 +00003466 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003467 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003468 }
drh8f941bc2009-01-14 23:03:40 +00003469#ifndef NDEBUG
3470 /* The pager calls this method to signal that it has done
3471 ** a rollback and that the database is therefore unchanged and
3472 ** it hence it is OK for the transaction change counter to be
3473 ** unchanged.
3474 */
3475 case SQLITE_FCNTL_DB_UNCHANGED: {
3476 ((unixFile*)id)->dbUpdate = 0;
3477 return SQLITE_OK;
3478 }
3479#endif
drhd2cb50b2009-01-09 21:41:17 +00003480#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003481 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003482 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003483 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003484 }
drhd2cb50b2009-01-09 21:41:17 +00003485#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003486 case SQLITE_FCNTL_SYNC_OMITTED: {
3487 return SQLITE_OK; /* A no-op */
3488 }
drh9e33c2c2007-08-31 18:34:59 +00003489 }
drh0b52b7d2011-01-26 19:46:22 +00003490 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003491}
3492
3493/*
danielk1977a3d4c882007-03-23 10:08:38 +00003494** Return the sector size in bytes of the underlying block device for
3495** the specified file. This is almost always 512 bytes, but may be
3496** larger for some devices.
3497**
3498** SQLite code assumes this function cannot fail. It also assumes that
3499** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003500** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003501** same for both.
3502*/
danielk1977397d65f2008-11-19 11:35:39 +00003503static int unixSectorSize(sqlite3_file *NotUsed){
3504 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003505 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003506}
3507
danielk197790949c22007-08-17 16:50:38 +00003508/*
danielk1977397d65f2008-11-19 11:35:39 +00003509** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003510*/
danielk1977397d65f2008-11-19 11:35:39 +00003511static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3512 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003513 return 0;
3514}
3515
drhd9e5c4f2010-05-12 18:01:39 +00003516#ifndef SQLITE_OMIT_WAL
3517
3518
3519/*
drhd91c68f2010-05-14 14:52:25 +00003520** Object used to represent an shared memory buffer.
3521**
3522** When multiple threads all reference the same wal-index, each thread
3523** has its own unixShm object, but they all point to a single instance
3524** of this unixShmNode object. In other words, each wal-index is opened
3525** only once per process.
3526**
3527** Each unixShmNode object is connected to a single unixInodeInfo object.
3528** We could coalesce this object into unixInodeInfo, but that would mean
3529** every open file that does not use shared memory (in other words, most
3530** open files) would have to carry around this extra information. So
3531** the unixInodeInfo object contains a pointer to this unixShmNode object
3532** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003533**
3534** unixMutexHeld() must be true when creating or destroying
3535** this object or while reading or writing the following fields:
3536**
3537** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003538**
3539** The following fields are read-only after the object is created:
3540**
3541** fid
3542** zFilename
3543**
drhd91c68f2010-05-14 14:52:25 +00003544** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003545** unixMutexHeld() is true when reading or writing any other field
3546** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003547*/
drhd91c68f2010-05-14 14:52:25 +00003548struct unixShmNode {
3549 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003550 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003551 char *zFilename; /* Name of the mmapped file */
3552 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003553 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003554 u16 nRegion; /* Size of array apRegion */
3555 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003556 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003557 int nRef; /* Number of unixShm objects pointing to this */
3558 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003559#ifdef SQLITE_DEBUG
3560 u8 exclMask; /* Mask of exclusive locks held */
3561 u8 sharedMask; /* Mask of shared locks held */
3562 u8 nextShmId; /* Next available unixShm.id value */
3563#endif
3564};
3565
3566/*
drhd9e5c4f2010-05-12 18:01:39 +00003567** Structure used internally by this VFS to record the state of an
3568** open shared memory connection.
3569**
drhd91c68f2010-05-14 14:52:25 +00003570** The following fields are initialized when this object is created and
3571** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003572**
drhd91c68f2010-05-14 14:52:25 +00003573** unixShm.pFile
3574** unixShm.id
3575**
3576** All other fields are read/write. The unixShm.pFile->mutex must be held
3577** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003578*/
3579struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003580 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3581 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003582 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003583 u16 sharedMask; /* Mask of shared locks held */
3584 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003585#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003586 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003587#endif
3588};
3589
3590/*
drhd9e5c4f2010-05-12 18:01:39 +00003591** Constants used for locking
3592*/
drhbd9676c2010-06-23 17:58:38 +00003593#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003594#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003595
drhd9e5c4f2010-05-12 18:01:39 +00003596/*
drh73b64e42010-05-30 19:55:15 +00003597** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003598**
3599** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3600** otherwise.
3601*/
3602static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003603 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3604 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003605 int ofst, /* First byte of the locking range */
3606 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003607){
3608 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003609 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003610
drhd91c68f2010-05-14 14:52:25 +00003611 /* Access to the unixShmNode object is serialized by the caller */
3612 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003613
drh73b64e42010-05-30 19:55:15 +00003614 /* Shared locks never span more than one byte */
3615 assert( n==1 || lockType!=F_RDLCK );
3616
3617 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003618 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003619
drh3cb93392011-03-12 18:10:44 +00003620 if( pShmNode->h>=0 ){
3621 /* Initialize the locking parameters */
3622 memset(&f, 0, sizeof(f));
3623 f.l_type = lockType;
3624 f.l_whence = SEEK_SET;
3625 f.l_start = ofst;
3626 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003627
drh3cb93392011-03-12 18:10:44 +00003628 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3629 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3630 }
drhd9e5c4f2010-05-12 18:01:39 +00003631
3632 /* Update the global lock state and do debug tracing */
3633#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003634 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003635 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003636 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003637 if( rc==SQLITE_OK ){
3638 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003639 OSTRACE(("unlock %d ok", ofst));
3640 pShmNode->exclMask &= ~mask;
3641 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003642 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003643 OSTRACE(("read-lock %d ok", ofst));
3644 pShmNode->exclMask &= ~mask;
3645 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003646 }else{
3647 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003648 OSTRACE(("write-lock %d ok", ofst));
3649 pShmNode->exclMask |= mask;
3650 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003651 }
3652 }else{
3653 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003654 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003655 }else if( lockType==F_RDLCK ){
3656 OSTRACE(("read-lock failed"));
3657 }else{
3658 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003659 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003660 }
3661 }
drh20e1f082010-05-31 16:10:12 +00003662 OSTRACE((" - afterwards %03x,%03x\n",
3663 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003664 }
drhd9e5c4f2010-05-12 18:01:39 +00003665#endif
3666
3667 return rc;
3668}
3669
drhd9e5c4f2010-05-12 18:01:39 +00003670
3671/*
drhd91c68f2010-05-14 14:52:25 +00003672** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003673**
3674** This is not a VFS shared-memory method; it is a utility function called
3675** by VFS shared-memory methods.
3676*/
drhd91c68f2010-05-14 14:52:25 +00003677static void unixShmPurge(unixFile *pFd){
3678 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003679 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003680 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003681 int i;
drhd91c68f2010-05-14 14:52:25 +00003682 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003683 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003684 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003685 if( p->h>=0 ){
3686 munmap(p->apRegion[i], p->szRegion);
3687 }else{
3688 sqlite3_free(p->apRegion[i]);
3689 }
dan13a3cb82010-06-11 19:04:21 +00003690 }
dan18801912010-06-14 14:07:50 +00003691 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003692 if( p->h>=0 ){
3693 robust_close(pFd, p->h, __LINE__);
3694 p->h = -1;
3695 }
drhd91c68f2010-05-14 14:52:25 +00003696 p->pInode->pShmNode = 0;
3697 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003698 }
3699}
3700
3701/*
danda9fe0c2010-07-13 18:44:03 +00003702** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003703** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003704**
drh7234c6d2010-06-19 15:10:09 +00003705** The file used to implement shared-memory is in the same directory
3706** as the open database file and has the same name as the open database
3707** file with the "-shm" suffix added. For example, if the database file
3708** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003709** for shared memory will be called "/home/user1/config.db-shm".
3710**
3711** Another approach to is to use files in /dev/shm or /dev/tmp or an
3712** some other tmpfs mount. But if a file in a different directory
3713** from the database file is used, then differing access permissions
3714** or a chroot() might cause two different processes on the same
3715** database to end up using different files for shared memory -
3716** meaning that their memory would not really be shared - resulting
3717** in database corruption. Nevertheless, this tmpfs file usage
3718** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3719** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3720** option results in an incompatible build of SQLite; builds of SQLite
3721** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3722** same database file at the same time, database corruption will likely
3723** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3724** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003725**
3726** When opening a new shared-memory file, if no other instances of that
3727** file are currently open, in this process or in other processes, then
3728** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003729**
3730** If the original database file (pDbFd) is using the "unix-excl" VFS
3731** that means that an exclusive lock is held on the database file and
3732** that no other processes are able to read or write the database. In
3733** that case, we do not really need shared memory. No shared memory
3734** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003735*/
danda9fe0c2010-07-13 18:44:03 +00003736static int unixOpenSharedMemory(unixFile *pDbFd){
3737 struct unixShm *p = 0; /* The connection to be opened */
3738 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3739 int rc; /* Result code */
3740 unixInodeInfo *pInode; /* The inode of fd */
3741 char *zShmFilename; /* Name of the file used for SHM */
3742 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003743
danda9fe0c2010-07-13 18:44:03 +00003744 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003745 p = sqlite3_malloc( sizeof(*p) );
3746 if( p==0 ) return SQLITE_NOMEM;
3747 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003748 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003749
danda9fe0c2010-07-13 18:44:03 +00003750 /* Check to see if a unixShmNode object already exists. Reuse an existing
3751 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003752 */
3753 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003754 pInode = pDbFd->pInode;
3755 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003756 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003757 struct stat sStat; /* fstat() info for database file */
3758
3759 /* Call fstat() to figure out the permissions on the database file. If
3760 ** a new *-shm file is created, an attempt will be made to create it
3761 ** with the same permissions. The actual permissions the file is created
3762 ** with are subject to the current umask setting.
3763 */
drh3cb93392011-03-12 18:10:44 +00003764 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003765 rc = SQLITE_IOERR_FSTAT;
3766 goto shm_open_err;
3767 }
3768
drha4ced192010-07-15 18:32:40 +00003769#ifdef SQLITE_SHM_DIRECTORY
3770 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3771#else
drh7234c6d2010-06-19 15:10:09 +00003772 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003773#endif
drh7234c6d2010-06-19 15:10:09 +00003774 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003775 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003776 rc = SQLITE_NOMEM;
3777 goto shm_open_err;
3778 }
drhd91c68f2010-05-14 14:52:25 +00003779 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003780 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003781#ifdef SQLITE_SHM_DIRECTORY
3782 sqlite3_snprintf(nShmFilename, zShmFilename,
3783 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3784 (u32)sStat.st_ino, (u32)sStat.st_dev);
3785#else
drh7234c6d2010-06-19 15:10:09 +00003786 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003787 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003788#endif
drhd91c68f2010-05-14 14:52:25 +00003789 pShmNode->h = -1;
3790 pDbFd->pInode->pShmNode = pShmNode;
3791 pShmNode->pInode = pDbFd->pInode;
3792 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3793 if( pShmNode->mutex==0 ){
3794 rc = SQLITE_NOMEM;
3795 goto shm_open_err;
3796 }
drhd9e5c4f2010-05-12 18:01:39 +00003797
drh3cb93392011-03-12 18:10:44 +00003798 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003799 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3800 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003801 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003802 const char *zRO;
3803 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003804 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003805 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3806 (sStat.st_mode & 0777));
3807 pShmNode->isReadonly = 1;
3808 }
3809 if( pShmNode->h<0 ){
3810 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3811 goto shm_open_err;
3812 }
drhd9e5c4f2010-05-12 18:01:39 +00003813 }
drh3cb93392011-03-12 18:10:44 +00003814
3815 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003816 ** If not, truncate the file to zero length.
3817 */
3818 rc = SQLITE_OK;
3819 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3820 if( robust_ftruncate(pShmNode->h, 0) ){
3821 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003822 }
3823 }
drh66dfec8b2011-06-01 20:01:49 +00003824 if( rc==SQLITE_OK ){
3825 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3826 }
3827 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003828 }
drhd9e5c4f2010-05-12 18:01:39 +00003829 }
3830
drhd91c68f2010-05-14 14:52:25 +00003831 /* Make the new connection a child of the unixShmNode */
3832 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003833#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003834 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003835#endif
drhd91c68f2010-05-14 14:52:25 +00003836 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003837 pDbFd->pShm = p;
3838 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003839
3840 /* The reference count on pShmNode has already been incremented under
3841 ** the cover of the unixEnterMutex() mutex and the pointer from the
3842 ** new (struct unixShm) object to the pShmNode has been set. All that is
3843 ** left to do is to link the new object into the linked list starting
3844 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3845 ** mutex.
3846 */
3847 sqlite3_mutex_enter(pShmNode->mutex);
3848 p->pNext = pShmNode->pFirst;
3849 pShmNode->pFirst = p;
3850 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003851 return SQLITE_OK;
3852
3853 /* Jump here on any error */
3854shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003855 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003856 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003857 unixLeaveMutex();
3858 return rc;
3859}
3860
3861/*
danda9fe0c2010-07-13 18:44:03 +00003862** This function is called to obtain a pointer to region iRegion of the
3863** shared-memory associated with the database file fd. Shared-memory regions
3864** are numbered starting from zero. Each shared-memory region is szRegion
3865** bytes in size.
3866**
3867** If an error occurs, an error code is returned and *pp is set to NULL.
3868**
3869** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3870** region has not been allocated (by any client, including one running in a
3871** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3872** bExtend is non-zero and the requested shared-memory region has not yet
3873** been allocated, it is allocated by this function.
3874**
3875** If the shared-memory region has already been allocated or is allocated by
3876** this call as described above, then it is mapped into this processes
3877** address space (if it is not already), *pp is set to point to the mapped
3878** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003879*/
danda9fe0c2010-07-13 18:44:03 +00003880static int unixShmMap(
3881 sqlite3_file *fd, /* Handle open on database file */
3882 int iRegion, /* Region to retrieve */
3883 int szRegion, /* Size of regions */
3884 int bExtend, /* True to extend file if necessary */
3885 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003886){
danda9fe0c2010-07-13 18:44:03 +00003887 unixFile *pDbFd = (unixFile*)fd;
3888 unixShm *p;
3889 unixShmNode *pShmNode;
3890 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003891
danda9fe0c2010-07-13 18:44:03 +00003892 /* If the shared-memory file has not yet been opened, open it now. */
3893 if( pDbFd->pShm==0 ){
3894 rc = unixOpenSharedMemory(pDbFd);
3895 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003896 }
drhd9e5c4f2010-05-12 18:01:39 +00003897
danda9fe0c2010-07-13 18:44:03 +00003898 p = pDbFd->pShm;
3899 pShmNode = p->pShmNode;
3900 sqlite3_mutex_enter(pShmNode->mutex);
3901 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003902 assert( pShmNode->pInode==pDbFd->pInode );
3903 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3904 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003905
3906 if( pShmNode->nRegion<=iRegion ){
3907 char **apNew; /* New apRegion[] array */
3908 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3909 struct stat sStat; /* Used by fstat() */
3910
3911 pShmNode->szRegion = szRegion;
3912
drh3cb93392011-03-12 18:10:44 +00003913 if( pShmNode->h>=0 ){
3914 /* The requested region is not mapped into this processes address space.
3915 ** Check to see if it has been allocated (i.e. if the wal-index file is
3916 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003917 */
drh3cb93392011-03-12 18:10:44 +00003918 if( osFstat(pShmNode->h, &sStat) ){
3919 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003920 goto shmpage_out;
3921 }
drh3cb93392011-03-12 18:10:44 +00003922
3923 if( sStat.st_size<nByte ){
3924 /* The requested memory region does not exist. If bExtend is set to
3925 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3926 **
3927 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3928 ** the requested memory region.
3929 */
3930 if( !bExtend ) goto shmpage_out;
3931 if( robust_ftruncate(pShmNode->h, nByte) ){
3932 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3933 pShmNode->zFilename);
3934 goto shmpage_out;
3935 }
3936 }
danda9fe0c2010-07-13 18:44:03 +00003937 }
3938
3939 /* Map the requested memory region into this processes address space. */
3940 apNew = (char **)sqlite3_realloc(
3941 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3942 );
3943 if( !apNew ){
3944 rc = SQLITE_IOERR_NOMEM;
3945 goto shmpage_out;
3946 }
3947 pShmNode->apRegion = apNew;
3948 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003949 void *pMem;
3950 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00003951 pMem = mmap(0, szRegion,
3952 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00003953 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3954 );
3955 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00003956 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00003957 goto shmpage_out;
3958 }
3959 }else{
3960 pMem = sqlite3_malloc(szRegion);
3961 if( pMem==0 ){
3962 rc = SQLITE_NOMEM;
3963 goto shmpage_out;
3964 }
3965 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003966 }
3967 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3968 pShmNode->nRegion++;
3969 }
3970 }
3971
3972shmpage_out:
3973 if( pShmNode->nRegion>iRegion ){
3974 *pp = pShmNode->apRegion[iRegion];
3975 }else{
3976 *pp = 0;
3977 }
drh66dfec8b2011-06-01 20:01:49 +00003978 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00003979 sqlite3_mutex_leave(pShmNode->mutex);
3980 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003981}
3982
3983/*
drhd9e5c4f2010-05-12 18:01:39 +00003984** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003985**
3986** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3987** different here than in posix. In xShmLock(), one can go from unlocked
3988** to shared and back or from unlocked to exclusive and back. But one may
3989** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003990*/
3991static int unixShmLock(
3992 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003993 int ofst, /* First lock to acquire or release */
3994 int n, /* Number of locks to acquire or release */
3995 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003996){
drh73b64e42010-05-30 19:55:15 +00003997 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3998 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3999 unixShm *pX; /* For looping over all siblings */
4000 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4001 int rc = SQLITE_OK; /* Result code */
4002 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004003
drhd91c68f2010-05-14 14:52:25 +00004004 assert( pShmNode==pDbFd->pInode->pShmNode );
4005 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004006 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004007 assert( n>=1 );
4008 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4009 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4010 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4011 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4012 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004013 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4014 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004015
drhc99597c2010-05-31 01:41:15 +00004016 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004017 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004018 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004019 if( flags & SQLITE_SHM_UNLOCK ){
4020 u16 allMask = 0; /* Mask of locks held by siblings */
4021
4022 /* See if any siblings hold this same lock */
4023 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4024 if( pX==p ) continue;
4025 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4026 allMask |= pX->sharedMask;
4027 }
4028
4029 /* Unlock the system-level locks */
4030 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004031 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004032 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004033 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004034 }
drh73b64e42010-05-30 19:55:15 +00004035
4036 /* Undo the local locks */
4037 if( rc==SQLITE_OK ){
4038 p->exclMask &= ~mask;
4039 p->sharedMask &= ~mask;
4040 }
4041 }else if( flags & SQLITE_SHM_SHARED ){
4042 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4043
4044 /* Find out which shared locks are already held by sibling connections.
4045 ** If any sibling already holds an exclusive lock, go ahead and return
4046 ** SQLITE_BUSY.
4047 */
4048 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004049 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004050 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004051 break;
4052 }
4053 allShared |= pX->sharedMask;
4054 }
4055
4056 /* Get shared locks at the system level, if necessary */
4057 if( rc==SQLITE_OK ){
4058 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004059 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004060 }else{
drh73b64e42010-05-30 19:55:15 +00004061 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004062 }
drhd9e5c4f2010-05-12 18:01:39 +00004063 }
drh73b64e42010-05-30 19:55:15 +00004064
4065 /* Get the local shared locks */
4066 if( rc==SQLITE_OK ){
4067 p->sharedMask |= mask;
4068 }
4069 }else{
4070 /* Make sure no sibling connections hold locks that will block this
4071 ** lock. If any do, return SQLITE_BUSY right away.
4072 */
4073 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004074 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4075 rc = SQLITE_BUSY;
4076 break;
4077 }
4078 }
4079
4080 /* Get the exclusive locks at the system level. Then if successful
4081 ** also mark the local connection as being locked.
4082 */
4083 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004084 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004085 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004086 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004087 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004088 }
drhd9e5c4f2010-05-12 18:01:39 +00004089 }
4090 }
drhd91c68f2010-05-14 14:52:25 +00004091 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004092 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4093 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004094 return rc;
4095}
4096
drh286a2882010-05-20 23:51:06 +00004097/*
4098** Implement a memory barrier or memory fence on shared memory.
4099**
4100** All loads and stores begun before the barrier must complete before
4101** any load or store begun after the barrier.
4102*/
4103static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004104 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004105){
drhff828942010-06-26 21:34:06 +00004106 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004107 unixEnterMutex();
4108 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004109}
4110
dan18801912010-06-14 14:07:50 +00004111/*
danda9fe0c2010-07-13 18:44:03 +00004112** Close a connection to shared-memory. Delete the underlying
4113** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004114**
4115** If there is no shared memory associated with the connection then this
4116** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004117*/
danda9fe0c2010-07-13 18:44:03 +00004118static int unixShmUnmap(
4119 sqlite3_file *fd, /* The underlying database file */
4120 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004121){
danda9fe0c2010-07-13 18:44:03 +00004122 unixShm *p; /* The connection to be closed */
4123 unixShmNode *pShmNode; /* The underlying shared-memory file */
4124 unixShm **pp; /* For looping over sibling connections */
4125 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004126
danda9fe0c2010-07-13 18:44:03 +00004127 pDbFd = (unixFile*)fd;
4128 p = pDbFd->pShm;
4129 if( p==0 ) return SQLITE_OK;
4130 pShmNode = p->pShmNode;
4131
4132 assert( pShmNode==pDbFd->pInode->pShmNode );
4133 assert( pShmNode->pInode==pDbFd->pInode );
4134
4135 /* Remove connection p from the set of connections associated
4136 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004137 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004138 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4139 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004140
danda9fe0c2010-07-13 18:44:03 +00004141 /* Free the connection p */
4142 sqlite3_free(p);
4143 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004144 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004145
4146 /* If pShmNode->nRef has reached 0, then close the underlying
4147 ** shared-memory file, too */
4148 unixEnterMutex();
4149 assert( pShmNode->nRef>0 );
4150 pShmNode->nRef--;
4151 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004152 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004153 unixShmPurge(pDbFd);
4154 }
4155 unixLeaveMutex();
4156
4157 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004158}
drh286a2882010-05-20 23:51:06 +00004159
danda9fe0c2010-07-13 18:44:03 +00004160
drhd9e5c4f2010-05-12 18:01:39 +00004161#else
drh6b017cc2010-06-14 18:01:46 +00004162# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004163# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004164# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004165# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004166#endif /* #ifndef SQLITE_OMIT_WAL */
4167
drh734c9862008-11-28 15:37:20 +00004168/*
4169** Here ends the implementation of all sqlite3_file methods.
4170**
4171********************** End sqlite3_file Methods *******************************
4172******************************************************************************/
4173
4174/*
drh6b9d6dd2008-12-03 19:34:47 +00004175** This division contains definitions of sqlite3_io_methods objects that
4176** implement various file locking strategies. It also contains definitions
4177** of "finder" functions. A finder-function is used to locate the appropriate
4178** sqlite3_io_methods object for a particular database file. The pAppData
4179** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4180** the correct finder-function for that VFS.
4181**
4182** Most finder functions return a pointer to a fixed sqlite3_io_methods
4183** object. The only interesting finder-function is autolockIoFinder, which
4184** looks at the filesystem type and tries to guess the best locking
4185** strategy from that.
4186**
drh1875f7a2008-12-08 18:19:17 +00004187** For finder-funtion F, two objects are created:
4188**
4189** (1) The real finder-function named "FImpt()".
4190**
dane946c392009-08-22 11:39:46 +00004191** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004192**
4193**
4194** A pointer to the F pointer is used as the pAppData value for VFS
4195** objects. We have to do this instead of letting pAppData point
4196** directly at the finder-function since C90 rules prevent a void*
4197** from be cast into a function pointer.
4198**
drh6b9d6dd2008-12-03 19:34:47 +00004199**
drh7708e972008-11-29 00:56:52 +00004200** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004201**
drh7708e972008-11-29 00:56:52 +00004202** * A constant sqlite3_io_methods object call METHOD that has locking
4203** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4204**
4205** * An I/O method finder function called FINDER that returns a pointer
4206** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004207*/
drhd9e5c4f2010-05-12 18:01:39 +00004208#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004209static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004210 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004211 CLOSE, /* xClose */ \
4212 unixRead, /* xRead */ \
4213 unixWrite, /* xWrite */ \
4214 unixTruncate, /* xTruncate */ \
4215 unixSync, /* xSync */ \
4216 unixFileSize, /* xFileSize */ \
4217 LOCK, /* xLock */ \
4218 UNLOCK, /* xUnlock */ \
4219 CKLOCK, /* xCheckReservedLock */ \
4220 unixFileControl, /* xFileControl */ \
4221 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004222 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004223 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004224 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004225 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004226 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004227}; \
drh0c2694b2009-09-03 16:23:44 +00004228static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4229 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004230 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004231} \
drh0c2694b2009-09-03 16:23:44 +00004232static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004233 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004234
4235/*
4236** Here are all of the sqlite3_io_methods objects for each of the
4237** locking strategies. Functions that return pointers to these methods
4238** are also created.
4239*/
4240IOMETHODS(
4241 posixIoFinder, /* Finder function name */
4242 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004243 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004244 unixClose, /* xClose method */
4245 unixLock, /* xLock method */
4246 unixUnlock, /* xUnlock method */
4247 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004248)
drh7708e972008-11-29 00:56:52 +00004249IOMETHODS(
4250 nolockIoFinder, /* Finder function name */
4251 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004252 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004253 nolockClose, /* xClose method */
4254 nolockLock, /* xLock method */
4255 nolockUnlock, /* xUnlock method */
4256 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004257)
drh7708e972008-11-29 00:56:52 +00004258IOMETHODS(
4259 dotlockIoFinder, /* Finder function name */
4260 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004261 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004262 dotlockClose, /* xClose method */
4263 dotlockLock, /* xLock method */
4264 dotlockUnlock, /* xUnlock method */
4265 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004266)
drh7708e972008-11-29 00:56:52 +00004267
chw78a13182009-04-07 05:35:03 +00004268#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004269IOMETHODS(
4270 flockIoFinder, /* Finder function name */
4271 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004272 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004273 flockClose, /* xClose method */
4274 flockLock, /* xLock method */
4275 flockUnlock, /* xUnlock method */
4276 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004277)
drh7708e972008-11-29 00:56:52 +00004278#endif
4279
drh6c7d5c52008-11-21 20:32:33 +00004280#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004281IOMETHODS(
4282 semIoFinder, /* Finder function name */
4283 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004284 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004285 semClose, /* xClose method */
4286 semLock, /* xLock method */
4287 semUnlock, /* xUnlock method */
4288 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004289)
aswiftaebf4132008-11-21 00:10:35 +00004290#endif
drh7708e972008-11-29 00:56:52 +00004291
drhd2cb50b2009-01-09 21:41:17 +00004292#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004293IOMETHODS(
4294 afpIoFinder, /* Finder function name */
4295 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004296 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004297 afpClose, /* xClose method */
4298 afpLock, /* xLock method */
4299 afpUnlock, /* xUnlock method */
4300 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004301)
drh715ff302008-12-03 22:32:44 +00004302#endif
4303
4304/*
4305** The proxy locking method is a "super-method" in the sense that it
4306** opens secondary file descriptors for the conch and lock files and
4307** it uses proxy, dot-file, AFP, and flock() locking methods on those
4308** secondary files. For this reason, the division that implements
4309** proxy locking is located much further down in the file. But we need
4310** to go ahead and define the sqlite3_io_methods and finder function
4311** for proxy locking here. So we forward declare the I/O methods.
4312*/
drhd2cb50b2009-01-09 21:41:17 +00004313#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004314static int proxyClose(sqlite3_file*);
4315static int proxyLock(sqlite3_file*, int);
4316static int proxyUnlock(sqlite3_file*, int);
4317static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004318IOMETHODS(
4319 proxyIoFinder, /* Finder function name */
4320 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004321 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004322 proxyClose, /* xClose method */
4323 proxyLock, /* xLock method */
4324 proxyUnlock, /* xUnlock method */
4325 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004326)
aswiftaebf4132008-11-21 00:10:35 +00004327#endif
drh7708e972008-11-29 00:56:52 +00004328
drh7ed97b92010-01-20 13:07:21 +00004329/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4330#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4331IOMETHODS(
4332 nfsIoFinder, /* Finder function name */
4333 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004334 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004335 unixClose, /* xClose method */
4336 unixLock, /* xLock method */
4337 nfsUnlock, /* xUnlock method */
4338 unixCheckReservedLock /* xCheckReservedLock method */
4339)
4340#endif
drh7708e972008-11-29 00:56:52 +00004341
drhd2cb50b2009-01-09 21:41:17 +00004342#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004343/*
drh6b9d6dd2008-12-03 19:34:47 +00004344** This "finder" function attempts to determine the best locking strategy
4345** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004346** object that implements that strategy.
4347**
4348** This is for MacOSX only.
4349*/
drh1875f7a2008-12-08 18:19:17 +00004350static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004351 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004352 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004353){
4354 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004355 const char *zFilesystem; /* Filesystem type name */
4356 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004357 } aMap[] = {
4358 { "hfs", &posixIoMethods },
4359 { "ufs", &posixIoMethods },
4360 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004361 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004362 { "webdav", &nolockIoMethods },
4363 { 0, 0 }
4364 };
4365 int i;
4366 struct statfs fsInfo;
4367 struct flock lockInfo;
4368
4369 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004370 /* If filePath==NULL that means we are dealing with a transient file
4371 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004372 return &nolockIoMethods;
4373 }
4374 if( statfs(filePath, &fsInfo) != -1 ){
4375 if( fsInfo.f_flags & MNT_RDONLY ){
4376 return &nolockIoMethods;
4377 }
4378 for(i=0; aMap[i].zFilesystem; i++){
4379 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4380 return aMap[i].pMethods;
4381 }
4382 }
4383 }
4384
4385 /* Default case. Handles, amongst others, "nfs".
4386 ** Test byte-range lock using fcntl(). If the call succeeds,
4387 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004388 */
drh7708e972008-11-29 00:56:52 +00004389 lockInfo.l_len = 1;
4390 lockInfo.l_start = 0;
4391 lockInfo.l_whence = SEEK_SET;
4392 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004393 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004394 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4395 return &nfsIoMethods;
4396 } else {
4397 return &posixIoMethods;
4398 }
drh7708e972008-11-29 00:56:52 +00004399 }else{
4400 return &dotlockIoMethods;
4401 }
4402}
drh0c2694b2009-09-03 16:23:44 +00004403static const sqlite3_io_methods
4404 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004405
drhd2cb50b2009-01-09 21:41:17 +00004406#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004407
chw78a13182009-04-07 05:35:03 +00004408#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4409/*
4410** This "finder" function attempts to determine the best locking strategy
4411** for the database file "filePath". It then returns the sqlite3_io_methods
4412** object that implements that strategy.
4413**
4414** This is for VXWorks only.
4415*/
4416static const sqlite3_io_methods *autolockIoFinderImpl(
4417 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004418 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004419){
4420 struct flock lockInfo;
4421
4422 if( !filePath ){
4423 /* If filePath==NULL that means we are dealing with a transient file
4424 ** that does not need to be locked. */
4425 return &nolockIoMethods;
4426 }
4427
4428 /* Test if fcntl() is supported and use POSIX style locks.
4429 ** Otherwise fall back to the named semaphore method.
4430 */
4431 lockInfo.l_len = 1;
4432 lockInfo.l_start = 0;
4433 lockInfo.l_whence = SEEK_SET;
4434 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004435 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004436 return &posixIoMethods;
4437 }else{
4438 return &semIoMethods;
4439 }
4440}
drh0c2694b2009-09-03 16:23:44 +00004441static const sqlite3_io_methods
4442 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004443
4444#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4445
drh7708e972008-11-29 00:56:52 +00004446/*
4447** An abstract type for a pointer to a IO method finder function:
4448*/
drh0c2694b2009-09-03 16:23:44 +00004449typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004450
aswiftaebf4132008-11-21 00:10:35 +00004451
drh734c9862008-11-28 15:37:20 +00004452/****************************************************************************
4453**************************** sqlite3_vfs methods ****************************
4454**
4455** This division contains the implementation of methods on the
4456** sqlite3_vfs object.
4457*/
4458
danielk1977a3d4c882007-03-23 10:08:38 +00004459/*
danielk1977e339d652008-06-28 11:23:00 +00004460** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004461*/
4462static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004463 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004464 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004465 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004466 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004467 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004468 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004469 int isDelete, /* Delete on close if true */
4470 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004471){
drh7708e972008-11-29 00:56:52 +00004472 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004473 unixFile *pNew = (unixFile *)pId;
4474 int rc = SQLITE_OK;
4475
drh8af6c222010-05-14 12:43:01 +00004476 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004477
dane946c392009-08-22 11:39:46 +00004478 /* Parameter isDelete is only used on vxworks. Express this explicitly
4479 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004480 */
drh7708e972008-11-29 00:56:52 +00004481 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004482
dan00157392010-10-05 11:33:15 +00004483 /* Usually the path zFilename should not be a relative pathname. The
4484 ** exception is when opening the proxy "conch" file in builds that
4485 ** include the special Apple locking styles.
4486 */
dan00157392010-10-05 11:33:15 +00004487#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004488 assert( zFilename==0 || zFilename[0]=='/'
4489 || pVfs->pAppData==(void*)&autolockIoFinder );
4490#else
4491 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004492#endif
dan00157392010-10-05 11:33:15 +00004493
drh308c2a52010-05-14 11:30:18 +00004494 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004495 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004496 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004497 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004498 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4499 pNew->ctrlFlags = UNIXFILE_EXCL;
4500 }else{
4501 pNew->ctrlFlags = 0;
4502 }
drh77197112011-03-15 19:08:48 +00004503 if( isReadOnly ){
4504 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4505 }
drh339eb0b2008-03-07 15:34:11 +00004506
drh6c7d5c52008-11-21 20:32:33 +00004507#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004508 pNew->pId = vxworksFindFileId(zFilename);
4509 if( pNew->pId==0 ){
4510 noLock = 1;
4511 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004512 }
4513#endif
4514
drhda0e7682008-07-30 15:27:54 +00004515 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004516 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004517 }else{
drh0c2694b2009-09-03 16:23:44 +00004518 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004519#if SQLITE_ENABLE_LOCKING_STYLE
4520 /* Cache zFilename in the locking context (AFP and dotlock override) for
4521 ** proxyLock activation is possible (remote proxy is based on db name)
4522 ** zFilename remains valid until file is closed, to support */
4523 pNew->lockingContext = (void*)zFilename;
4524#endif
drhda0e7682008-07-30 15:27:54 +00004525 }
danielk1977e339d652008-06-28 11:23:00 +00004526
drh7ed97b92010-01-20 13:07:21 +00004527 if( pLockingStyle == &posixIoMethods
4528#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4529 || pLockingStyle == &nfsIoMethods
4530#endif
4531 ){
drh7708e972008-11-29 00:56:52 +00004532 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004533 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004534 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004535 /* If an error occured in findInodeInfo(), close the file descriptor
4536 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004537 ** in two scenarios:
4538 **
4539 ** (a) A call to fstat() failed.
4540 ** (b) A malloc failed.
4541 **
4542 ** Scenario (b) may only occur if the process is holding no other
4543 ** file descriptors open on the same file. If there were other file
4544 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004545 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004546 ** handle h - as it is guaranteed that no posix locks will be released
4547 ** by doing so.
4548 **
4549 ** If scenario (a) caused the error then things are not so safe. The
4550 ** implicit assumption here is that if fstat() fails, things are in
4551 ** such bad shape that dropping a lock or two doesn't matter much.
4552 */
drh0e9365c2011-03-02 02:08:13 +00004553 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004554 h = -1;
4555 }
drh7708e972008-11-29 00:56:52 +00004556 unixLeaveMutex();
4557 }
danielk1977e339d652008-06-28 11:23:00 +00004558
drhd2cb50b2009-01-09 21:41:17 +00004559#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004560 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004561 /* AFP locking uses the file path so it needs to be included in
4562 ** the afpLockingContext.
4563 */
4564 afpLockingContext *pCtx;
4565 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4566 if( pCtx==0 ){
4567 rc = SQLITE_NOMEM;
4568 }else{
4569 /* NB: zFilename exists and remains valid until the file is closed
4570 ** according to requirement F11141. So we do not need to make a
4571 ** copy of the filename. */
4572 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004573 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004574 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004575 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004576 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004577 if( rc!=SQLITE_OK ){
4578 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004579 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004580 h = -1;
4581 }
drh7708e972008-11-29 00:56:52 +00004582 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004583 }
drh7708e972008-11-29 00:56:52 +00004584 }
4585#endif
danielk1977e339d652008-06-28 11:23:00 +00004586
drh7708e972008-11-29 00:56:52 +00004587 else if( pLockingStyle == &dotlockIoMethods ){
4588 /* Dotfile locking uses the file path so it needs to be included in
4589 ** the dotlockLockingContext
4590 */
4591 char *zLockFile;
4592 int nFilename;
drhea678832008-12-10 19:26:22 +00004593 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004594 zLockFile = (char *)sqlite3_malloc(nFilename);
4595 if( zLockFile==0 ){
4596 rc = SQLITE_NOMEM;
4597 }else{
4598 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004599 }
drh7708e972008-11-29 00:56:52 +00004600 pNew->lockingContext = zLockFile;
4601 }
danielk1977e339d652008-06-28 11:23:00 +00004602
drh6c7d5c52008-11-21 20:32:33 +00004603#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004604 else if( pLockingStyle == &semIoMethods ){
4605 /* Named semaphore locking uses the file path so it needs to be
4606 ** included in the semLockingContext
4607 */
4608 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004609 rc = findInodeInfo(pNew, &pNew->pInode);
4610 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4611 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004612 int n;
drh2238dcc2009-08-27 17:56:20 +00004613 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004614 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004615 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004616 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004617 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4618 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004619 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004620 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004621 }
chw97185482008-11-17 08:05:31 +00004622 }
drh7708e972008-11-29 00:56:52 +00004623 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004624 }
drh7708e972008-11-29 00:56:52 +00004625#endif
aswift5b1a2562008-08-22 00:22:35 +00004626
4627 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004628#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004629 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004630 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004631 h = -1;
chw97185482008-11-17 08:05:31 +00004632 unlink(zFilename);
4633 isDelete = 0;
4634 }
4635 pNew->isDelete = isDelete;
4636#endif
danielk1977e339d652008-06-28 11:23:00 +00004637 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004638 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4639 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004640 }else{
drh7708e972008-11-29 00:56:52 +00004641 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004642 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004643 }
danielk1977e339d652008-06-28 11:23:00 +00004644 return rc;
drh054889e2005-11-30 03:20:31 +00004645}
drh9c06c952005-11-26 00:25:00 +00004646
danielk1977ad94b582007-08-20 06:44:22 +00004647/*
4648** Open a file descriptor to the directory containing file zFilename.
4649** If successful, *pFd is set to the opened file descriptor and
4650** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4651** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4652** value.
4653**
4654** If SQLITE_OK is returned, the caller is responsible for closing
4655** the file descriptor *pFd using close().
4656*/
danielk1977fee2d252007-08-18 10:59:19 +00004657static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004658 int ii;
drh777b17a2007-09-20 10:02:54 +00004659 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004660 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004661
drh153c62c2007-08-24 03:51:33 +00004662 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004663 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004664 if( ii>0 ){
4665 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004666 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004667 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004668#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004669 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004670#endif
drh308c2a52010-05-14 11:30:18 +00004671 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004672 }
4673 }
danielk1977fee2d252007-08-18 10:59:19 +00004674 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004675 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004676}
4677
danielk1977b4b47412007-08-17 15:53:36 +00004678/*
drh8b3cf822010-06-01 21:02:51 +00004679** Return the name of a directory in which to put temporary files.
4680** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004681*/
drh7234c6d2010-06-19 15:10:09 +00004682static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004683 static const char *azDirs[] = {
4684 0,
aswiftaebf4132008-11-21 00:10:35 +00004685 0,
danielk197717b90b52008-06-06 11:11:25 +00004686 "/var/tmp",
4687 "/usr/tmp",
4688 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004689 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004690 };
drh8b3cf822010-06-01 21:02:51 +00004691 unsigned int i;
4692 struct stat buf;
4693 const char *zDir = 0;
4694
4695 azDirs[0] = sqlite3_temp_directory;
4696 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004697 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004698 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004699 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004700 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004701 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004702 break;
4703 }
4704 return zDir;
4705}
4706
4707/*
4708** Create a temporary file name in zBuf. zBuf must be allocated
4709** by the calling process and must be big enough to hold at least
4710** pVfs->mxPathname bytes.
4711*/
4712static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004713 static const unsigned char zChars[] =
4714 "abcdefghijklmnopqrstuvwxyz"
4715 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4716 "0123456789";
drh41022642008-11-21 00:24:42 +00004717 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004718 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004719
4720 /* It's odd to simulate an io-error here, but really this is just
4721 ** using the io-error infrastructure to test that SQLite handles this
4722 ** function failing.
4723 */
4724 SimulateIOError( return SQLITE_IOERR );
4725
drh7234c6d2010-06-19 15:10:09 +00004726 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004727 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004728
4729 /* Check that the output buffer is large enough for the temporary file
4730 ** name. If it is not, return SQLITE_ERROR.
4731 */
danielk197700e13612008-11-17 19:18:54 +00004732 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004733 return SQLITE_ERROR;
4734 }
4735
4736 do{
4737 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004738 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004739 sqlite3_randomness(15, &zBuf[j]);
4740 for(i=0; i<15; i++, j++){
4741 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4742 }
4743 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004744 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004745 return SQLITE_OK;
4746}
4747
drhd2cb50b2009-01-09 21:41:17 +00004748#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004749/*
4750** Routine to transform a unixFile into a proxy-locking unixFile.
4751** Implementation in the proxy-lock division, but used by unixOpen()
4752** if SQLITE_PREFER_PROXY_LOCKING is defined.
4753*/
4754static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004755#endif
drhc66d5b62008-12-03 22:48:32 +00004756
dan08da86a2009-08-21 17:18:03 +00004757/*
4758** Search for an unused file descriptor that was opened on the database
4759** file (not a journal or master-journal file) identified by pathname
4760** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4761** argument to this function.
4762**
4763** Such a file descriptor may exist if a database connection was closed
4764** but the associated file descriptor could not be closed because some
4765** other file descriptor open on the same file is holding a file-lock.
4766** Refer to comments in the unixClose() function and the lengthy comment
4767** describing "Posix Advisory Locking" at the start of this file for
4768** further details. Also, ticket #4018.
4769**
4770** If a suitable file descriptor is found, then it is returned. If no
4771** such file descriptor is located, -1 is returned.
4772*/
dane946c392009-08-22 11:39:46 +00004773static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4774 UnixUnusedFd *pUnused = 0;
4775
4776 /* Do not search for an unused file descriptor on vxworks. Not because
4777 ** vxworks would not benefit from the change (it might, we're not sure),
4778 ** but because no way to test it is currently available. It is better
4779 ** not to risk breaking vxworks support for the sake of such an obscure
4780 ** feature. */
4781#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004782 struct stat sStat; /* Results of stat() call */
4783
4784 /* A stat() call may fail for various reasons. If this happens, it is
4785 ** almost certain that an open() call on the same path will also fail.
4786 ** For this reason, if an error occurs in the stat() call here, it is
4787 ** ignored and -1 is returned. The caller will try to open a new file
4788 ** descriptor on the same path, fail, and return an error to SQLite.
4789 **
4790 ** Even if a subsequent open() call does succeed, the consequences of
4791 ** not searching for a resusable file descriptor are not dire. */
4792 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004793 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004794
4795 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004796 pInode = inodeList;
4797 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4798 || pInode->fileId.ino!=sStat.st_ino) ){
4799 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004800 }
drh8af6c222010-05-14 12:43:01 +00004801 if( pInode ){
dane946c392009-08-22 11:39:46 +00004802 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004803 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004804 pUnused = *pp;
4805 if( pUnused ){
4806 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004807 }
4808 }
4809 unixLeaveMutex();
4810 }
dane946c392009-08-22 11:39:46 +00004811#endif /* if !OS_VXWORKS */
4812 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004813}
danielk197717b90b52008-06-06 11:11:25 +00004814
4815/*
danddb0ac42010-07-14 14:48:58 +00004816** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004817** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004818** and a value suitable for passing as the third argument to open(2) is
4819** written to *pMode. If an IO error occurs, an SQLite error code is
4820** returned and the value of *pMode is not modified.
4821**
4822** If the file being opened is a temporary file, it is always created with
4823** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004824** is a database or master journal file, it is created with the permissions
4825** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004826**
drh8ab58662010-07-15 18:38:39 +00004827** Finally, if the file being opened is a WAL or regular journal file, then
4828** this function queries the file-system for the permissions on the
4829** corresponding database file and sets *pMode to this value. Whenever
4830** possible, WAL and journal files are created using the same permissions
4831** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004832**
4833** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4834** original filename is unavailable. But 8_3_NAMES is only used for
4835** FAT filesystems and permissions do not matter there, so just use
4836** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004837*/
4838static int findCreateFileMode(
4839 const char *zPath, /* Path of file (possibly) being created */
4840 int flags, /* Flags passed as 4th argument to xOpen() */
4841 mode_t *pMode /* OUT: Permissions to open file with */
4842){
4843 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004844 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004845 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004846 char zDb[MAX_PATHNAME+1]; /* Database file path */
4847 int nDb; /* Number of valid bytes in zDb */
4848 struct stat sStat; /* Output of stat() on database file */
4849
dana0c989d2010-11-05 18:07:37 +00004850 /* zPath is a path to a WAL or journal file. The following block derives
4851 ** the path to the associated database file from zPath. This block handles
4852 ** the following naming conventions:
4853 **
4854 ** "<path to db>-journal"
4855 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004856 ** "<path to db>-journalNN"
4857 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004858 **
drh81cc5162011-05-17 20:36:21 +00004859 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004860 ** used by the test_multiplex.c module.
4861 */
4862 nDb = sqlite3Strlen30(zPath) - 1;
drh81cc5162011-05-17 20:36:21 +00004863 while( nDb>0 && zPath[nDb]!='-' ) nDb--;
4864 if( nDb==0 ) return SQLITE_OK;
danddb0ac42010-07-14 14:48:58 +00004865 memcpy(zDb, zPath, nDb);
4866 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004867
danddb0ac42010-07-14 14:48:58 +00004868 if( 0==stat(zDb, &sStat) ){
4869 *pMode = sStat.st_mode & 0777;
4870 }else{
4871 rc = SQLITE_IOERR_FSTAT;
4872 }
4873 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4874 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004875 }
4876 return rc;
4877}
4878
4879/*
danielk1977ad94b582007-08-20 06:44:22 +00004880** Open the file zPath.
4881**
danielk1977b4b47412007-08-17 15:53:36 +00004882** Previously, the SQLite OS layer used three functions in place of this
4883** one:
4884**
4885** sqlite3OsOpenReadWrite();
4886** sqlite3OsOpenReadOnly();
4887** sqlite3OsOpenExclusive();
4888**
4889** These calls correspond to the following combinations of flags:
4890**
4891** ReadWrite() -> (READWRITE | CREATE)
4892** ReadOnly() -> (READONLY)
4893** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4894**
4895** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4896** true, the file was configured to be automatically deleted when the
4897** file handle closed. To achieve the same effect using this new
4898** interface, add the DELETEONCLOSE flag to those specified above for
4899** OpenExclusive().
4900*/
4901static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004902 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4903 const char *zPath, /* Pathname of file to be opened */
4904 sqlite3_file *pFile, /* The file descriptor to be filled in */
4905 int flags, /* Input flags to control the opening */
4906 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004907){
dan08da86a2009-08-21 17:18:03 +00004908 unixFile *p = (unixFile *)pFile;
4909 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004910 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004911 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004912 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004913 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004914 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004915
4916 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4917 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4918 int isCreate = (flags & SQLITE_OPEN_CREATE);
4919 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4920 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004921#if SQLITE_ENABLE_LOCKING_STYLE
4922 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4923#endif
danielk1977b4b47412007-08-17 15:53:36 +00004924
danielk1977fee2d252007-08-18 10:59:19 +00004925 /* If creating a master or main-file journal, this function will open
4926 ** a file-descriptor on the directory too. The first time unixSync()
4927 ** is called the directory file descriptor will be fsync()ed and close()d.
4928 */
danddb0ac42010-07-14 14:48:58 +00004929 int isOpenDirectory = (isCreate && (
4930 eType==SQLITE_OPEN_MASTER_JOURNAL
4931 || eType==SQLITE_OPEN_MAIN_JOURNAL
4932 || eType==SQLITE_OPEN_WAL
4933 ));
danielk1977fee2d252007-08-18 10:59:19 +00004934
danielk197717b90b52008-06-06 11:11:25 +00004935 /* If argument zPath is a NULL pointer, this function is required to open
4936 ** a temporary file. Use this buffer to store the file name in.
4937 */
4938 char zTmpname[MAX_PATHNAME+1];
4939 const char *zName = zPath;
4940
danielk1977fee2d252007-08-18 10:59:19 +00004941 /* Check the following statements are true:
4942 **
4943 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4944 ** (b) if CREATE is set, then READWRITE must also be set, and
4945 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004946 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004947 */
danielk1977b4b47412007-08-17 15:53:36 +00004948 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004949 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004950 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004951 assert(isDelete==0 || isCreate);
4952
danddb0ac42010-07-14 14:48:58 +00004953 /* The main DB, main journal, WAL file and master journal are never
4954 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004955 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4956 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4957 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004958 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004959
danielk1977fee2d252007-08-18 10:59:19 +00004960 /* Assert that the upper layer has set one of the "file-type" flags. */
4961 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4962 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4963 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004964 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004965 );
4966
dan08da86a2009-08-21 17:18:03 +00004967 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004968
dan08da86a2009-08-21 17:18:03 +00004969 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004970 UnixUnusedFd *pUnused;
4971 pUnused = findReusableFd(zName, flags);
4972 if( pUnused ){
4973 fd = pUnused->fd;
4974 }else{
dan6aa657f2009-08-24 18:57:58 +00004975 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004976 if( !pUnused ){
4977 return SQLITE_NOMEM;
4978 }
4979 }
4980 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004981 }else if( !zName ){
4982 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004983 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004984 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004985 if( rc!=SQLITE_OK ){
4986 return rc;
4987 }
4988 zName = zTmpname;
4989 }
4990
dan08da86a2009-08-21 17:18:03 +00004991 /* Determine the value of the flags parameter passed to POSIX function
4992 ** open(). These must be calculated even if open() is not called, as
4993 ** they may be stored as part of the file handle and used by the
4994 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004995 if( isReadonly ) openFlags |= O_RDONLY;
4996 if( isReadWrite ) openFlags |= O_RDWR;
4997 if( isCreate ) openFlags |= O_CREAT;
4998 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4999 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005000
danielk1977b4b47412007-08-17 15:53:36 +00005001 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005002 mode_t openMode; /* Permissions to create file with */
5003 rc = findCreateFileMode(zName, flags, &openMode);
5004 if( rc!=SQLITE_OK ){
5005 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005006 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005007 return rc;
5008 }
drhad4f1e52011-03-04 15:43:57 +00005009 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005010 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005011 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5012 /* Failed to open the file for read/write access. Try read-only. */
5013 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005014 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005015 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005016 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005017 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005018 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005019 }
5020 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005021 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005022 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005023 }
danielk1977b4b47412007-08-17 15:53:36 +00005024 }
dan08da86a2009-08-21 17:18:03 +00005025 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005026 if( pOutFlags ){
5027 *pOutFlags = flags;
5028 }
5029
dane946c392009-08-22 11:39:46 +00005030 if( p->pUnused ){
5031 p->pUnused->fd = fd;
5032 p->pUnused->flags = flags;
5033 }
5034
danielk1977b4b47412007-08-17 15:53:36 +00005035 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005036#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005037 zPath = zName;
5038#else
danielk197717b90b52008-06-06 11:11:25 +00005039 unlink(zName);
chw97185482008-11-17 08:05:31 +00005040#endif
danielk1977b4b47412007-08-17 15:53:36 +00005041 }
drh41022642008-11-21 00:24:42 +00005042#if SQLITE_ENABLE_LOCKING_STYLE
5043 else{
dan08da86a2009-08-21 17:18:03 +00005044 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005045 }
5046#endif
5047
danielk1977fee2d252007-08-18 10:59:19 +00005048 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005049 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005050 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005051 /* It is safe to close fd at this point, because it is guaranteed not
5052 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005053 ** it would not be safe to close as this would release any locks held
5054 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005055 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005056 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005057 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005058 }
5059 }
danielk1977e339d652008-06-28 11:23:00 +00005060
5061#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005062 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005063#endif
5064
drhda0e7682008-07-30 15:27:54 +00005065 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005066
drh7ed97b92010-01-20 13:07:21 +00005067
5068#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5069 struct statfs fsInfo;
5070 if( fstatfs(fd, &fsInfo) == -1 ){
5071 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005072 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5073 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005074 return SQLITE_IOERR_ACCESS;
5075 }
5076 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5077 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5078 }
5079#endif
5080
5081#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005082#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005083 isAutoProxy = 1;
5084#endif
5085 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005086 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5087 int useProxy = 0;
5088
dan08da86a2009-08-21 17:18:03 +00005089 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5090 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005091 if( envforce!=NULL ){
5092 useProxy = atoi(envforce)>0;
5093 }else{
5094 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005095 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005096 /* In theory, the close(fd) call is sub-optimal. If the file opened
5097 ** with fd is a database file, and there are other connections open
5098 ** on that file that are currently holding advisory locks on it,
5099 ** then the call to close() will cancel those locks. In practice,
5100 ** we're assuming that statfs() doesn't fail very often. At least
5101 ** not while other file descriptors opened by the same process on
5102 ** the same file are working. */
5103 p->lastErrno = errno;
5104 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005105 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005106 }
drh0e9365c2011-03-02 02:08:13 +00005107 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005108 rc = SQLITE_IOERR_ACCESS;
5109 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005110 }
5111 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5112 }
5113 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005114 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5115 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005116 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005117 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005118 if( rc!=SQLITE_OK ){
5119 /* Use unixClose to clean up the resources added in fillInUnixFile
5120 ** and clear all the structure's references. Specifically,
5121 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5122 */
5123 unixClose(pFile);
5124 return rc;
5125 }
aswiftaebf4132008-11-21 00:10:35 +00005126 }
dane946c392009-08-22 11:39:46 +00005127 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005128 }
5129 }
5130#endif
5131
drh77197112011-03-15 19:08:48 +00005132 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5133 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005134open_finished:
5135 if( rc!=SQLITE_OK ){
5136 sqlite3_free(p->pUnused);
5137 }
5138 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005139}
5140
dane946c392009-08-22 11:39:46 +00005141
danielk1977b4b47412007-08-17 15:53:36 +00005142/*
danielk1977fee2d252007-08-18 10:59:19 +00005143** Delete the file at zPath. If the dirSync argument is true, fsync()
5144** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005145*/
drh6b9d6dd2008-12-03 19:34:47 +00005146static int unixDelete(
5147 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5148 const char *zPath, /* Name of file to be deleted */
5149 int dirSync /* If true, fsync() directory after deleting file */
5150){
danielk1977fee2d252007-08-18 10:59:19 +00005151 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005152 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005153 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005154 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005155 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005156 }
danielk1977d39fa702008-10-16 13:27:40 +00005157#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005158 if( dirSync ){
5159 int fd;
5160 rc = openDirectory(zPath, &fd);
5161 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005162#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005163 if( fsync(fd)==-1 )
5164#else
5165 if( fsync(fd) )
5166#endif
5167 {
dane18d4952011-02-21 11:46:24 +00005168 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005169 }
drh0e9365c2011-03-02 02:08:13 +00005170 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005171 }
5172 }
danielk1977d138dd82008-10-15 16:02:48 +00005173#endif
danielk1977fee2d252007-08-18 10:59:19 +00005174 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005175}
5176
danielk197790949c22007-08-17 16:50:38 +00005177/*
5178** Test the existance of or access permissions of file zPath. The
5179** test performed depends on the value of flags:
5180**
5181** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5182** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5183** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5184**
5185** Otherwise return 0.
5186*/
danielk1977861f7452008-06-05 11:39:11 +00005187static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005188 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5189 const char *zPath, /* Path of the file to examine */
5190 int flags, /* What do we want to learn about the zPath file? */
5191 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005192){
rse25c0d1a2007-09-20 08:38:14 +00005193 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005194 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005195 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005196 switch( flags ){
5197 case SQLITE_ACCESS_EXISTS:
5198 amode = F_OK;
5199 break;
5200 case SQLITE_ACCESS_READWRITE:
5201 amode = W_OK|R_OK;
5202 break;
drh50d3f902007-08-27 21:10:36 +00005203 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005204 amode = R_OK;
5205 break;
5206
5207 default:
5208 assert(!"Invalid flags argument");
5209 }
drh99ab3b12011-03-02 15:09:07 +00005210 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005211 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5212 struct stat buf;
5213 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5214 *pResOut = 0;
5215 }
5216 }
danielk1977861f7452008-06-05 11:39:11 +00005217 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005218}
5219
danielk1977b4b47412007-08-17 15:53:36 +00005220
5221/*
5222** Turn a relative pathname into a full pathname. The relative path
5223** is stored as a nul-terminated string in the buffer pointed to by
5224** zPath.
5225**
5226** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5227** (in this case, MAX_PATHNAME bytes). The full-path is written to
5228** this buffer before returning.
5229*/
danielk1977adfb9b02007-09-17 07:02:56 +00005230static int unixFullPathname(
5231 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5232 const char *zPath, /* Possibly relative input path */
5233 int nOut, /* Size of output buffer in bytes */
5234 char *zOut /* Output buffer */
5235){
danielk1977843e65f2007-09-01 16:16:15 +00005236
5237 /* It's odd to simulate an io-error here, but really this is just
5238 ** using the io-error infrastructure to test that SQLite handles this
5239 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005240 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005241 */
5242 SimulateIOError( return SQLITE_ERROR );
5243
drh153c62c2007-08-24 03:51:33 +00005244 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005245 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005246
drh3c7f2dc2007-12-06 13:26:20 +00005247 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005248 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005249 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005250 }else{
5251 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005252 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005253 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005254 }
drhea678832008-12-10 19:26:22 +00005255 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005256 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005257 }
5258 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005259}
5260
drh0ccebe72005-06-07 22:22:50 +00005261
drh761df872006-12-21 01:29:22 +00005262#ifndef SQLITE_OMIT_LOAD_EXTENSION
5263/*
5264** Interfaces for opening a shared library, finding entry points
5265** within the shared library, and closing the shared library.
5266*/
5267#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005268static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5269 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005270 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5271}
danielk197795c8a542007-09-01 06:51:27 +00005272
5273/*
5274** SQLite calls this function immediately after a call to unixDlSym() or
5275** unixDlOpen() fails (returns a null pointer). If a more detailed error
5276** message is available, it is written to zBufOut. If no error message
5277** is available, zBufOut is left unmodified and SQLite uses a default
5278** error message.
5279*/
danielk1977397d65f2008-11-19 11:35:39 +00005280static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005281 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005282 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005283 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005284 zErr = dlerror();
5285 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005286 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005287 }
drh6c7d5c52008-11-21 20:32:33 +00005288 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005289}
drh1875f7a2008-12-08 18:19:17 +00005290static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5291 /*
5292 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5293 ** cast into a pointer to a function. And yet the library dlsym() routine
5294 ** returns a void* which is really a pointer to a function. So how do we
5295 ** use dlsym() with -pedantic-errors?
5296 **
5297 ** Variable x below is defined to be a pointer to a function taking
5298 ** parameters void* and const char* and returning a pointer to a function.
5299 ** We initialize x by assigning it a pointer to the dlsym() function.
5300 ** (That assignment requires a cast.) Then we call the function that
5301 ** x points to.
5302 **
5303 ** This work-around is unlikely to work correctly on any system where
5304 ** you really cannot cast a function pointer into void*. But then, on the
5305 ** other hand, dlsym() will not work on such a system either, so we have
5306 ** not really lost anything.
5307 */
5308 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005309 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005310 x = (void(*(*)(void*,const char*))(void))dlsym;
5311 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005312}
danielk1977397d65f2008-11-19 11:35:39 +00005313static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5314 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005315 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005316}
danielk1977b4b47412007-08-17 15:53:36 +00005317#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5318 #define unixDlOpen 0
5319 #define unixDlError 0
5320 #define unixDlSym 0
5321 #define unixDlClose 0
5322#endif
5323
5324/*
danielk197790949c22007-08-17 16:50:38 +00005325** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005326*/
danielk1977397d65f2008-11-19 11:35:39 +00005327static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5328 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005329 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005330
drhbbd42a62004-05-22 17:41:58 +00005331 /* We have to initialize zBuf to prevent valgrind from reporting
5332 ** errors. The reports issued by valgrind are incorrect - we would
5333 ** prefer that the randomness be increased by making use of the
5334 ** uninitialized space in zBuf - but valgrind errors tend to worry
5335 ** some users. Rather than argue, it seems easier just to initialize
5336 ** the whole array and silence valgrind, even if that means less randomness
5337 ** in the random seed.
5338 **
5339 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005340 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005341 ** tests repeatable.
5342 */
danielk1977b4b47412007-08-17 15:53:36 +00005343 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005344#if !defined(SQLITE_TEST)
5345 {
drh842b8642005-01-21 17:53:17 +00005346 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005347 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005348 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005349 time_t t;
5350 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005351 memcpy(zBuf, &t, sizeof(t));
5352 pid = getpid();
5353 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005354 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005355 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005356 }else{
drhe562be52011-03-02 18:01:10 +00005357 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005358 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005359 }
drhbbd42a62004-05-22 17:41:58 +00005360 }
5361#endif
drh72cbd072008-10-14 17:58:38 +00005362 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005363}
5364
danielk1977b4b47412007-08-17 15:53:36 +00005365
drhbbd42a62004-05-22 17:41:58 +00005366/*
5367** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005368** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005369** The return value is the number of microseconds of sleep actually
5370** requested from the underlying operating system, a number which
5371** might be greater than or equal to the argument, but not less
5372** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005373*/
danielk1977397d65f2008-11-19 11:35:39 +00005374static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005375#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005376 struct timespec sp;
5377
5378 sp.tv_sec = microseconds / 1000000;
5379 sp.tv_nsec = (microseconds % 1000000) * 1000;
5380 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005381 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005382 return microseconds;
5383#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005384 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005385 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005386 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005387#else
danielk1977b4b47412007-08-17 15:53:36 +00005388 int seconds = (microseconds+999999)/1000000;
5389 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005390 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005391 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005392#endif
drh88f474a2006-01-02 20:00:12 +00005393}
5394
5395/*
drh6b9d6dd2008-12-03 19:34:47 +00005396** The following variable, if set to a non-zero value, is interpreted as
5397** the number of seconds since 1970 and is used to set the result of
5398** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005399*/
5400#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005401int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005402#endif
5403
5404/*
drhb7e8ea22010-05-03 14:32:30 +00005405** Find the current time (in Universal Coordinated Time). Write into *piNow
5406** the current time and date as a Julian Day number times 86_400_000. In
5407** other words, write into *piNow the number of milliseconds since the Julian
5408** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5409** proleptic Gregorian calendar.
5410**
5411** On success, return 0. Return 1 if the time and date cannot be found.
5412*/
5413static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5414 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5415#if defined(NO_GETTOD)
5416 time_t t;
5417 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005418 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005419#elif OS_VXWORKS
5420 struct timespec sNow;
5421 clock_gettime(CLOCK_REALTIME, &sNow);
5422 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5423#else
5424 struct timeval sNow;
5425 gettimeofday(&sNow, 0);
5426 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5427#endif
5428
5429#ifdef SQLITE_TEST
5430 if( sqlite3_current_time ){
5431 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5432 }
5433#endif
5434 UNUSED_PARAMETER(NotUsed);
5435 return 0;
5436}
5437
5438/*
drhbbd42a62004-05-22 17:41:58 +00005439** Find the current time (in Universal Coordinated Time). Write the
5440** current time and date as a Julian Day number into *prNow and
5441** return 0. Return 1 if the time and date cannot be found.
5442*/
danielk1977397d65f2008-11-19 11:35:39 +00005443static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005444 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005445 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005446 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005447 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005448 return 0;
5449}
danielk1977b4b47412007-08-17 15:53:36 +00005450
drh6b9d6dd2008-12-03 19:34:47 +00005451/*
5452** We added the xGetLastError() method with the intention of providing
5453** better low-level error messages when operating-system problems come up
5454** during SQLite operation. But so far, none of that has been implemented
5455** in the core. So this routine is never called. For now, it is merely
5456** a place-holder.
5457*/
danielk1977397d65f2008-11-19 11:35:39 +00005458static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5459 UNUSED_PARAMETER(NotUsed);
5460 UNUSED_PARAMETER(NotUsed2);
5461 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005462 return 0;
5463}
5464
drhf2424c52010-04-26 00:04:55 +00005465
5466/*
drh734c9862008-11-28 15:37:20 +00005467************************ End of sqlite3_vfs methods ***************************
5468******************************************************************************/
5469
drh715ff302008-12-03 22:32:44 +00005470/******************************************************************************
5471************************** Begin Proxy Locking ********************************
5472**
5473** Proxy locking is a "uber-locking-method" in this sense: It uses the
5474** other locking methods on secondary lock files. Proxy locking is a
5475** meta-layer over top of the primitive locking implemented above. For
5476** this reason, the division that implements of proxy locking is deferred
5477** until late in the file (here) after all of the other I/O methods have
5478** been defined - so that the primitive locking methods are available
5479** as services to help with the implementation of proxy locking.
5480**
5481****
5482**
5483** The default locking schemes in SQLite use byte-range locks on the
5484** database file to coordinate safe, concurrent access by multiple readers
5485** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5486** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5487** as POSIX read & write locks over fixed set of locations (via fsctl),
5488** on AFP and SMB only exclusive byte-range locks are available via fsctl
5489** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5490** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5491** address in the shared range is taken for a SHARED lock, the entire
5492** shared range is taken for an EXCLUSIVE lock):
5493**
5494** PENDING_BYTE 0x40000000
5495** RESERVED_BYTE 0x40000001
5496** SHARED_RANGE 0x40000002 -> 0x40000200
5497**
5498** This works well on the local file system, but shows a nearly 100x
5499** slowdown in read performance on AFP because the AFP client disables
5500** the read cache when byte-range locks are present. Enabling the read
5501** cache exposes a cache coherency problem that is present on all OS X
5502** supported network file systems. NFS and AFP both observe the
5503** close-to-open semantics for ensuring cache coherency
5504** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5505** address the requirements for concurrent database access by multiple
5506** readers and writers
5507** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5508**
5509** To address the performance and cache coherency issues, proxy file locking
5510** changes the way database access is controlled by limiting access to a
5511** single host at a time and moving file locks off of the database file
5512** and onto a proxy file on the local file system.
5513**
5514**
5515** Using proxy locks
5516** -----------------
5517**
5518** C APIs
5519**
5520** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5521** <proxy_path> | ":auto:");
5522** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5523**
5524**
5525** SQL pragmas
5526**
5527** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5528** PRAGMA [database.]lock_proxy_file
5529**
5530** Specifying ":auto:" means that if there is a conch file with a matching
5531** host ID in it, the proxy path in the conch file will be used, otherwise
5532** a proxy path based on the user's temp dir
5533** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5534** actual proxy file name is generated from the name and path of the
5535** database file. For example:
5536**
5537** For database path "/Users/me/foo.db"
5538** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5539**
5540** Once a lock proxy is configured for a database connection, it can not
5541** be removed, however it may be switched to a different proxy path via
5542** the above APIs (assuming the conch file is not being held by another
5543** connection or process).
5544**
5545**
5546** How proxy locking works
5547** -----------------------
5548**
5549** Proxy file locking relies primarily on two new supporting files:
5550**
5551** * conch file to limit access to the database file to a single host
5552** at a time
5553**
5554** * proxy file to act as a proxy for the advisory locks normally
5555** taken on the database
5556**
5557** The conch file - to use a proxy file, sqlite must first "hold the conch"
5558** by taking an sqlite-style shared lock on the conch file, reading the
5559** contents and comparing the host's unique host ID (see below) and lock
5560** proxy path against the values stored in the conch. The conch file is
5561** stored in the same directory as the database file and the file name
5562** is patterned after the database file name as ".<databasename>-conch".
5563** If the conch file does not exist, or it's contents do not match the
5564** host ID and/or proxy path, then the lock is escalated to an exclusive
5565** lock and the conch file contents is updated with the host ID and proxy
5566** path and the lock is downgraded to a shared lock again. If the conch
5567** is held by another process (with a shared lock), the exclusive lock
5568** will fail and SQLITE_BUSY is returned.
5569**
5570** The proxy file - a single-byte file used for all advisory file locks
5571** normally taken on the database file. This allows for safe sharing
5572** of the database file for multiple readers and writers on the same
5573** host (the conch ensures that they all use the same local lock file).
5574**
drh715ff302008-12-03 22:32:44 +00005575** Requesting the lock proxy does not immediately take the conch, it is
5576** only taken when the first request to lock database file is made.
5577** This matches the semantics of the traditional locking behavior, where
5578** opening a connection to a database file does not take a lock on it.
5579** The shared lock and an open file descriptor are maintained until
5580** the connection to the database is closed.
5581**
5582** The proxy file and the lock file are never deleted so they only need
5583** to be created the first time they are used.
5584**
5585** Configuration options
5586** ---------------------
5587**
5588** SQLITE_PREFER_PROXY_LOCKING
5589**
5590** Database files accessed on non-local file systems are
5591** automatically configured for proxy locking, lock files are
5592** named automatically using the same logic as
5593** PRAGMA lock_proxy_file=":auto:"
5594**
5595** SQLITE_PROXY_DEBUG
5596**
5597** Enables the logging of error messages during host id file
5598** retrieval and creation
5599**
drh715ff302008-12-03 22:32:44 +00005600** LOCKPROXYDIR
5601**
5602** Overrides the default directory used for lock proxy files that
5603** are named automatically via the ":auto:" setting
5604**
5605** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5606**
5607** Permissions to use when creating a directory for storing the
5608** lock proxy files, only used when LOCKPROXYDIR is not set.
5609**
5610**
5611** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5612** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5613** force proxy locking to be used for every database file opened, and 0
5614** will force automatic proxy locking to be disabled for all database
5615** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5616** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5617*/
5618
5619/*
5620** Proxy locking is only available on MacOSX
5621*/
drhd2cb50b2009-01-09 21:41:17 +00005622#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005623
drh715ff302008-12-03 22:32:44 +00005624/*
5625** The proxyLockingContext has the path and file structures for the remote
5626** and local proxy files in it
5627*/
5628typedef struct proxyLockingContext proxyLockingContext;
5629struct proxyLockingContext {
5630 unixFile *conchFile; /* Open conch file */
5631 char *conchFilePath; /* Name of the conch file */
5632 unixFile *lockProxy; /* Open proxy lock file */
5633 char *lockProxyPath; /* Name of the proxy lock file */
5634 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005635 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005636 void *oldLockingContext; /* Original lockingcontext to restore on close */
5637 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5638};
5639
drh7ed97b92010-01-20 13:07:21 +00005640/*
5641** The proxy lock file path for the database at dbPath is written into lPath,
5642** which must point to valid, writable memory large enough for a maxLen length
5643** file path.
drh715ff302008-12-03 22:32:44 +00005644*/
drh715ff302008-12-03 22:32:44 +00005645static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5646 int len;
5647 int dbLen;
5648 int i;
5649
5650#ifdef LOCKPROXYDIR
5651 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5652#else
5653# ifdef _CS_DARWIN_USER_TEMP_DIR
5654 {
drh7ed97b92010-01-20 13:07:21 +00005655 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005656 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5657 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005658 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005659 }
drh7ed97b92010-01-20 13:07:21 +00005660 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005661 }
5662# else
5663 len = strlcpy(lPath, "/tmp/", maxLen);
5664# endif
5665#endif
5666
5667 if( lPath[len-1]!='/' ){
5668 len = strlcat(lPath, "/", maxLen);
5669 }
5670
5671 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005672 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005673 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005674 char c = dbPath[i];
5675 lPath[i+len] = (c=='/')?'_':c;
5676 }
5677 lPath[i+len]='\0';
5678 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005679 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005680 return SQLITE_OK;
5681}
5682
drh7ed97b92010-01-20 13:07:21 +00005683/*
5684 ** Creates the lock file and any missing directories in lockPath
5685 */
5686static int proxyCreateLockPath(const char *lockPath){
5687 int i, len;
5688 char buf[MAXPATHLEN];
5689 int start = 0;
5690
5691 assert(lockPath!=NULL);
5692 /* try to create all the intermediate directories */
5693 len = (int)strlen(lockPath);
5694 buf[0] = lockPath[0];
5695 for( i=1; i<len; i++ ){
5696 if( lockPath[i] == '/' && (i - start > 0) ){
5697 /* only mkdir if leaf dir != "." or "/" or ".." */
5698 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5699 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5700 buf[i]='\0';
5701 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5702 int err=errno;
5703 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005704 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005705 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005706 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005707 return err;
5708 }
5709 }
5710 }
5711 start=i+1;
5712 }
5713 buf[i] = lockPath[i];
5714 }
drh308c2a52010-05-14 11:30:18 +00005715 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005716 return 0;
5717}
5718
drh715ff302008-12-03 22:32:44 +00005719/*
5720** Create a new VFS file descriptor (stored in memory obtained from
5721** sqlite3_malloc) and open the file named "path" in the file descriptor.
5722**
5723** The caller is responsible not only for closing the file descriptor
5724** but also for freeing the memory associated with the file descriptor.
5725*/
drh7ed97b92010-01-20 13:07:21 +00005726static int proxyCreateUnixFile(
5727 const char *path, /* path for the new unixFile */
5728 unixFile **ppFile, /* unixFile created and returned by ref */
5729 int islockfile /* if non zero missing dirs will be created */
5730) {
5731 int fd = -1;
5732 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005733 unixFile *pNew;
5734 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005735 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005736 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005737 int terrno = 0;
5738 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005739
drh7ed97b92010-01-20 13:07:21 +00005740 /* 1. first try to open/create the file
5741 ** 2. if that fails, and this is a lock file (not-conch), try creating
5742 ** the parent directories and then try again.
5743 ** 3. if that fails, try to open the file read-only
5744 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5745 */
5746 pUnused = findReusableFd(path, openFlags);
5747 if( pUnused ){
5748 fd = pUnused->fd;
5749 }else{
5750 pUnused = sqlite3_malloc(sizeof(*pUnused));
5751 if( !pUnused ){
5752 return SQLITE_NOMEM;
5753 }
5754 }
5755 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005756 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005757 terrno = errno;
5758 if( fd<0 && errno==ENOENT && islockfile ){
5759 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005760 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005761 }
5762 }
5763 }
5764 if( fd<0 ){
5765 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005766 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005767 terrno = errno;
5768 }
5769 if( fd<0 ){
5770 if( islockfile ){
5771 return SQLITE_BUSY;
5772 }
5773 switch (terrno) {
5774 case EACCES:
5775 return SQLITE_PERM;
5776 case EIO:
5777 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5778 default:
drh9978c972010-02-23 17:36:32 +00005779 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005780 }
5781 }
5782
5783 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5784 if( pNew==NULL ){
5785 rc = SQLITE_NOMEM;
5786 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005787 }
5788 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005789 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005790 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005791 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005792 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005793 pUnused->fd = fd;
5794 pUnused->flags = openFlags;
5795 pNew->pUnused = pUnused;
5796
drh77197112011-03-15 19:08:48 +00005797 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005798 if( rc==SQLITE_OK ){
5799 *ppFile = pNew;
5800 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005801 }
drh7ed97b92010-01-20 13:07:21 +00005802end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005803 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005804 sqlite3_free(pNew);
5805 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005806 return rc;
5807}
5808
drh7ed97b92010-01-20 13:07:21 +00005809#ifdef SQLITE_TEST
5810/* simulate multiple hosts by creating unique hostid file paths */
5811int sqlite3_hostid_num = 0;
5812#endif
5813
5814#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5815
drh0ab216a2010-07-02 17:10:40 +00005816/* Not always defined in the headers as it ought to be */
5817extern int gethostuuid(uuid_t id, const struct timespec *wait);
5818
drh7ed97b92010-01-20 13:07:21 +00005819/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5820** bytes of writable memory.
5821*/
5822static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005823 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5824 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005825#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5826 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005827 {
5828 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5829 if( gethostuuid(pHostID, &timeout) ){
5830 int err = errno;
5831 if( pError ){
5832 *pError = err;
5833 }
5834 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005835 }
drh7ed97b92010-01-20 13:07:21 +00005836 }
drhe8b0c9b2010-09-25 14:13:17 +00005837#endif
drh7ed97b92010-01-20 13:07:21 +00005838#ifdef SQLITE_TEST
5839 /* simulate multiple hosts by creating unique hostid file paths */
5840 if( sqlite3_hostid_num != 0){
5841 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5842 }
5843#endif
5844
5845 return SQLITE_OK;
5846}
5847
5848/* The conch file contains the header, host id and lock file path
5849 */
5850#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5851#define PROXY_HEADERLEN 1 /* conch file header length */
5852#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5853#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5854
5855/*
5856** Takes an open conch file, copies the contents to a new path and then moves
5857** it back. The newly created file's file descriptor is assigned to the
5858** conch file structure and finally the original conch file descriptor is
5859** closed. Returns zero if successful.
5860*/
5861static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5862 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5863 unixFile *conchFile = pCtx->conchFile;
5864 char tPath[MAXPATHLEN];
5865 char buf[PROXY_MAXCONCHLEN];
5866 char *cPath = pCtx->conchFilePath;
5867 size_t readLen = 0;
5868 size_t pathLen = 0;
5869 char errmsg[64] = "";
5870 int fd = -1;
5871 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005872 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005873
5874 /* create a new path by replace the trailing '-conch' with '-break' */
5875 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5876 if( pathLen>MAXPATHLEN || pathLen<6 ||
5877 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005878 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005879 goto end_breaklock;
5880 }
5881 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005882 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005883 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005884 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005885 goto end_breaklock;
5886 }
5887 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005888 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5889 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005890 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005891 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005892 goto end_breaklock;
5893 }
drhe562be52011-03-02 18:01:10 +00005894 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005895 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005896 goto end_breaklock;
5897 }
5898 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005899 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005900 goto end_breaklock;
5901 }
5902 rc = 0;
5903 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005904 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005905 conchFile->h = fd;
5906 conchFile->openFlags = O_RDWR | O_CREAT;
5907
5908end_breaklock:
5909 if( rc ){
5910 if( fd>=0 ){
5911 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005912 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005913 }
5914 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5915 }
5916 return rc;
5917}
5918
5919/* Take the requested lock on the conch file and break a stale lock if the
5920** host id matches.
5921*/
5922static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5923 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5924 unixFile *conchFile = pCtx->conchFile;
5925 int rc = SQLITE_OK;
5926 int nTries = 0;
5927 struct timespec conchModTime;
5928
5929 do {
5930 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5931 nTries ++;
5932 if( rc==SQLITE_BUSY ){
5933 /* If the lock failed (busy):
5934 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5935 * 2nd try: fail if the mod time changed or host id is different, wait
5936 * 10 sec and try again
5937 * 3rd try: break the lock unless the mod time has changed.
5938 */
5939 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005940 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005941 pFile->lastErrno = errno;
5942 return SQLITE_IOERR_LOCK;
5943 }
5944
5945 if( nTries==1 ){
5946 conchModTime = buf.st_mtimespec;
5947 usleep(500000); /* wait 0.5 sec and try the lock again*/
5948 continue;
5949 }
5950
5951 assert( nTries>1 );
5952 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5953 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5954 return SQLITE_BUSY;
5955 }
5956
5957 if( nTries==2 ){
5958 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005959 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005960 if( len<0 ){
5961 pFile->lastErrno = errno;
5962 return SQLITE_IOERR_LOCK;
5963 }
5964 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5965 /* don't break the lock if the host id doesn't match */
5966 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5967 return SQLITE_BUSY;
5968 }
5969 }else{
5970 /* don't break the lock on short read or a version mismatch */
5971 return SQLITE_BUSY;
5972 }
5973 usleep(10000000); /* wait 10 sec and try the lock again */
5974 continue;
5975 }
5976
5977 assert( nTries==3 );
5978 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5979 rc = SQLITE_OK;
5980 if( lockType==EXCLUSIVE_LOCK ){
5981 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5982 }
5983 if( !rc ){
5984 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5985 }
5986 }
5987 }
5988 } while( rc==SQLITE_BUSY && nTries<3 );
5989
5990 return rc;
5991}
5992
5993/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005994** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5995** lockPath means that the lockPath in the conch file will be used if the
5996** host IDs match, or a new lock path will be generated automatically
5997** and written to the conch file.
5998*/
5999static int proxyTakeConch(unixFile *pFile){
6000 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6001
drh7ed97b92010-01-20 13:07:21 +00006002 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006003 return SQLITE_OK;
6004 }else{
6005 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006006 uuid_t myHostID;
6007 int pError = 0;
6008 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006009 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006010 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006011 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006012 int createConch = 0;
6013 int hostIdMatch = 0;
6014 int readLen = 0;
6015 int tryOldLockPath = 0;
6016 int forceNewLockPath = 0;
6017
drh308c2a52010-05-14 11:30:18 +00006018 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6019 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006020
drh7ed97b92010-01-20 13:07:21 +00006021 rc = proxyGetHostID(myHostID, &pError);
6022 if( (rc&0xff)==SQLITE_IOERR ){
6023 pFile->lastErrno = pError;
6024 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006025 }
drh7ed97b92010-01-20 13:07:21 +00006026 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006027 if( rc!=SQLITE_OK ){
6028 goto end_takeconch;
6029 }
drh7ed97b92010-01-20 13:07:21 +00006030 /* read the existing conch file */
6031 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6032 if( readLen<0 ){
6033 /* I/O error: lastErrno set by seekAndRead */
6034 pFile->lastErrno = conchFile->lastErrno;
6035 rc = SQLITE_IOERR_READ;
6036 goto end_takeconch;
6037 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6038 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6039 /* a short read or version format mismatch means we need to create a new
6040 ** conch file.
6041 */
6042 createConch = 1;
6043 }
6044 /* if the host id matches and the lock path already exists in the conch
6045 ** we'll try to use the path there, if we can't open that path, we'll
6046 ** retry with a new auto-generated path
6047 */
6048 do { /* in case we need to try again for an :auto: named lock file */
6049
6050 if( !createConch && !forceNewLockPath ){
6051 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6052 PROXY_HOSTIDLEN);
6053 /* if the conch has data compare the contents */
6054 if( !pCtx->lockProxyPath ){
6055 /* for auto-named local lock file, just check the host ID and we'll
6056 ** use the local lock file path that's already in there
6057 */
6058 if( hostIdMatch ){
6059 size_t pathLen = (readLen - PROXY_PATHINDEX);
6060
6061 if( pathLen>=MAXPATHLEN ){
6062 pathLen=MAXPATHLEN-1;
6063 }
6064 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6065 lockPath[pathLen] = 0;
6066 tempLockPath = lockPath;
6067 tryOldLockPath = 1;
6068 /* create a copy of the lock path if the conch is taken */
6069 goto end_takeconch;
6070 }
6071 }else if( hostIdMatch
6072 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6073 readLen-PROXY_PATHINDEX)
6074 ){
6075 /* conch host and lock path match */
6076 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006077 }
drh7ed97b92010-01-20 13:07:21 +00006078 }
6079
6080 /* if the conch isn't writable and doesn't match, we can't take it */
6081 if( (conchFile->openFlags&O_RDWR) == 0 ){
6082 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006083 goto end_takeconch;
6084 }
drh7ed97b92010-01-20 13:07:21 +00006085
6086 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006087 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006088 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6089 tempLockPath = lockPath;
6090 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006091 }
drh7ed97b92010-01-20 13:07:21 +00006092
6093 /* update conch with host and path (this will fail if other process
6094 ** has a shared lock already), if the host id matches, use the big
6095 ** stick.
drh715ff302008-12-03 22:32:44 +00006096 */
drh7ed97b92010-01-20 13:07:21 +00006097 futimes(conchFile->h, NULL);
6098 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006099 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006100 /* We are trying for an exclusive lock but another thread in this
6101 ** same process is still holding a shared lock. */
6102 rc = SQLITE_BUSY;
6103 } else {
6104 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006105 }
drh715ff302008-12-03 22:32:44 +00006106 }else{
drh7ed97b92010-01-20 13:07:21 +00006107 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006108 }
drh7ed97b92010-01-20 13:07:21 +00006109 if( rc==SQLITE_OK ){
6110 char writeBuffer[PROXY_MAXCONCHLEN];
6111 int writeSize = 0;
6112
6113 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6114 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6115 if( pCtx->lockProxyPath!=NULL ){
6116 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6117 }else{
6118 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6119 }
6120 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006121 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006122 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6123 fsync(conchFile->h);
6124 /* If we created a new conch file (not just updated the contents of a
6125 ** valid conch file), try to match the permissions of the database
6126 */
6127 if( rc==SQLITE_OK && createConch ){
6128 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006129 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006130 if( err==0 ){
6131 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6132 S_IROTH|S_IWOTH);
6133 /* try to match the database file R/W permissions, ignore failure */
6134#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006135 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006136#else
drhff812312011-02-23 13:33:46 +00006137 do{
drhe562be52011-03-02 18:01:10 +00006138 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006139 }while( rc==(-1) && errno==EINTR );
6140 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006141 int code = errno;
6142 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6143 cmode, code, strerror(code));
6144 } else {
6145 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6146 }
6147 }else{
6148 int code = errno;
6149 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6150 err, code, strerror(code));
6151#endif
6152 }
drh715ff302008-12-03 22:32:44 +00006153 }
6154 }
drh7ed97b92010-01-20 13:07:21 +00006155 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6156
6157 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006158 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006159 if( rc==SQLITE_OK && pFile->openFlags ){
6160 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006161 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006162 }
6163 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006164 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006165 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006166 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006167 if( fd>=0 ){
6168 pFile->h = fd;
6169 }else{
drh9978c972010-02-23 17:36:32 +00006170 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006171 during locking */
6172 }
6173 }
6174 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6175 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6176 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6177 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6178 /* we couldn't create the proxy lock file with the old lock file path
6179 ** so try again via auto-naming
6180 */
6181 forceNewLockPath = 1;
6182 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006183 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006184 }
6185 }
6186 if( rc==SQLITE_OK ){
6187 /* Need to make a copy of path if we extracted the value
6188 ** from the conch file or the path was allocated on the stack
6189 */
6190 if( tempLockPath ){
6191 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6192 if( !pCtx->lockProxyPath ){
6193 rc = SQLITE_NOMEM;
6194 }
6195 }
6196 }
6197 if( rc==SQLITE_OK ){
6198 pCtx->conchHeld = 1;
6199
6200 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6201 afpLockingContext *afpCtx;
6202 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6203 afpCtx->dbPath = pCtx->lockProxyPath;
6204 }
6205 } else {
6206 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6207 }
drh308c2a52010-05-14 11:30:18 +00006208 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6209 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006210 return rc;
drh308c2a52010-05-14 11:30:18 +00006211 } while (1); /* in case we need to retry the :auto: lock file -
6212 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006213 }
6214}
6215
6216/*
6217** If pFile holds a lock on a conch file, then release that lock.
6218*/
6219static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006220 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006221 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6222 unixFile *conchFile; /* Name of the conch file */
6223
6224 pCtx = (proxyLockingContext *)pFile->lockingContext;
6225 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006226 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006227 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006228 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006229 if( pCtx->conchHeld>0 ){
6230 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6231 }
drh715ff302008-12-03 22:32:44 +00006232 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006233 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6234 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006235 return rc;
6236}
6237
6238/*
6239** Given the name of a database file, compute the name of its conch file.
6240** Store the conch filename in memory obtained from sqlite3_malloc().
6241** Make *pConchPath point to the new name. Return SQLITE_OK on success
6242** or SQLITE_NOMEM if unable to obtain memory.
6243**
6244** The caller is responsible for ensuring that the allocated memory
6245** space is eventually freed.
6246**
6247** *pConchPath is set to NULL if a memory allocation error occurs.
6248*/
6249static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6250 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006251 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006252 char *conchPath; /* buffer in which to construct conch name */
6253
6254 /* Allocate space for the conch filename and initialize the name to
6255 ** the name of the original database file. */
6256 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6257 if( conchPath==0 ){
6258 return SQLITE_NOMEM;
6259 }
6260 memcpy(conchPath, dbPath, len+1);
6261
6262 /* now insert a "." before the last / character */
6263 for( i=(len-1); i>=0; i-- ){
6264 if( conchPath[i]=='/' ){
6265 i++;
6266 break;
6267 }
6268 }
6269 conchPath[i]='.';
6270 while ( i<len ){
6271 conchPath[i+1]=dbPath[i];
6272 i++;
6273 }
6274
6275 /* append the "-conch" suffix to the file */
6276 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006277 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006278
6279 return SQLITE_OK;
6280}
6281
6282
6283/* Takes a fully configured proxy locking-style unix file and switches
6284** the local lock file path
6285*/
6286static int switchLockProxyPath(unixFile *pFile, const char *path) {
6287 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6288 char *oldPath = pCtx->lockProxyPath;
6289 int rc = SQLITE_OK;
6290
drh308c2a52010-05-14 11:30:18 +00006291 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006292 return SQLITE_BUSY;
6293 }
6294
6295 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6296 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6297 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6298 return SQLITE_OK;
6299 }else{
6300 unixFile *lockProxy = pCtx->lockProxy;
6301 pCtx->lockProxy=NULL;
6302 pCtx->conchHeld = 0;
6303 if( lockProxy!=NULL ){
6304 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6305 if( rc ) return rc;
6306 sqlite3_free(lockProxy);
6307 }
6308 sqlite3_free(oldPath);
6309 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6310 }
6311
6312 return rc;
6313}
6314
6315/*
6316** pFile is a file that has been opened by a prior xOpen call. dbPath
6317** is a string buffer at least MAXPATHLEN+1 characters in size.
6318**
6319** This routine find the filename associated with pFile and writes it
6320** int dbPath.
6321*/
6322static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006323#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006324 if( pFile->pMethod == &afpIoMethods ){
6325 /* afp style keeps a reference to the db path in the filePath field
6326 ** of the struct */
drhea678832008-12-10 19:26:22 +00006327 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006328 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6329 } else
drh715ff302008-12-03 22:32:44 +00006330#endif
6331 if( pFile->pMethod == &dotlockIoMethods ){
6332 /* dot lock style uses the locking context to store the dot lock
6333 ** file path */
6334 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6335 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6336 }else{
6337 /* all other styles use the locking context to store the db file path */
6338 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006339 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006340 }
6341 return SQLITE_OK;
6342}
6343
6344/*
6345** Takes an already filled in unix file and alters it so all file locking
6346** will be performed on the local proxy lock file. The following fields
6347** are preserved in the locking context so that they can be restored and
6348** the unix structure properly cleaned up at close time:
6349** ->lockingContext
6350** ->pMethod
6351*/
6352static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6353 proxyLockingContext *pCtx;
6354 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6355 char *lockPath=NULL;
6356 int rc = SQLITE_OK;
6357
drh308c2a52010-05-14 11:30:18 +00006358 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006359 return SQLITE_BUSY;
6360 }
6361 proxyGetDbPathForUnixFile(pFile, dbPath);
6362 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6363 lockPath=NULL;
6364 }else{
6365 lockPath=(char *)path;
6366 }
6367
drh308c2a52010-05-14 11:30:18 +00006368 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6369 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006370
6371 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6372 if( pCtx==0 ){
6373 return SQLITE_NOMEM;
6374 }
6375 memset(pCtx, 0, sizeof(*pCtx));
6376
6377 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6378 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006379 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6380 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6381 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6382 ** (c) the file system is read-only, then enable no-locking access.
6383 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6384 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6385 */
6386 struct statfs fsInfo;
6387 struct stat conchInfo;
6388 int goLockless = 0;
6389
drh99ab3b12011-03-02 15:09:07 +00006390 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006391 int err = errno;
6392 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6393 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6394 }
6395 }
6396 if( goLockless ){
6397 pCtx->conchHeld = -1; /* read only FS/ lockless */
6398 rc = SQLITE_OK;
6399 }
6400 }
drh715ff302008-12-03 22:32:44 +00006401 }
6402 if( rc==SQLITE_OK && lockPath ){
6403 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6404 }
6405
6406 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006407 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6408 if( pCtx->dbPath==NULL ){
6409 rc = SQLITE_NOMEM;
6410 }
6411 }
6412 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006413 /* all memory is allocated, proxys are created and assigned,
6414 ** switch the locking context and pMethod then return.
6415 */
drh715ff302008-12-03 22:32:44 +00006416 pCtx->oldLockingContext = pFile->lockingContext;
6417 pFile->lockingContext = pCtx;
6418 pCtx->pOldMethod = pFile->pMethod;
6419 pFile->pMethod = &proxyIoMethods;
6420 }else{
6421 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006422 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006423 sqlite3_free(pCtx->conchFile);
6424 }
drhd56b1212010-08-11 06:14:15 +00006425 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006426 sqlite3_free(pCtx->conchFilePath);
6427 sqlite3_free(pCtx);
6428 }
drh308c2a52010-05-14 11:30:18 +00006429 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6430 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006431 return rc;
6432}
6433
6434
6435/*
6436** This routine handles sqlite3_file_control() calls that are specific
6437** to proxy locking.
6438*/
6439static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6440 switch( op ){
6441 case SQLITE_GET_LOCKPROXYFILE: {
6442 unixFile *pFile = (unixFile*)id;
6443 if( pFile->pMethod == &proxyIoMethods ){
6444 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6445 proxyTakeConch(pFile);
6446 if( pCtx->lockProxyPath ){
6447 *(const char **)pArg = pCtx->lockProxyPath;
6448 }else{
6449 *(const char **)pArg = ":auto: (not held)";
6450 }
6451 } else {
6452 *(const char **)pArg = NULL;
6453 }
6454 return SQLITE_OK;
6455 }
6456 case SQLITE_SET_LOCKPROXYFILE: {
6457 unixFile *pFile = (unixFile*)id;
6458 int rc = SQLITE_OK;
6459 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6460 if( pArg==NULL || (const char *)pArg==0 ){
6461 if( isProxyStyle ){
6462 /* turn off proxy locking - not supported */
6463 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6464 }else{
6465 /* turn off proxy locking - already off - NOOP */
6466 rc = SQLITE_OK;
6467 }
6468 }else{
6469 const char *proxyPath = (const char *)pArg;
6470 if( isProxyStyle ){
6471 proxyLockingContext *pCtx =
6472 (proxyLockingContext*)pFile->lockingContext;
6473 if( !strcmp(pArg, ":auto:")
6474 || (pCtx->lockProxyPath &&
6475 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6476 ){
6477 rc = SQLITE_OK;
6478 }else{
6479 rc = switchLockProxyPath(pFile, proxyPath);
6480 }
6481 }else{
6482 /* turn on proxy file locking */
6483 rc = proxyTransformUnixFile(pFile, proxyPath);
6484 }
6485 }
6486 return rc;
6487 }
6488 default: {
6489 assert( 0 ); /* The call assures that only valid opcodes are sent */
6490 }
6491 }
6492 /*NOTREACHED*/
6493 return SQLITE_ERROR;
6494}
6495
6496/*
6497** Within this division (the proxying locking implementation) the procedures
6498** above this point are all utilities. The lock-related methods of the
6499** proxy-locking sqlite3_io_method object follow.
6500*/
6501
6502
6503/*
6504** This routine checks if there is a RESERVED lock held on the specified
6505** file by this or any other process. If such a lock is held, set *pResOut
6506** to a non-zero value otherwise *pResOut is set to zero. The return value
6507** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6508*/
6509static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6510 unixFile *pFile = (unixFile*)id;
6511 int rc = proxyTakeConch(pFile);
6512 if( rc==SQLITE_OK ){
6513 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006514 if( pCtx->conchHeld>0 ){
6515 unixFile *proxy = pCtx->lockProxy;
6516 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6517 }else{ /* conchHeld < 0 is lockless */
6518 pResOut=0;
6519 }
drh715ff302008-12-03 22:32:44 +00006520 }
6521 return rc;
6522}
6523
6524/*
drh308c2a52010-05-14 11:30:18 +00006525** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006526** of the following:
6527**
6528** (1) SHARED_LOCK
6529** (2) RESERVED_LOCK
6530** (3) PENDING_LOCK
6531** (4) EXCLUSIVE_LOCK
6532**
6533** Sometimes when requesting one lock state, additional lock states
6534** are inserted in between. The locking might fail on one of the later
6535** transitions leaving the lock state different from what it started but
6536** still short of its goal. The following chart shows the allowed
6537** transitions and the inserted intermediate states:
6538**
6539** UNLOCKED -> SHARED
6540** SHARED -> RESERVED
6541** SHARED -> (PENDING) -> EXCLUSIVE
6542** RESERVED -> (PENDING) -> EXCLUSIVE
6543** PENDING -> EXCLUSIVE
6544**
6545** This routine will only increase a lock. Use the sqlite3OsUnlock()
6546** routine to lower a locking level.
6547*/
drh308c2a52010-05-14 11:30:18 +00006548static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006549 unixFile *pFile = (unixFile*)id;
6550 int rc = proxyTakeConch(pFile);
6551 if( rc==SQLITE_OK ){
6552 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006553 if( pCtx->conchHeld>0 ){
6554 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006555 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6556 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006557 }else{
6558 /* conchHeld < 0 is lockless */
6559 }
drh715ff302008-12-03 22:32:44 +00006560 }
6561 return rc;
6562}
6563
6564
6565/*
drh308c2a52010-05-14 11:30:18 +00006566** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006567** must be either NO_LOCK or SHARED_LOCK.
6568**
6569** If the locking level of the file descriptor is already at or below
6570** the requested locking level, this routine is a no-op.
6571*/
drh308c2a52010-05-14 11:30:18 +00006572static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006573 unixFile *pFile = (unixFile*)id;
6574 int rc = proxyTakeConch(pFile);
6575 if( rc==SQLITE_OK ){
6576 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006577 if( pCtx->conchHeld>0 ){
6578 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006579 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6580 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006581 }else{
6582 /* conchHeld < 0 is lockless */
6583 }
drh715ff302008-12-03 22:32:44 +00006584 }
6585 return rc;
6586}
6587
6588/*
6589** Close a file that uses proxy locks.
6590*/
6591static int proxyClose(sqlite3_file *id) {
6592 if( id ){
6593 unixFile *pFile = (unixFile*)id;
6594 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6595 unixFile *lockProxy = pCtx->lockProxy;
6596 unixFile *conchFile = pCtx->conchFile;
6597 int rc = SQLITE_OK;
6598
6599 if( lockProxy ){
6600 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6601 if( rc ) return rc;
6602 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6603 if( rc ) return rc;
6604 sqlite3_free(lockProxy);
6605 pCtx->lockProxy = 0;
6606 }
6607 if( conchFile ){
6608 if( pCtx->conchHeld ){
6609 rc = proxyReleaseConch(pFile);
6610 if( rc ) return rc;
6611 }
6612 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6613 if( rc ) return rc;
6614 sqlite3_free(conchFile);
6615 }
drhd56b1212010-08-11 06:14:15 +00006616 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006617 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006618 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006619 /* restore the original locking context and pMethod then close it */
6620 pFile->lockingContext = pCtx->oldLockingContext;
6621 pFile->pMethod = pCtx->pOldMethod;
6622 sqlite3_free(pCtx);
6623 return pFile->pMethod->xClose(id);
6624 }
6625 return SQLITE_OK;
6626}
6627
6628
6629
drhd2cb50b2009-01-09 21:41:17 +00006630#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006631/*
6632** The proxy locking style is intended for use with AFP filesystems.
6633** And since AFP is only supported on MacOSX, the proxy locking is also
6634** restricted to MacOSX.
6635**
6636**
6637******************* End of the proxy lock implementation **********************
6638******************************************************************************/
6639
drh734c9862008-11-28 15:37:20 +00006640/*
danielk1977e339d652008-06-28 11:23:00 +00006641** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006642**
6643** This routine registers all VFS implementations for unix-like operating
6644** systems. This routine, and the sqlite3_os_end() routine that follows,
6645** should be the only routines in this file that are visible from other
6646** files.
drh6b9d6dd2008-12-03 19:34:47 +00006647**
6648** This routine is called once during SQLite initialization and by a
6649** single thread. The memory allocation and mutex subsystems have not
6650** necessarily been initialized when this routine is called, and so they
6651** should not be used.
drh153c62c2007-08-24 03:51:33 +00006652*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006653int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006654 /*
6655 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006656 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6657 ** to the "finder" function. (pAppData is a pointer to a pointer because
6658 ** silly C90 rules prohibit a void* from being cast to a function pointer
6659 ** and so we have to go through the intermediate pointer to avoid problems
6660 ** when compiling with -pedantic-errors on GCC.)
6661 **
6662 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006663 ** finder-function. The finder-function returns a pointer to the
6664 ** sqlite_io_methods object that implements the desired locking
6665 ** behaviors. See the division above that contains the IOMETHODS
6666 ** macro for addition information on finder-functions.
6667 **
6668 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6669 ** object. But the "autolockIoFinder" available on MacOSX does a little
6670 ** more than that; it looks at the filesystem type that hosts the
6671 ** database file and tries to choose an locking method appropriate for
6672 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006673 */
drh7708e972008-11-29 00:56:52 +00006674 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006675 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006676 sizeof(unixFile), /* szOsFile */ \
6677 MAX_PATHNAME, /* mxPathname */ \
6678 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006679 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006680 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006681 unixOpen, /* xOpen */ \
6682 unixDelete, /* xDelete */ \
6683 unixAccess, /* xAccess */ \
6684 unixFullPathname, /* xFullPathname */ \
6685 unixDlOpen, /* xDlOpen */ \
6686 unixDlError, /* xDlError */ \
6687 unixDlSym, /* xDlSym */ \
6688 unixDlClose, /* xDlClose */ \
6689 unixRandomness, /* xRandomness */ \
6690 unixSleep, /* xSleep */ \
6691 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006692 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006693 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006694 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006695 unixGetSystemCall, /* xGetSystemCall */ \
6696 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006697 }
6698
drh6b9d6dd2008-12-03 19:34:47 +00006699 /*
6700 ** All default VFSes for unix are contained in the following array.
6701 **
6702 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6703 ** by the SQLite core when the VFS is registered. So the following
6704 ** array cannot be const.
6705 */
danielk1977e339d652008-06-28 11:23:00 +00006706 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006707#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006708 UNIXVFS("unix", autolockIoFinder ),
6709#else
6710 UNIXVFS("unix", posixIoFinder ),
6711#endif
6712 UNIXVFS("unix-none", nolockIoFinder ),
6713 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006714 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006715#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006716 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006717#endif
6718#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006719 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006720#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006721 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006722#endif
chw78a13182009-04-07 05:35:03 +00006723#endif
drhd2cb50b2009-01-09 21:41:17 +00006724#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006725 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006726 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006727 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006728#endif
drh153c62c2007-08-24 03:51:33 +00006729 };
drh6b9d6dd2008-12-03 19:34:47 +00006730 unsigned int i; /* Loop counter */
6731
drh2aa5a002011-04-13 13:42:25 +00006732 /* Double-check that the aSyscall[] array has been constructed
6733 ** correctly. See ticket [bb3a86e890c8e96ab] */
6734 assert( ArraySize(aSyscall)==16 );
6735
drh6b9d6dd2008-12-03 19:34:47 +00006736 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006737 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006738 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006739 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006740 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006741}
danielk1977e339d652008-06-28 11:23:00 +00006742
6743/*
drh6b9d6dd2008-12-03 19:34:47 +00006744** Shutdown the operating system interface.
6745**
6746** Some operating systems might need to do some cleanup in this routine,
6747** to release dynamically allocated objects. But not on unix.
6748** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006749*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006750int sqlite3_os_end(void){
6751 return SQLITE_OK;
6752}
drhdce8bdb2007-08-16 13:01:44 +00006753
danielk197729bafea2008-06-26 10:41:19 +00006754#endif /* SQLITE_OS_UNIX */