blob: b2956c1647e8aa163136514f6a6653a022b7bbbd [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){
3398 if( pFile->szChunk ){
3399 i64 nSize; /* Required file size */
3400 struct stat buf; /* Used to hold return values of fstat() */
3401
drh99ab3b12011-03-02 15:09:07 +00003402 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003403
3404 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3405 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003406
dan502019c2010-07-28 14:26:17 +00003407#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003408 /* The code below is handling the return value of osFallocate()
3409 ** correctly. posix_fallocate() is defined to "returns zero on success,
3410 ** or an error number on failure". See the manpage for details. */
3411 int err;
drhff812312011-02-23 13:33:46 +00003412 do{
dan661d71a2011-03-30 19:08:03 +00003413 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3414 }while( err==EINTR );
3415 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003416#else
3417 /* If the OS does not have posix_fallocate(), fake it. First use
3418 ** ftruncate() to set the file size, then write a single byte to
3419 ** the last byte in each block within the extended region. This
3420 ** is the same technique used by glibc to implement posix_fallocate()
3421 ** on systems that do not have a real fallocate() system call.
3422 */
3423 int nBlk = buf.st_blksize; /* File-system block size */
3424 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003425
drhff812312011-02-23 13:33:46 +00003426 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003427 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003428 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003429 }
3430 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003431 while( iWrite<nSize ){
3432 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3433 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003434 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003435 }
dan502019c2010-07-28 14:26:17 +00003436#endif
3437 }
3438 }
3439
3440 return SQLITE_OK;
3441}
danielk1977ad94b582007-08-20 06:44:22 +00003442
danielk1977e3026632004-06-22 11:29:02 +00003443/*
drh9e33c2c2007-08-31 18:34:59 +00003444** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003445*/
drhcc6bb3e2007-08-31 16:11:35 +00003446static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003447 switch( op ){
3448 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003449 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003450 return SQLITE_OK;
3451 }
drh7708e972008-11-29 00:56:52 +00003452 case SQLITE_LAST_ERRNO: {
3453 *(int*)pArg = ((unixFile*)id)->lastErrno;
3454 return SQLITE_OK;
3455 }
dan6e09d692010-07-27 18:34:15 +00003456 case SQLITE_FCNTL_CHUNK_SIZE: {
3457 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003458 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003459 }
drh9ff27ec2010-05-19 19:26:05 +00003460 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003461 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003462 }
drh8f941bc2009-01-14 23:03:40 +00003463#ifndef NDEBUG
3464 /* The pager calls this method to signal that it has done
3465 ** a rollback and that the database is therefore unchanged and
3466 ** it hence it is OK for the transaction change counter to be
3467 ** unchanged.
3468 */
3469 case SQLITE_FCNTL_DB_UNCHANGED: {
3470 ((unixFile*)id)->dbUpdate = 0;
3471 return SQLITE_OK;
3472 }
3473#endif
drhd2cb50b2009-01-09 21:41:17 +00003474#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003475 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003476 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003477 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003478 }
drhd2cb50b2009-01-09 21:41:17 +00003479#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003480 case SQLITE_FCNTL_SYNC_OMITTED: {
3481 return SQLITE_OK; /* A no-op */
3482 }
drh9e33c2c2007-08-31 18:34:59 +00003483 }
drh0b52b7d2011-01-26 19:46:22 +00003484 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003485}
3486
3487/*
danielk1977a3d4c882007-03-23 10:08:38 +00003488** Return the sector size in bytes of the underlying block device for
3489** the specified file. This is almost always 512 bytes, but may be
3490** larger for some devices.
3491**
3492** SQLite code assumes this function cannot fail. It also assumes that
3493** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003494** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003495** same for both.
3496*/
danielk1977397d65f2008-11-19 11:35:39 +00003497static int unixSectorSize(sqlite3_file *NotUsed){
3498 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003499 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003500}
3501
danielk197790949c22007-08-17 16:50:38 +00003502/*
danielk1977397d65f2008-11-19 11:35:39 +00003503** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003504*/
danielk1977397d65f2008-11-19 11:35:39 +00003505static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3506 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003507 return 0;
3508}
3509
drhd9e5c4f2010-05-12 18:01:39 +00003510#ifndef SQLITE_OMIT_WAL
3511
3512
3513/*
drhd91c68f2010-05-14 14:52:25 +00003514** Object used to represent an shared memory buffer.
3515**
3516** When multiple threads all reference the same wal-index, each thread
3517** has its own unixShm object, but they all point to a single instance
3518** of this unixShmNode object. In other words, each wal-index is opened
3519** only once per process.
3520**
3521** Each unixShmNode object is connected to a single unixInodeInfo object.
3522** We could coalesce this object into unixInodeInfo, but that would mean
3523** every open file that does not use shared memory (in other words, most
3524** open files) would have to carry around this extra information. So
3525** the unixInodeInfo object contains a pointer to this unixShmNode object
3526** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003527**
3528** unixMutexHeld() must be true when creating or destroying
3529** this object or while reading or writing the following fields:
3530**
3531** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003532**
3533** The following fields are read-only after the object is created:
3534**
3535** fid
3536** zFilename
3537**
drhd91c68f2010-05-14 14:52:25 +00003538** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003539** unixMutexHeld() is true when reading or writing any other field
3540** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003541*/
drhd91c68f2010-05-14 14:52:25 +00003542struct unixShmNode {
3543 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003544 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003545 char *zFilename; /* Name of the mmapped file */
3546 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003547 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003548 u16 nRegion; /* Size of array apRegion */
3549 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003550 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003551 int nRef; /* Number of unixShm objects pointing to this */
3552 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003553#ifdef SQLITE_DEBUG
3554 u8 exclMask; /* Mask of exclusive locks held */
3555 u8 sharedMask; /* Mask of shared locks held */
3556 u8 nextShmId; /* Next available unixShm.id value */
3557#endif
3558};
3559
3560/*
drhd9e5c4f2010-05-12 18:01:39 +00003561** Structure used internally by this VFS to record the state of an
3562** open shared memory connection.
3563**
drhd91c68f2010-05-14 14:52:25 +00003564** The following fields are initialized when this object is created and
3565** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003566**
drhd91c68f2010-05-14 14:52:25 +00003567** unixShm.pFile
3568** unixShm.id
3569**
3570** All other fields are read/write. The unixShm.pFile->mutex must be held
3571** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003572*/
3573struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003574 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3575 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003576 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003577 u16 sharedMask; /* Mask of shared locks held */
3578 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003579#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003580 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003581#endif
3582};
3583
3584/*
drhd9e5c4f2010-05-12 18:01:39 +00003585** Constants used for locking
3586*/
drhbd9676c2010-06-23 17:58:38 +00003587#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003588#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003589
drhd9e5c4f2010-05-12 18:01:39 +00003590/*
drh73b64e42010-05-30 19:55:15 +00003591** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003592**
3593** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3594** otherwise.
3595*/
3596static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003597 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3598 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003599 int ofst, /* First byte of the locking range */
3600 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003601){
3602 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003603 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003604
drhd91c68f2010-05-14 14:52:25 +00003605 /* Access to the unixShmNode object is serialized by the caller */
3606 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003607
drh73b64e42010-05-30 19:55:15 +00003608 /* Shared locks never span more than one byte */
3609 assert( n==1 || lockType!=F_RDLCK );
3610
3611 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003612 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003613
drh3cb93392011-03-12 18:10:44 +00003614 if( pShmNode->h>=0 ){
3615 /* Initialize the locking parameters */
3616 memset(&f, 0, sizeof(f));
3617 f.l_type = lockType;
3618 f.l_whence = SEEK_SET;
3619 f.l_start = ofst;
3620 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003621
drh3cb93392011-03-12 18:10:44 +00003622 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3623 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3624 }
drhd9e5c4f2010-05-12 18:01:39 +00003625
3626 /* Update the global lock state and do debug tracing */
3627#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003628 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003629 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003630 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003631 if( rc==SQLITE_OK ){
3632 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003633 OSTRACE(("unlock %d ok", ofst));
3634 pShmNode->exclMask &= ~mask;
3635 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003636 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003637 OSTRACE(("read-lock %d ok", ofst));
3638 pShmNode->exclMask &= ~mask;
3639 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003640 }else{
3641 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003642 OSTRACE(("write-lock %d ok", ofst));
3643 pShmNode->exclMask |= mask;
3644 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003645 }
3646 }else{
3647 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003648 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003649 }else if( lockType==F_RDLCK ){
3650 OSTRACE(("read-lock failed"));
3651 }else{
3652 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003653 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003654 }
3655 }
drh20e1f082010-05-31 16:10:12 +00003656 OSTRACE((" - afterwards %03x,%03x\n",
3657 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003658 }
drhd9e5c4f2010-05-12 18:01:39 +00003659#endif
3660
3661 return rc;
3662}
3663
drhd9e5c4f2010-05-12 18:01:39 +00003664
3665/*
drhd91c68f2010-05-14 14:52:25 +00003666** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003667**
3668** This is not a VFS shared-memory method; it is a utility function called
3669** by VFS shared-memory methods.
3670*/
drhd91c68f2010-05-14 14:52:25 +00003671static void unixShmPurge(unixFile *pFd){
3672 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003673 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003674 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003675 int i;
drhd91c68f2010-05-14 14:52:25 +00003676 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003677 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003678 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003679 if( p->h>=0 ){
3680 munmap(p->apRegion[i], p->szRegion);
3681 }else{
3682 sqlite3_free(p->apRegion[i]);
3683 }
dan13a3cb82010-06-11 19:04:21 +00003684 }
dan18801912010-06-14 14:07:50 +00003685 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003686 if( p->h>=0 ){
3687 robust_close(pFd, p->h, __LINE__);
3688 p->h = -1;
3689 }
drhd91c68f2010-05-14 14:52:25 +00003690 p->pInode->pShmNode = 0;
3691 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003692 }
3693}
3694
3695/*
danda9fe0c2010-07-13 18:44:03 +00003696** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003697** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003698**
drh7234c6d2010-06-19 15:10:09 +00003699** The file used to implement shared-memory is in the same directory
3700** as the open database file and has the same name as the open database
3701** file with the "-shm" suffix added. For example, if the database file
3702** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003703** for shared memory will be called "/home/user1/config.db-shm".
3704**
3705** Another approach to is to use files in /dev/shm or /dev/tmp or an
3706** some other tmpfs mount. But if a file in a different directory
3707** from the database file is used, then differing access permissions
3708** or a chroot() might cause two different processes on the same
3709** database to end up using different files for shared memory -
3710** meaning that their memory would not really be shared - resulting
3711** in database corruption. Nevertheless, this tmpfs file usage
3712** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3713** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3714** option results in an incompatible build of SQLite; builds of SQLite
3715** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3716** same database file at the same time, database corruption will likely
3717** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3718** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003719**
3720** When opening a new shared-memory file, if no other instances of that
3721** file are currently open, in this process or in other processes, then
3722** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003723**
3724** If the original database file (pDbFd) is using the "unix-excl" VFS
3725** that means that an exclusive lock is held on the database file and
3726** that no other processes are able to read or write the database. In
3727** that case, we do not really need shared memory. No shared memory
3728** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003729*/
danda9fe0c2010-07-13 18:44:03 +00003730static int unixOpenSharedMemory(unixFile *pDbFd){
3731 struct unixShm *p = 0; /* The connection to be opened */
3732 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3733 int rc; /* Result code */
3734 unixInodeInfo *pInode; /* The inode of fd */
3735 char *zShmFilename; /* Name of the file used for SHM */
3736 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003737
danda9fe0c2010-07-13 18:44:03 +00003738 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003739 p = sqlite3_malloc( sizeof(*p) );
3740 if( p==0 ) return SQLITE_NOMEM;
3741 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003742 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003743
danda9fe0c2010-07-13 18:44:03 +00003744 /* Check to see if a unixShmNode object already exists. Reuse an existing
3745 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003746 */
3747 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003748 pInode = pDbFd->pInode;
3749 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003750 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003751 struct stat sStat; /* fstat() info for database file */
3752
3753 /* Call fstat() to figure out the permissions on the database file. If
3754 ** a new *-shm file is created, an attempt will be made to create it
3755 ** with the same permissions. The actual permissions the file is created
3756 ** with are subject to the current umask setting.
3757 */
drh3cb93392011-03-12 18:10:44 +00003758 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003759 rc = SQLITE_IOERR_FSTAT;
3760 goto shm_open_err;
3761 }
3762
drha4ced192010-07-15 18:32:40 +00003763#ifdef SQLITE_SHM_DIRECTORY
3764 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3765#else
drh7234c6d2010-06-19 15:10:09 +00003766 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003767#endif
drh7234c6d2010-06-19 15:10:09 +00003768 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003769 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003770 rc = SQLITE_NOMEM;
3771 goto shm_open_err;
3772 }
drhd91c68f2010-05-14 14:52:25 +00003773 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003774 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003775#ifdef SQLITE_SHM_DIRECTORY
3776 sqlite3_snprintf(nShmFilename, zShmFilename,
3777 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3778 (u32)sStat.st_ino, (u32)sStat.st_dev);
3779#else
drh7234c6d2010-06-19 15:10:09 +00003780 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003781 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003782#endif
drhd91c68f2010-05-14 14:52:25 +00003783 pShmNode->h = -1;
3784 pDbFd->pInode->pShmNode = pShmNode;
3785 pShmNode->pInode = pDbFd->pInode;
3786 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3787 if( pShmNode->mutex==0 ){
3788 rc = SQLITE_NOMEM;
3789 goto shm_open_err;
3790 }
drhd9e5c4f2010-05-12 18:01:39 +00003791
drh3cb93392011-03-12 18:10:44 +00003792 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003793 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3794 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003795 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003796 const char *zRO;
3797 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003798 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003799 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3800 (sStat.st_mode & 0777));
3801 pShmNode->isReadonly = 1;
3802 }
3803 if( pShmNode->h<0 ){
3804 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3805 goto shm_open_err;
3806 }
drhd9e5c4f2010-05-12 18:01:39 +00003807 }
drh3cb93392011-03-12 18:10:44 +00003808
3809 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003810 ** If not, truncate the file to zero length.
3811 */
3812 rc = SQLITE_OK;
3813 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3814 if( robust_ftruncate(pShmNode->h, 0) ){
3815 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003816 }
3817 }
drh66dfec8b2011-06-01 20:01:49 +00003818 if( rc==SQLITE_OK ){
3819 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3820 }
3821 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003822 }
drhd9e5c4f2010-05-12 18:01:39 +00003823 }
3824
drhd91c68f2010-05-14 14:52:25 +00003825 /* Make the new connection a child of the unixShmNode */
3826 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003827#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003828 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003829#endif
drhd91c68f2010-05-14 14:52:25 +00003830 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003831 pDbFd->pShm = p;
3832 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003833
3834 /* The reference count on pShmNode has already been incremented under
3835 ** the cover of the unixEnterMutex() mutex and the pointer from the
3836 ** new (struct unixShm) object to the pShmNode has been set. All that is
3837 ** left to do is to link the new object into the linked list starting
3838 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3839 ** mutex.
3840 */
3841 sqlite3_mutex_enter(pShmNode->mutex);
3842 p->pNext = pShmNode->pFirst;
3843 pShmNode->pFirst = p;
3844 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003845 return SQLITE_OK;
3846
3847 /* Jump here on any error */
3848shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003849 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003850 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003851 unixLeaveMutex();
3852 return rc;
3853}
3854
3855/*
danda9fe0c2010-07-13 18:44:03 +00003856** This function is called to obtain a pointer to region iRegion of the
3857** shared-memory associated with the database file fd. Shared-memory regions
3858** are numbered starting from zero. Each shared-memory region is szRegion
3859** bytes in size.
3860**
3861** If an error occurs, an error code is returned and *pp is set to NULL.
3862**
3863** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3864** region has not been allocated (by any client, including one running in a
3865** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3866** bExtend is non-zero and the requested shared-memory region has not yet
3867** been allocated, it is allocated by this function.
3868**
3869** If the shared-memory region has already been allocated or is allocated by
3870** this call as described above, then it is mapped into this processes
3871** address space (if it is not already), *pp is set to point to the mapped
3872** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003873*/
danda9fe0c2010-07-13 18:44:03 +00003874static int unixShmMap(
3875 sqlite3_file *fd, /* Handle open on database file */
3876 int iRegion, /* Region to retrieve */
3877 int szRegion, /* Size of regions */
3878 int bExtend, /* True to extend file if necessary */
3879 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003880){
danda9fe0c2010-07-13 18:44:03 +00003881 unixFile *pDbFd = (unixFile*)fd;
3882 unixShm *p;
3883 unixShmNode *pShmNode;
3884 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003885
danda9fe0c2010-07-13 18:44:03 +00003886 /* If the shared-memory file has not yet been opened, open it now. */
3887 if( pDbFd->pShm==0 ){
3888 rc = unixOpenSharedMemory(pDbFd);
3889 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003890 }
drhd9e5c4f2010-05-12 18:01:39 +00003891
danda9fe0c2010-07-13 18:44:03 +00003892 p = pDbFd->pShm;
3893 pShmNode = p->pShmNode;
3894 sqlite3_mutex_enter(pShmNode->mutex);
3895 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003896 assert( pShmNode->pInode==pDbFd->pInode );
3897 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3898 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003899
3900 if( pShmNode->nRegion<=iRegion ){
3901 char **apNew; /* New apRegion[] array */
3902 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3903 struct stat sStat; /* Used by fstat() */
3904
3905 pShmNode->szRegion = szRegion;
3906
drh3cb93392011-03-12 18:10:44 +00003907 if( pShmNode->h>=0 ){
3908 /* The requested region is not mapped into this processes address space.
3909 ** Check to see if it has been allocated (i.e. if the wal-index file is
3910 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003911 */
drh3cb93392011-03-12 18:10:44 +00003912 if( osFstat(pShmNode->h, &sStat) ){
3913 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003914 goto shmpage_out;
3915 }
drh3cb93392011-03-12 18:10:44 +00003916
3917 if( sStat.st_size<nByte ){
3918 /* The requested memory region does not exist. If bExtend is set to
3919 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3920 **
3921 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3922 ** the requested memory region.
3923 */
3924 if( !bExtend ) goto shmpage_out;
3925 if( robust_ftruncate(pShmNode->h, nByte) ){
3926 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3927 pShmNode->zFilename);
3928 goto shmpage_out;
3929 }
3930 }
danda9fe0c2010-07-13 18:44:03 +00003931 }
3932
3933 /* Map the requested memory region into this processes address space. */
3934 apNew = (char **)sqlite3_realloc(
3935 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3936 );
3937 if( !apNew ){
3938 rc = SQLITE_IOERR_NOMEM;
3939 goto shmpage_out;
3940 }
3941 pShmNode->apRegion = apNew;
3942 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003943 void *pMem;
3944 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00003945 pMem = mmap(0, szRegion,
3946 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00003947 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3948 );
3949 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00003950 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00003951 goto shmpage_out;
3952 }
3953 }else{
3954 pMem = sqlite3_malloc(szRegion);
3955 if( pMem==0 ){
3956 rc = SQLITE_NOMEM;
3957 goto shmpage_out;
3958 }
3959 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003960 }
3961 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3962 pShmNode->nRegion++;
3963 }
3964 }
3965
3966shmpage_out:
3967 if( pShmNode->nRegion>iRegion ){
3968 *pp = pShmNode->apRegion[iRegion];
3969 }else{
3970 *pp = 0;
3971 }
drh66dfec8b2011-06-01 20:01:49 +00003972 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00003973 sqlite3_mutex_leave(pShmNode->mutex);
3974 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003975}
3976
3977/*
drhd9e5c4f2010-05-12 18:01:39 +00003978** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003979**
3980** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3981** different here than in posix. In xShmLock(), one can go from unlocked
3982** to shared and back or from unlocked to exclusive and back. But one may
3983** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003984*/
3985static int unixShmLock(
3986 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003987 int ofst, /* First lock to acquire or release */
3988 int n, /* Number of locks to acquire or release */
3989 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003990){
drh73b64e42010-05-30 19:55:15 +00003991 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3992 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3993 unixShm *pX; /* For looping over all siblings */
3994 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3995 int rc = SQLITE_OK; /* Result code */
3996 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003997
drhd91c68f2010-05-14 14:52:25 +00003998 assert( pShmNode==pDbFd->pInode->pShmNode );
3999 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004000 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004001 assert( n>=1 );
4002 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4003 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4004 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4005 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4006 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004007 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4008 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004009
drhc99597c2010-05-31 01:41:15 +00004010 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004011 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004012 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004013 if( flags & SQLITE_SHM_UNLOCK ){
4014 u16 allMask = 0; /* Mask of locks held by siblings */
4015
4016 /* See if any siblings hold this same lock */
4017 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4018 if( pX==p ) continue;
4019 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4020 allMask |= pX->sharedMask;
4021 }
4022
4023 /* Unlock the system-level locks */
4024 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004025 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004026 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004027 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004028 }
drh73b64e42010-05-30 19:55:15 +00004029
4030 /* Undo the local locks */
4031 if( rc==SQLITE_OK ){
4032 p->exclMask &= ~mask;
4033 p->sharedMask &= ~mask;
4034 }
4035 }else if( flags & SQLITE_SHM_SHARED ){
4036 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4037
4038 /* Find out which shared locks are already held by sibling connections.
4039 ** If any sibling already holds an exclusive lock, go ahead and return
4040 ** SQLITE_BUSY.
4041 */
4042 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004043 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004044 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004045 break;
4046 }
4047 allShared |= pX->sharedMask;
4048 }
4049
4050 /* Get shared locks at the system level, if necessary */
4051 if( rc==SQLITE_OK ){
4052 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004053 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004054 }else{
drh73b64e42010-05-30 19:55:15 +00004055 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004056 }
drhd9e5c4f2010-05-12 18:01:39 +00004057 }
drh73b64e42010-05-30 19:55:15 +00004058
4059 /* Get the local shared locks */
4060 if( rc==SQLITE_OK ){
4061 p->sharedMask |= mask;
4062 }
4063 }else{
4064 /* Make sure no sibling connections hold locks that will block this
4065 ** lock. If any do, return SQLITE_BUSY right away.
4066 */
4067 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004068 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4069 rc = SQLITE_BUSY;
4070 break;
4071 }
4072 }
4073
4074 /* Get the exclusive locks at the system level. Then if successful
4075 ** also mark the local connection as being locked.
4076 */
4077 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004078 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004079 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004080 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004081 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004082 }
drhd9e5c4f2010-05-12 18:01:39 +00004083 }
4084 }
drhd91c68f2010-05-14 14:52:25 +00004085 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004086 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4087 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004088 return rc;
4089}
4090
drh286a2882010-05-20 23:51:06 +00004091/*
4092** Implement a memory barrier or memory fence on shared memory.
4093**
4094** All loads and stores begun before the barrier must complete before
4095** any load or store begun after the barrier.
4096*/
4097static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004098 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004099){
drhff828942010-06-26 21:34:06 +00004100 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004101 unixEnterMutex();
4102 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004103}
4104
dan18801912010-06-14 14:07:50 +00004105/*
danda9fe0c2010-07-13 18:44:03 +00004106** Close a connection to shared-memory. Delete the underlying
4107** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004108**
4109** If there is no shared memory associated with the connection then this
4110** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004111*/
danda9fe0c2010-07-13 18:44:03 +00004112static int unixShmUnmap(
4113 sqlite3_file *fd, /* The underlying database file */
4114 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004115){
danda9fe0c2010-07-13 18:44:03 +00004116 unixShm *p; /* The connection to be closed */
4117 unixShmNode *pShmNode; /* The underlying shared-memory file */
4118 unixShm **pp; /* For looping over sibling connections */
4119 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004120
danda9fe0c2010-07-13 18:44:03 +00004121 pDbFd = (unixFile*)fd;
4122 p = pDbFd->pShm;
4123 if( p==0 ) return SQLITE_OK;
4124 pShmNode = p->pShmNode;
4125
4126 assert( pShmNode==pDbFd->pInode->pShmNode );
4127 assert( pShmNode->pInode==pDbFd->pInode );
4128
4129 /* Remove connection p from the set of connections associated
4130 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004131 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004132 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4133 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004134
danda9fe0c2010-07-13 18:44:03 +00004135 /* Free the connection p */
4136 sqlite3_free(p);
4137 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004138 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004139
4140 /* If pShmNode->nRef has reached 0, then close the underlying
4141 ** shared-memory file, too */
4142 unixEnterMutex();
4143 assert( pShmNode->nRef>0 );
4144 pShmNode->nRef--;
4145 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004146 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004147 unixShmPurge(pDbFd);
4148 }
4149 unixLeaveMutex();
4150
4151 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004152}
drh286a2882010-05-20 23:51:06 +00004153
danda9fe0c2010-07-13 18:44:03 +00004154
drhd9e5c4f2010-05-12 18:01:39 +00004155#else
drh6b017cc2010-06-14 18:01:46 +00004156# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004157# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004158# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004159# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004160#endif /* #ifndef SQLITE_OMIT_WAL */
4161
drh734c9862008-11-28 15:37:20 +00004162/*
4163** Here ends the implementation of all sqlite3_file methods.
4164**
4165********************** End sqlite3_file Methods *******************************
4166******************************************************************************/
4167
4168/*
drh6b9d6dd2008-12-03 19:34:47 +00004169** This division contains definitions of sqlite3_io_methods objects that
4170** implement various file locking strategies. It also contains definitions
4171** of "finder" functions. A finder-function is used to locate the appropriate
4172** sqlite3_io_methods object for a particular database file. The pAppData
4173** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4174** the correct finder-function for that VFS.
4175**
4176** Most finder functions return a pointer to a fixed sqlite3_io_methods
4177** object. The only interesting finder-function is autolockIoFinder, which
4178** looks at the filesystem type and tries to guess the best locking
4179** strategy from that.
4180**
drh1875f7a2008-12-08 18:19:17 +00004181** For finder-funtion F, two objects are created:
4182**
4183** (1) The real finder-function named "FImpt()".
4184**
dane946c392009-08-22 11:39:46 +00004185** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004186**
4187**
4188** A pointer to the F pointer is used as the pAppData value for VFS
4189** objects. We have to do this instead of letting pAppData point
4190** directly at the finder-function since C90 rules prevent a void*
4191** from be cast into a function pointer.
4192**
drh6b9d6dd2008-12-03 19:34:47 +00004193**
drh7708e972008-11-29 00:56:52 +00004194** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004195**
drh7708e972008-11-29 00:56:52 +00004196** * A constant sqlite3_io_methods object call METHOD that has locking
4197** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4198**
4199** * An I/O method finder function called FINDER that returns a pointer
4200** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004201*/
drhd9e5c4f2010-05-12 18:01:39 +00004202#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004203static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004204 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004205 CLOSE, /* xClose */ \
4206 unixRead, /* xRead */ \
4207 unixWrite, /* xWrite */ \
4208 unixTruncate, /* xTruncate */ \
4209 unixSync, /* xSync */ \
4210 unixFileSize, /* xFileSize */ \
4211 LOCK, /* xLock */ \
4212 UNLOCK, /* xUnlock */ \
4213 CKLOCK, /* xCheckReservedLock */ \
4214 unixFileControl, /* xFileControl */ \
4215 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004216 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004217 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004218 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004219 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004220 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004221}; \
drh0c2694b2009-09-03 16:23:44 +00004222static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4223 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004224 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004225} \
drh0c2694b2009-09-03 16:23:44 +00004226static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004227 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004228
4229/*
4230** Here are all of the sqlite3_io_methods objects for each of the
4231** locking strategies. Functions that return pointers to these methods
4232** are also created.
4233*/
4234IOMETHODS(
4235 posixIoFinder, /* Finder function name */
4236 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004237 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004238 unixClose, /* xClose method */
4239 unixLock, /* xLock method */
4240 unixUnlock, /* xUnlock method */
4241 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004242)
drh7708e972008-11-29 00:56:52 +00004243IOMETHODS(
4244 nolockIoFinder, /* Finder function name */
4245 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004246 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004247 nolockClose, /* xClose method */
4248 nolockLock, /* xLock method */
4249 nolockUnlock, /* xUnlock method */
4250 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004251)
drh7708e972008-11-29 00:56:52 +00004252IOMETHODS(
4253 dotlockIoFinder, /* Finder function name */
4254 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004255 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004256 dotlockClose, /* xClose method */
4257 dotlockLock, /* xLock method */
4258 dotlockUnlock, /* xUnlock method */
4259 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004260)
drh7708e972008-11-29 00:56:52 +00004261
chw78a13182009-04-07 05:35:03 +00004262#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004263IOMETHODS(
4264 flockIoFinder, /* Finder function name */
4265 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004266 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004267 flockClose, /* xClose method */
4268 flockLock, /* xLock method */
4269 flockUnlock, /* xUnlock method */
4270 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004271)
drh7708e972008-11-29 00:56:52 +00004272#endif
4273
drh6c7d5c52008-11-21 20:32:33 +00004274#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004275IOMETHODS(
4276 semIoFinder, /* Finder function name */
4277 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004278 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004279 semClose, /* xClose method */
4280 semLock, /* xLock method */
4281 semUnlock, /* xUnlock method */
4282 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004283)
aswiftaebf4132008-11-21 00:10:35 +00004284#endif
drh7708e972008-11-29 00:56:52 +00004285
drhd2cb50b2009-01-09 21:41:17 +00004286#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004287IOMETHODS(
4288 afpIoFinder, /* Finder function name */
4289 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004290 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004291 afpClose, /* xClose method */
4292 afpLock, /* xLock method */
4293 afpUnlock, /* xUnlock method */
4294 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004295)
drh715ff302008-12-03 22:32:44 +00004296#endif
4297
4298/*
4299** The proxy locking method is a "super-method" in the sense that it
4300** opens secondary file descriptors for the conch and lock files and
4301** it uses proxy, dot-file, AFP, and flock() locking methods on those
4302** secondary files. For this reason, the division that implements
4303** proxy locking is located much further down in the file. But we need
4304** to go ahead and define the sqlite3_io_methods and finder function
4305** for proxy locking here. So we forward declare the I/O methods.
4306*/
drhd2cb50b2009-01-09 21:41:17 +00004307#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004308static int proxyClose(sqlite3_file*);
4309static int proxyLock(sqlite3_file*, int);
4310static int proxyUnlock(sqlite3_file*, int);
4311static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004312IOMETHODS(
4313 proxyIoFinder, /* Finder function name */
4314 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004315 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004316 proxyClose, /* xClose method */
4317 proxyLock, /* xLock method */
4318 proxyUnlock, /* xUnlock method */
4319 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004320)
aswiftaebf4132008-11-21 00:10:35 +00004321#endif
drh7708e972008-11-29 00:56:52 +00004322
drh7ed97b92010-01-20 13:07:21 +00004323/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4324#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4325IOMETHODS(
4326 nfsIoFinder, /* Finder function name */
4327 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004328 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004329 unixClose, /* xClose method */
4330 unixLock, /* xLock method */
4331 nfsUnlock, /* xUnlock method */
4332 unixCheckReservedLock /* xCheckReservedLock method */
4333)
4334#endif
drh7708e972008-11-29 00:56:52 +00004335
drhd2cb50b2009-01-09 21:41:17 +00004336#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004337/*
drh6b9d6dd2008-12-03 19:34:47 +00004338** This "finder" function attempts to determine the best locking strategy
4339** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004340** object that implements that strategy.
4341**
4342** This is for MacOSX only.
4343*/
drh1875f7a2008-12-08 18:19:17 +00004344static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004345 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004346 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004347){
4348 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004349 const char *zFilesystem; /* Filesystem type name */
4350 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004351 } aMap[] = {
4352 { "hfs", &posixIoMethods },
4353 { "ufs", &posixIoMethods },
4354 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004355 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004356 { "webdav", &nolockIoMethods },
4357 { 0, 0 }
4358 };
4359 int i;
4360 struct statfs fsInfo;
4361 struct flock lockInfo;
4362
4363 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004364 /* If filePath==NULL that means we are dealing with a transient file
4365 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004366 return &nolockIoMethods;
4367 }
4368 if( statfs(filePath, &fsInfo) != -1 ){
4369 if( fsInfo.f_flags & MNT_RDONLY ){
4370 return &nolockIoMethods;
4371 }
4372 for(i=0; aMap[i].zFilesystem; i++){
4373 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4374 return aMap[i].pMethods;
4375 }
4376 }
4377 }
4378
4379 /* Default case. Handles, amongst others, "nfs".
4380 ** Test byte-range lock using fcntl(). If the call succeeds,
4381 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004382 */
drh7708e972008-11-29 00:56:52 +00004383 lockInfo.l_len = 1;
4384 lockInfo.l_start = 0;
4385 lockInfo.l_whence = SEEK_SET;
4386 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004387 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004388 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4389 return &nfsIoMethods;
4390 } else {
4391 return &posixIoMethods;
4392 }
drh7708e972008-11-29 00:56:52 +00004393 }else{
4394 return &dotlockIoMethods;
4395 }
4396}
drh0c2694b2009-09-03 16:23:44 +00004397static const sqlite3_io_methods
4398 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004399
drhd2cb50b2009-01-09 21:41:17 +00004400#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004401
chw78a13182009-04-07 05:35:03 +00004402#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4403/*
4404** This "finder" function attempts to determine the best locking strategy
4405** for the database file "filePath". It then returns the sqlite3_io_methods
4406** object that implements that strategy.
4407**
4408** This is for VXWorks only.
4409*/
4410static const sqlite3_io_methods *autolockIoFinderImpl(
4411 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004412 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004413){
4414 struct flock lockInfo;
4415
4416 if( !filePath ){
4417 /* If filePath==NULL that means we are dealing with a transient file
4418 ** that does not need to be locked. */
4419 return &nolockIoMethods;
4420 }
4421
4422 /* Test if fcntl() is supported and use POSIX style locks.
4423 ** Otherwise fall back to the named semaphore method.
4424 */
4425 lockInfo.l_len = 1;
4426 lockInfo.l_start = 0;
4427 lockInfo.l_whence = SEEK_SET;
4428 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004429 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004430 return &posixIoMethods;
4431 }else{
4432 return &semIoMethods;
4433 }
4434}
drh0c2694b2009-09-03 16:23:44 +00004435static const sqlite3_io_methods
4436 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004437
4438#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4439
drh7708e972008-11-29 00:56:52 +00004440/*
4441** An abstract type for a pointer to a IO method finder function:
4442*/
drh0c2694b2009-09-03 16:23:44 +00004443typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004444
aswiftaebf4132008-11-21 00:10:35 +00004445
drh734c9862008-11-28 15:37:20 +00004446/****************************************************************************
4447**************************** sqlite3_vfs methods ****************************
4448**
4449** This division contains the implementation of methods on the
4450** sqlite3_vfs object.
4451*/
4452
danielk1977a3d4c882007-03-23 10:08:38 +00004453/*
danielk1977e339d652008-06-28 11:23:00 +00004454** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004455*/
4456static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004457 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004458 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004459 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004460 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004461 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004462 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004463 int isDelete, /* Delete on close if true */
4464 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004465){
drh7708e972008-11-29 00:56:52 +00004466 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004467 unixFile *pNew = (unixFile *)pId;
4468 int rc = SQLITE_OK;
4469
drh8af6c222010-05-14 12:43:01 +00004470 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004471
dane946c392009-08-22 11:39:46 +00004472 /* Parameter isDelete is only used on vxworks. Express this explicitly
4473 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004474 */
drh7708e972008-11-29 00:56:52 +00004475 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004476
dan00157392010-10-05 11:33:15 +00004477 /* Usually the path zFilename should not be a relative pathname. The
4478 ** exception is when opening the proxy "conch" file in builds that
4479 ** include the special Apple locking styles.
4480 */
dan00157392010-10-05 11:33:15 +00004481#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004482 assert( zFilename==0 || zFilename[0]=='/'
4483 || pVfs->pAppData==(void*)&autolockIoFinder );
4484#else
4485 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004486#endif
dan00157392010-10-05 11:33:15 +00004487
drh308c2a52010-05-14 11:30:18 +00004488 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004489 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004490 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004491 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004492 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4493 pNew->ctrlFlags = UNIXFILE_EXCL;
4494 }else{
4495 pNew->ctrlFlags = 0;
4496 }
drh77197112011-03-15 19:08:48 +00004497 if( isReadOnly ){
4498 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4499 }
drh339eb0b2008-03-07 15:34:11 +00004500
drh6c7d5c52008-11-21 20:32:33 +00004501#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004502 pNew->pId = vxworksFindFileId(zFilename);
4503 if( pNew->pId==0 ){
4504 noLock = 1;
4505 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004506 }
4507#endif
4508
drhda0e7682008-07-30 15:27:54 +00004509 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004510 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004511 }else{
drh0c2694b2009-09-03 16:23:44 +00004512 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004513#if SQLITE_ENABLE_LOCKING_STYLE
4514 /* Cache zFilename in the locking context (AFP and dotlock override) for
4515 ** proxyLock activation is possible (remote proxy is based on db name)
4516 ** zFilename remains valid until file is closed, to support */
4517 pNew->lockingContext = (void*)zFilename;
4518#endif
drhda0e7682008-07-30 15:27:54 +00004519 }
danielk1977e339d652008-06-28 11:23:00 +00004520
drh7ed97b92010-01-20 13:07:21 +00004521 if( pLockingStyle == &posixIoMethods
4522#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4523 || pLockingStyle == &nfsIoMethods
4524#endif
4525 ){
drh7708e972008-11-29 00:56:52 +00004526 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004527 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004528 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004529 /* If an error occured in findInodeInfo(), close the file descriptor
4530 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004531 ** in two scenarios:
4532 **
4533 ** (a) A call to fstat() failed.
4534 ** (b) A malloc failed.
4535 **
4536 ** Scenario (b) may only occur if the process is holding no other
4537 ** file descriptors open on the same file. If there were other file
4538 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004539 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004540 ** handle h - as it is guaranteed that no posix locks will be released
4541 ** by doing so.
4542 **
4543 ** If scenario (a) caused the error then things are not so safe. The
4544 ** implicit assumption here is that if fstat() fails, things are in
4545 ** such bad shape that dropping a lock or two doesn't matter much.
4546 */
drh0e9365c2011-03-02 02:08:13 +00004547 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004548 h = -1;
4549 }
drh7708e972008-11-29 00:56:52 +00004550 unixLeaveMutex();
4551 }
danielk1977e339d652008-06-28 11:23:00 +00004552
drhd2cb50b2009-01-09 21:41:17 +00004553#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004554 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004555 /* AFP locking uses the file path so it needs to be included in
4556 ** the afpLockingContext.
4557 */
4558 afpLockingContext *pCtx;
4559 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4560 if( pCtx==0 ){
4561 rc = SQLITE_NOMEM;
4562 }else{
4563 /* NB: zFilename exists and remains valid until the file is closed
4564 ** according to requirement F11141. So we do not need to make a
4565 ** copy of the filename. */
4566 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004567 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004568 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004569 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004570 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004571 if( rc!=SQLITE_OK ){
4572 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004573 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004574 h = -1;
4575 }
drh7708e972008-11-29 00:56:52 +00004576 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004577 }
drh7708e972008-11-29 00:56:52 +00004578 }
4579#endif
danielk1977e339d652008-06-28 11:23:00 +00004580
drh7708e972008-11-29 00:56:52 +00004581 else if( pLockingStyle == &dotlockIoMethods ){
4582 /* Dotfile locking uses the file path so it needs to be included in
4583 ** the dotlockLockingContext
4584 */
4585 char *zLockFile;
4586 int nFilename;
drhea678832008-12-10 19:26:22 +00004587 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004588 zLockFile = (char *)sqlite3_malloc(nFilename);
4589 if( zLockFile==0 ){
4590 rc = SQLITE_NOMEM;
4591 }else{
4592 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004593 }
drh7708e972008-11-29 00:56:52 +00004594 pNew->lockingContext = zLockFile;
4595 }
danielk1977e339d652008-06-28 11:23:00 +00004596
drh6c7d5c52008-11-21 20:32:33 +00004597#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004598 else if( pLockingStyle == &semIoMethods ){
4599 /* Named semaphore locking uses the file path so it needs to be
4600 ** included in the semLockingContext
4601 */
4602 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004603 rc = findInodeInfo(pNew, &pNew->pInode);
4604 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4605 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004606 int n;
drh2238dcc2009-08-27 17:56:20 +00004607 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004608 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004609 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004610 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004611 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4612 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004613 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004614 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004615 }
chw97185482008-11-17 08:05:31 +00004616 }
drh7708e972008-11-29 00:56:52 +00004617 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004618 }
drh7708e972008-11-29 00:56:52 +00004619#endif
aswift5b1a2562008-08-22 00:22:35 +00004620
4621 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004622#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004623 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004624 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004625 h = -1;
chw97185482008-11-17 08:05:31 +00004626 unlink(zFilename);
4627 isDelete = 0;
4628 }
4629 pNew->isDelete = isDelete;
4630#endif
danielk1977e339d652008-06-28 11:23:00 +00004631 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004632 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4633 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004634 }else{
drh7708e972008-11-29 00:56:52 +00004635 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004636 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004637 }
danielk1977e339d652008-06-28 11:23:00 +00004638 return rc;
drh054889e2005-11-30 03:20:31 +00004639}
drh9c06c952005-11-26 00:25:00 +00004640
danielk1977ad94b582007-08-20 06:44:22 +00004641/*
4642** Open a file descriptor to the directory containing file zFilename.
4643** If successful, *pFd is set to the opened file descriptor and
4644** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4645** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4646** value.
4647**
4648** If SQLITE_OK is returned, the caller is responsible for closing
4649** the file descriptor *pFd using close().
4650*/
danielk1977fee2d252007-08-18 10:59:19 +00004651static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004652 int ii;
drh777b17a2007-09-20 10:02:54 +00004653 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004654 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004655
drh153c62c2007-08-24 03:51:33 +00004656 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004657 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004658 if( ii>0 ){
4659 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004660 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004661 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004662#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004663 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004664#endif
drh308c2a52010-05-14 11:30:18 +00004665 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004666 }
4667 }
danielk1977fee2d252007-08-18 10:59:19 +00004668 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004669 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004670}
4671
danielk1977b4b47412007-08-17 15:53:36 +00004672/*
drh8b3cf822010-06-01 21:02:51 +00004673** Return the name of a directory in which to put temporary files.
4674** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004675*/
drh7234c6d2010-06-19 15:10:09 +00004676static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004677 static const char *azDirs[] = {
4678 0,
aswiftaebf4132008-11-21 00:10:35 +00004679 0,
danielk197717b90b52008-06-06 11:11:25 +00004680 "/var/tmp",
4681 "/usr/tmp",
4682 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004683 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004684 };
drh8b3cf822010-06-01 21:02:51 +00004685 unsigned int i;
4686 struct stat buf;
4687 const char *zDir = 0;
4688
4689 azDirs[0] = sqlite3_temp_directory;
4690 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004691 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004692 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004693 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004694 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004695 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004696 break;
4697 }
4698 return zDir;
4699}
4700
4701/*
4702** Create a temporary file name in zBuf. zBuf must be allocated
4703** by the calling process and must be big enough to hold at least
4704** pVfs->mxPathname bytes.
4705*/
4706static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004707 static const unsigned char zChars[] =
4708 "abcdefghijklmnopqrstuvwxyz"
4709 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4710 "0123456789";
drh41022642008-11-21 00:24:42 +00004711 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004712 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004713
4714 /* It's odd to simulate an io-error here, but really this is just
4715 ** using the io-error infrastructure to test that SQLite handles this
4716 ** function failing.
4717 */
4718 SimulateIOError( return SQLITE_IOERR );
4719
drh7234c6d2010-06-19 15:10:09 +00004720 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004721 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004722
4723 /* Check that the output buffer is large enough for the temporary file
4724 ** name. If it is not, return SQLITE_ERROR.
4725 */
danielk197700e13612008-11-17 19:18:54 +00004726 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004727 return SQLITE_ERROR;
4728 }
4729
4730 do{
4731 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004732 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004733 sqlite3_randomness(15, &zBuf[j]);
4734 for(i=0; i<15; i++, j++){
4735 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4736 }
4737 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004738 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004739 return SQLITE_OK;
4740}
4741
drhd2cb50b2009-01-09 21:41:17 +00004742#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004743/*
4744** Routine to transform a unixFile into a proxy-locking unixFile.
4745** Implementation in the proxy-lock division, but used by unixOpen()
4746** if SQLITE_PREFER_PROXY_LOCKING is defined.
4747*/
4748static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004749#endif
drhc66d5b62008-12-03 22:48:32 +00004750
dan08da86a2009-08-21 17:18:03 +00004751/*
4752** Search for an unused file descriptor that was opened on the database
4753** file (not a journal or master-journal file) identified by pathname
4754** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4755** argument to this function.
4756**
4757** Such a file descriptor may exist if a database connection was closed
4758** but the associated file descriptor could not be closed because some
4759** other file descriptor open on the same file is holding a file-lock.
4760** Refer to comments in the unixClose() function and the lengthy comment
4761** describing "Posix Advisory Locking" at the start of this file for
4762** further details. Also, ticket #4018.
4763**
4764** If a suitable file descriptor is found, then it is returned. If no
4765** such file descriptor is located, -1 is returned.
4766*/
dane946c392009-08-22 11:39:46 +00004767static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4768 UnixUnusedFd *pUnused = 0;
4769
4770 /* Do not search for an unused file descriptor on vxworks. Not because
4771 ** vxworks would not benefit from the change (it might, we're not sure),
4772 ** but because no way to test it is currently available. It is better
4773 ** not to risk breaking vxworks support for the sake of such an obscure
4774 ** feature. */
4775#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004776 struct stat sStat; /* Results of stat() call */
4777
4778 /* A stat() call may fail for various reasons. If this happens, it is
4779 ** almost certain that an open() call on the same path will also fail.
4780 ** For this reason, if an error occurs in the stat() call here, it is
4781 ** ignored and -1 is returned. The caller will try to open a new file
4782 ** descriptor on the same path, fail, and return an error to SQLite.
4783 **
4784 ** Even if a subsequent open() call does succeed, the consequences of
4785 ** not searching for a resusable file descriptor are not dire. */
4786 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004787 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004788
4789 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004790 pInode = inodeList;
4791 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4792 || pInode->fileId.ino!=sStat.st_ino) ){
4793 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004794 }
drh8af6c222010-05-14 12:43:01 +00004795 if( pInode ){
dane946c392009-08-22 11:39:46 +00004796 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004797 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004798 pUnused = *pp;
4799 if( pUnused ){
4800 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004801 }
4802 }
4803 unixLeaveMutex();
4804 }
dane946c392009-08-22 11:39:46 +00004805#endif /* if !OS_VXWORKS */
4806 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004807}
danielk197717b90b52008-06-06 11:11:25 +00004808
4809/*
danddb0ac42010-07-14 14:48:58 +00004810** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004811** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004812** and a value suitable for passing as the third argument to open(2) is
4813** written to *pMode. If an IO error occurs, an SQLite error code is
4814** returned and the value of *pMode is not modified.
4815**
4816** If the file being opened is a temporary file, it is always created with
4817** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004818** is a database or master journal file, it is created with the permissions
4819** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004820**
drh8ab58662010-07-15 18:38:39 +00004821** Finally, if the file being opened is a WAL or regular journal file, then
4822** this function queries the file-system for the permissions on the
4823** corresponding database file and sets *pMode to this value. Whenever
4824** possible, WAL and journal files are created using the same permissions
4825** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004826**
4827** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4828** original filename is unavailable. But 8_3_NAMES is only used for
4829** FAT filesystems and permissions do not matter there, so just use
4830** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004831*/
4832static int findCreateFileMode(
4833 const char *zPath, /* Path of file (possibly) being created */
4834 int flags, /* Flags passed as 4th argument to xOpen() */
4835 mode_t *pMode /* OUT: Permissions to open file with */
4836){
4837 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004838 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004839 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004840 char zDb[MAX_PATHNAME+1]; /* Database file path */
4841 int nDb; /* Number of valid bytes in zDb */
4842 struct stat sStat; /* Output of stat() on database file */
4843
dana0c989d2010-11-05 18:07:37 +00004844 /* zPath is a path to a WAL or journal file. The following block derives
4845 ** the path to the associated database file from zPath. This block handles
4846 ** the following naming conventions:
4847 **
4848 ** "<path to db>-journal"
4849 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004850 ** "<path to db>-journalNN"
4851 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004852 **
drh81cc5162011-05-17 20:36:21 +00004853 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004854 ** used by the test_multiplex.c module.
4855 */
4856 nDb = sqlite3Strlen30(zPath) - 1;
drh81cc5162011-05-17 20:36:21 +00004857 while( nDb>0 && zPath[nDb]!='-' ) nDb--;
4858 if( nDb==0 ) return SQLITE_OK;
danddb0ac42010-07-14 14:48:58 +00004859 memcpy(zDb, zPath, nDb);
4860 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004861
danddb0ac42010-07-14 14:48:58 +00004862 if( 0==stat(zDb, &sStat) ){
4863 *pMode = sStat.st_mode & 0777;
4864 }else{
4865 rc = SQLITE_IOERR_FSTAT;
4866 }
4867 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4868 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004869 }
4870 return rc;
4871}
4872
4873/*
danielk1977ad94b582007-08-20 06:44:22 +00004874** Open the file zPath.
4875**
danielk1977b4b47412007-08-17 15:53:36 +00004876** Previously, the SQLite OS layer used three functions in place of this
4877** one:
4878**
4879** sqlite3OsOpenReadWrite();
4880** sqlite3OsOpenReadOnly();
4881** sqlite3OsOpenExclusive();
4882**
4883** These calls correspond to the following combinations of flags:
4884**
4885** ReadWrite() -> (READWRITE | CREATE)
4886** ReadOnly() -> (READONLY)
4887** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4888**
4889** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4890** true, the file was configured to be automatically deleted when the
4891** file handle closed. To achieve the same effect using this new
4892** interface, add the DELETEONCLOSE flag to those specified above for
4893** OpenExclusive().
4894*/
4895static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004896 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4897 const char *zPath, /* Pathname of file to be opened */
4898 sqlite3_file *pFile, /* The file descriptor to be filled in */
4899 int flags, /* Input flags to control the opening */
4900 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004901){
dan08da86a2009-08-21 17:18:03 +00004902 unixFile *p = (unixFile *)pFile;
4903 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004904 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004905 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004906 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004907 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004908 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004909
4910 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4911 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4912 int isCreate = (flags & SQLITE_OPEN_CREATE);
4913 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4914 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004915#if SQLITE_ENABLE_LOCKING_STYLE
4916 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4917#endif
danielk1977b4b47412007-08-17 15:53:36 +00004918
danielk1977fee2d252007-08-18 10:59:19 +00004919 /* If creating a master or main-file journal, this function will open
4920 ** a file-descriptor on the directory too. The first time unixSync()
4921 ** is called the directory file descriptor will be fsync()ed and close()d.
4922 */
danddb0ac42010-07-14 14:48:58 +00004923 int isOpenDirectory = (isCreate && (
4924 eType==SQLITE_OPEN_MASTER_JOURNAL
4925 || eType==SQLITE_OPEN_MAIN_JOURNAL
4926 || eType==SQLITE_OPEN_WAL
4927 ));
danielk1977fee2d252007-08-18 10:59:19 +00004928
danielk197717b90b52008-06-06 11:11:25 +00004929 /* If argument zPath is a NULL pointer, this function is required to open
4930 ** a temporary file. Use this buffer to store the file name in.
4931 */
4932 char zTmpname[MAX_PATHNAME+1];
4933 const char *zName = zPath;
4934
danielk1977fee2d252007-08-18 10:59:19 +00004935 /* Check the following statements are true:
4936 **
4937 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4938 ** (b) if CREATE is set, then READWRITE must also be set, and
4939 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004940 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004941 */
danielk1977b4b47412007-08-17 15:53:36 +00004942 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004943 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004944 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004945 assert(isDelete==0 || isCreate);
4946
danddb0ac42010-07-14 14:48:58 +00004947 /* The main DB, main journal, WAL file and master journal are never
4948 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004949 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4950 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4951 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004952 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004953
danielk1977fee2d252007-08-18 10:59:19 +00004954 /* Assert that the upper layer has set one of the "file-type" flags. */
4955 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4956 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4957 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004958 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004959 );
4960
dan08da86a2009-08-21 17:18:03 +00004961 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004962
dan08da86a2009-08-21 17:18:03 +00004963 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004964 UnixUnusedFd *pUnused;
4965 pUnused = findReusableFd(zName, flags);
4966 if( pUnused ){
4967 fd = pUnused->fd;
4968 }else{
dan6aa657f2009-08-24 18:57:58 +00004969 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004970 if( !pUnused ){
4971 return SQLITE_NOMEM;
4972 }
4973 }
4974 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004975 }else if( !zName ){
4976 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004977 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004978 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004979 if( rc!=SQLITE_OK ){
4980 return rc;
4981 }
4982 zName = zTmpname;
4983 }
4984
dan08da86a2009-08-21 17:18:03 +00004985 /* Determine the value of the flags parameter passed to POSIX function
4986 ** open(). These must be calculated even if open() is not called, as
4987 ** they may be stored as part of the file handle and used by the
4988 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004989 if( isReadonly ) openFlags |= O_RDONLY;
4990 if( isReadWrite ) openFlags |= O_RDWR;
4991 if( isCreate ) openFlags |= O_CREAT;
4992 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4993 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004994
danielk1977b4b47412007-08-17 15:53:36 +00004995 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004996 mode_t openMode; /* Permissions to create file with */
4997 rc = findCreateFileMode(zName, flags, &openMode);
4998 if( rc!=SQLITE_OK ){
4999 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005000 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005001 return rc;
5002 }
drhad4f1e52011-03-04 15:43:57 +00005003 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005004 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005005 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5006 /* Failed to open the file for read/write access. Try read-only. */
5007 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005008 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005009 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005010 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005011 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005012 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005013 }
5014 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005015 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005016 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005017 }
danielk1977b4b47412007-08-17 15:53:36 +00005018 }
dan08da86a2009-08-21 17:18:03 +00005019 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005020 if( pOutFlags ){
5021 *pOutFlags = flags;
5022 }
5023
dane946c392009-08-22 11:39:46 +00005024 if( p->pUnused ){
5025 p->pUnused->fd = fd;
5026 p->pUnused->flags = flags;
5027 }
5028
danielk1977b4b47412007-08-17 15:53:36 +00005029 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005030#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005031 zPath = zName;
5032#else
danielk197717b90b52008-06-06 11:11:25 +00005033 unlink(zName);
chw97185482008-11-17 08:05:31 +00005034#endif
danielk1977b4b47412007-08-17 15:53:36 +00005035 }
drh41022642008-11-21 00:24:42 +00005036#if SQLITE_ENABLE_LOCKING_STYLE
5037 else{
dan08da86a2009-08-21 17:18:03 +00005038 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005039 }
5040#endif
5041
danielk1977fee2d252007-08-18 10:59:19 +00005042 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005043 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005044 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005045 /* It is safe to close fd at this point, because it is guaranteed not
5046 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005047 ** it would not be safe to close as this would release any locks held
5048 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005049 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005050 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005051 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005052 }
5053 }
danielk1977e339d652008-06-28 11:23:00 +00005054
5055#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005056 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005057#endif
5058
drhda0e7682008-07-30 15:27:54 +00005059 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005060
drh7ed97b92010-01-20 13:07:21 +00005061
5062#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5063 struct statfs fsInfo;
5064 if( fstatfs(fd, &fsInfo) == -1 ){
5065 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005066 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5067 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005068 return SQLITE_IOERR_ACCESS;
5069 }
5070 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5071 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5072 }
5073#endif
5074
5075#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005076#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005077 isAutoProxy = 1;
5078#endif
5079 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005080 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5081 int useProxy = 0;
5082
dan08da86a2009-08-21 17:18:03 +00005083 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5084 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005085 if( envforce!=NULL ){
5086 useProxy = atoi(envforce)>0;
5087 }else{
5088 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005089 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005090 /* In theory, the close(fd) call is sub-optimal. If the file opened
5091 ** with fd is a database file, and there are other connections open
5092 ** on that file that are currently holding advisory locks on it,
5093 ** then the call to close() will cancel those locks. In practice,
5094 ** we're assuming that statfs() doesn't fail very often. At least
5095 ** not while other file descriptors opened by the same process on
5096 ** the same file are working. */
5097 p->lastErrno = errno;
5098 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005099 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005100 }
drh0e9365c2011-03-02 02:08:13 +00005101 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005102 rc = SQLITE_IOERR_ACCESS;
5103 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005104 }
5105 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5106 }
5107 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005108 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5109 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005110 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005111 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005112 if( rc!=SQLITE_OK ){
5113 /* Use unixClose to clean up the resources added in fillInUnixFile
5114 ** and clear all the structure's references. Specifically,
5115 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5116 */
5117 unixClose(pFile);
5118 return rc;
5119 }
aswiftaebf4132008-11-21 00:10:35 +00005120 }
dane946c392009-08-22 11:39:46 +00005121 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005122 }
5123 }
5124#endif
5125
drh77197112011-03-15 19:08:48 +00005126 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5127 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005128open_finished:
5129 if( rc!=SQLITE_OK ){
5130 sqlite3_free(p->pUnused);
5131 }
5132 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005133}
5134
dane946c392009-08-22 11:39:46 +00005135
danielk1977b4b47412007-08-17 15:53:36 +00005136/*
danielk1977fee2d252007-08-18 10:59:19 +00005137** Delete the file at zPath. If the dirSync argument is true, fsync()
5138** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005139*/
drh6b9d6dd2008-12-03 19:34:47 +00005140static int unixDelete(
5141 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5142 const char *zPath, /* Name of file to be deleted */
5143 int dirSync /* If true, fsync() directory after deleting file */
5144){
danielk1977fee2d252007-08-18 10:59:19 +00005145 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005146 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005147 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005148 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005149 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005150 }
danielk1977d39fa702008-10-16 13:27:40 +00005151#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005152 if( dirSync ){
5153 int fd;
5154 rc = openDirectory(zPath, &fd);
5155 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005156#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005157 if( fsync(fd)==-1 )
5158#else
5159 if( fsync(fd) )
5160#endif
5161 {
dane18d4952011-02-21 11:46:24 +00005162 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005163 }
drh0e9365c2011-03-02 02:08:13 +00005164 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005165 }
5166 }
danielk1977d138dd82008-10-15 16:02:48 +00005167#endif
danielk1977fee2d252007-08-18 10:59:19 +00005168 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005169}
5170
danielk197790949c22007-08-17 16:50:38 +00005171/*
5172** Test the existance of or access permissions of file zPath. The
5173** test performed depends on the value of flags:
5174**
5175** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5176** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5177** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5178**
5179** Otherwise return 0.
5180*/
danielk1977861f7452008-06-05 11:39:11 +00005181static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005182 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5183 const char *zPath, /* Path of the file to examine */
5184 int flags, /* What do we want to learn about the zPath file? */
5185 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005186){
rse25c0d1a2007-09-20 08:38:14 +00005187 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005188 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005189 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005190 switch( flags ){
5191 case SQLITE_ACCESS_EXISTS:
5192 amode = F_OK;
5193 break;
5194 case SQLITE_ACCESS_READWRITE:
5195 amode = W_OK|R_OK;
5196 break;
drh50d3f902007-08-27 21:10:36 +00005197 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005198 amode = R_OK;
5199 break;
5200
5201 default:
5202 assert(!"Invalid flags argument");
5203 }
drh99ab3b12011-03-02 15:09:07 +00005204 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005205 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5206 struct stat buf;
5207 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5208 *pResOut = 0;
5209 }
5210 }
danielk1977861f7452008-06-05 11:39:11 +00005211 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005212}
5213
danielk1977b4b47412007-08-17 15:53:36 +00005214
5215/*
5216** Turn a relative pathname into a full pathname. The relative path
5217** is stored as a nul-terminated string in the buffer pointed to by
5218** zPath.
5219**
5220** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5221** (in this case, MAX_PATHNAME bytes). The full-path is written to
5222** this buffer before returning.
5223*/
danielk1977adfb9b02007-09-17 07:02:56 +00005224static int unixFullPathname(
5225 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5226 const char *zPath, /* Possibly relative input path */
5227 int nOut, /* Size of output buffer in bytes */
5228 char *zOut /* Output buffer */
5229){
danielk1977843e65f2007-09-01 16:16:15 +00005230
5231 /* It's odd to simulate an io-error here, but really this is just
5232 ** using the io-error infrastructure to test that SQLite handles this
5233 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005234 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005235 */
5236 SimulateIOError( return SQLITE_ERROR );
5237
drh153c62c2007-08-24 03:51:33 +00005238 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005239 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005240
drh3c7f2dc2007-12-06 13:26:20 +00005241 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005242 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005243 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005244 }else{
5245 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005246 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005247 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005248 }
drhea678832008-12-10 19:26:22 +00005249 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005250 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005251 }
5252 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005253}
5254
drh0ccebe72005-06-07 22:22:50 +00005255
drh761df872006-12-21 01:29:22 +00005256#ifndef SQLITE_OMIT_LOAD_EXTENSION
5257/*
5258** Interfaces for opening a shared library, finding entry points
5259** within the shared library, and closing the shared library.
5260*/
5261#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005262static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5263 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005264 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5265}
danielk197795c8a542007-09-01 06:51:27 +00005266
5267/*
5268** SQLite calls this function immediately after a call to unixDlSym() or
5269** unixDlOpen() fails (returns a null pointer). If a more detailed error
5270** message is available, it is written to zBufOut. If no error message
5271** is available, zBufOut is left unmodified and SQLite uses a default
5272** error message.
5273*/
danielk1977397d65f2008-11-19 11:35:39 +00005274static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005275 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005276 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005277 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005278 zErr = dlerror();
5279 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005280 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005281 }
drh6c7d5c52008-11-21 20:32:33 +00005282 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005283}
drh1875f7a2008-12-08 18:19:17 +00005284static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5285 /*
5286 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5287 ** cast into a pointer to a function. And yet the library dlsym() routine
5288 ** returns a void* which is really a pointer to a function. So how do we
5289 ** use dlsym() with -pedantic-errors?
5290 **
5291 ** Variable x below is defined to be a pointer to a function taking
5292 ** parameters void* and const char* and returning a pointer to a function.
5293 ** We initialize x by assigning it a pointer to the dlsym() function.
5294 ** (That assignment requires a cast.) Then we call the function that
5295 ** x points to.
5296 **
5297 ** This work-around is unlikely to work correctly on any system where
5298 ** you really cannot cast a function pointer into void*. But then, on the
5299 ** other hand, dlsym() will not work on such a system either, so we have
5300 ** not really lost anything.
5301 */
5302 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005303 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005304 x = (void(*(*)(void*,const char*))(void))dlsym;
5305 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005306}
danielk1977397d65f2008-11-19 11:35:39 +00005307static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5308 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005309 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005310}
danielk1977b4b47412007-08-17 15:53:36 +00005311#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5312 #define unixDlOpen 0
5313 #define unixDlError 0
5314 #define unixDlSym 0
5315 #define unixDlClose 0
5316#endif
5317
5318/*
danielk197790949c22007-08-17 16:50:38 +00005319** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005320*/
danielk1977397d65f2008-11-19 11:35:39 +00005321static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5322 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005323 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005324
drhbbd42a62004-05-22 17:41:58 +00005325 /* We have to initialize zBuf to prevent valgrind from reporting
5326 ** errors. The reports issued by valgrind are incorrect - we would
5327 ** prefer that the randomness be increased by making use of the
5328 ** uninitialized space in zBuf - but valgrind errors tend to worry
5329 ** some users. Rather than argue, it seems easier just to initialize
5330 ** the whole array and silence valgrind, even if that means less randomness
5331 ** in the random seed.
5332 **
5333 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005334 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005335 ** tests repeatable.
5336 */
danielk1977b4b47412007-08-17 15:53:36 +00005337 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005338#if !defined(SQLITE_TEST)
5339 {
drh842b8642005-01-21 17:53:17 +00005340 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005341 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005342 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005343 time_t t;
5344 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005345 memcpy(zBuf, &t, sizeof(t));
5346 pid = getpid();
5347 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005348 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005349 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005350 }else{
drhe562be52011-03-02 18:01:10 +00005351 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005352 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005353 }
drhbbd42a62004-05-22 17:41:58 +00005354 }
5355#endif
drh72cbd072008-10-14 17:58:38 +00005356 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005357}
5358
danielk1977b4b47412007-08-17 15:53:36 +00005359
drhbbd42a62004-05-22 17:41:58 +00005360/*
5361** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005362** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005363** The return value is the number of microseconds of sleep actually
5364** requested from the underlying operating system, a number which
5365** might be greater than or equal to the argument, but not less
5366** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005367*/
danielk1977397d65f2008-11-19 11:35:39 +00005368static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005369#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005370 struct timespec sp;
5371
5372 sp.tv_sec = microseconds / 1000000;
5373 sp.tv_nsec = (microseconds % 1000000) * 1000;
5374 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005375 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005376 return microseconds;
5377#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005378 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005379 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005380 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005381#else
danielk1977b4b47412007-08-17 15:53:36 +00005382 int seconds = (microseconds+999999)/1000000;
5383 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005384 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005385 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005386#endif
drh88f474a2006-01-02 20:00:12 +00005387}
5388
5389/*
drh6b9d6dd2008-12-03 19:34:47 +00005390** The following variable, if set to a non-zero value, is interpreted as
5391** the number of seconds since 1970 and is used to set the result of
5392** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005393*/
5394#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005395int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005396#endif
5397
5398/*
drhb7e8ea22010-05-03 14:32:30 +00005399** Find the current time (in Universal Coordinated Time). Write into *piNow
5400** the current time and date as a Julian Day number times 86_400_000. In
5401** other words, write into *piNow the number of milliseconds since the Julian
5402** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5403** proleptic Gregorian calendar.
5404**
5405** On success, return 0. Return 1 if the time and date cannot be found.
5406*/
5407static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5408 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5409#if defined(NO_GETTOD)
5410 time_t t;
5411 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005412 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005413#elif OS_VXWORKS
5414 struct timespec sNow;
5415 clock_gettime(CLOCK_REALTIME, &sNow);
5416 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5417#else
5418 struct timeval sNow;
5419 gettimeofday(&sNow, 0);
5420 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5421#endif
5422
5423#ifdef SQLITE_TEST
5424 if( sqlite3_current_time ){
5425 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5426 }
5427#endif
5428 UNUSED_PARAMETER(NotUsed);
5429 return 0;
5430}
5431
5432/*
drhbbd42a62004-05-22 17:41:58 +00005433** Find the current time (in Universal Coordinated Time). Write the
5434** current time and date as a Julian Day number into *prNow and
5435** return 0. Return 1 if the time and date cannot be found.
5436*/
danielk1977397d65f2008-11-19 11:35:39 +00005437static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005438 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005439 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005440 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005441 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005442 return 0;
5443}
danielk1977b4b47412007-08-17 15:53:36 +00005444
drh6b9d6dd2008-12-03 19:34:47 +00005445/*
5446** We added the xGetLastError() method with the intention of providing
5447** better low-level error messages when operating-system problems come up
5448** during SQLite operation. But so far, none of that has been implemented
5449** in the core. So this routine is never called. For now, it is merely
5450** a place-holder.
5451*/
danielk1977397d65f2008-11-19 11:35:39 +00005452static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5453 UNUSED_PARAMETER(NotUsed);
5454 UNUSED_PARAMETER(NotUsed2);
5455 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005456 return 0;
5457}
5458
drhf2424c52010-04-26 00:04:55 +00005459
5460/*
drh734c9862008-11-28 15:37:20 +00005461************************ End of sqlite3_vfs methods ***************************
5462******************************************************************************/
5463
drh715ff302008-12-03 22:32:44 +00005464/******************************************************************************
5465************************** Begin Proxy Locking ********************************
5466**
5467** Proxy locking is a "uber-locking-method" in this sense: It uses the
5468** other locking methods on secondary lock files. Proxy locking is a
5469** meta-layer over top of the primitive locking implemented above. For
5470** this reason, the division that implements of proxy locking is deferred
5471** until late in the file (here) after all of the other I/O methods have
5472** been defined - so that the primitive locking methods are available
5473** as services to help with the implementation of proxy locking.
5474**
5475****
5476**
5477** The default locking schemes in SQLite use byte-range locks on the
5478** database file to coordinate safe, concurrent access by multiple readers
5479** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5480** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5481** as POSIX read & write locks over fixed set of locations (via fsctl),
5482** on AFP and SMB only exclusive byte-range locks are available via fsctl
5483** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5484** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5485** address in the shared range is taken for a SHARED lock, the entire
5486** shared range is taken for an EXCLUSIVE lock):
5487**
5488** PENDING_BYTE 0x40000000
5489** RESERVED_BYTE 0x40000001
5490** SHARED_RANGE 0x40000002 -> 0x40000200
5491**
5492** This works well on the local file system, but shows a nearly 100x
5493** slowdown in read performance on AFP because the AFP client disables
5494** the read cache when byte-range locks are present. Enabling the read
5495** cache exposes a cache coherency problem that is present on all OS X
5496** supported network file systems. NFS and AFP both observe the
5497** close-to-open semantics for ensuring cache coherency
5498** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5499** address the requirements for concurrent database access by multiple
5500** readers and writers
5501** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5502**
5503** To address the performance and cache coherency issues, proxy file locking
5504** changes the way database access is controlled by limiting access to a
5505** single host at a time and moving file locks off of the database file
5506** and onto a proxy file on the local file system.
5507**
5508**
5509** Using proxy locks
5510** -----------------
5511**
5512** C APIs
5513**
5514** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5515** <proxy_path> | ":auto:");
5516** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5517**
5518**
5519** SQL pragmas
5520**
5521** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5522** PRAGMA [database.]lock_proxy_file
5523**
5524** Specifying ":auto:" means that if there is a conch file with a matching
5525** host ID in it, the proxy path in the conch file will be used, otherwise
5526** a proxy path based on the user's temp dir
5527** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5528** actual proxy file name is generated from the name and path of the
5529** database file. For example:
5530**
5531** For database path "/Users/me/foo.db"
5532** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5533**
5534** Once a lock proxy is configured for a database connection, it can not
5535** be removed, however it may be switched to a different proxy path via
5536** the above APIs (assuming the conch file is not being held by another
5537** connection or process).
5538**
5539**
5540** How proxy locking works
5541** -----------------------
5542**
5543** Proxy file locking relies primarily on two new supporting files:
5544**
5545** * conch file to limit access to the database file to a single host
5546** at a time
5547**
5548** * proxy file to act as a proxy for the advisory locks normally
5549** taken on the database
5550**
5551** The conch file - to use a proxy file, sqlite must first "hold the conch"
5552** by taking an sqlite-style shared lock on the conch file, reading the
5553** contents and comparing the host's unique host ID (see below) and lock
5554** proxy path against the values stored in the conch. The conch file is
5555** stored in the same directory as the database file and the file name
5556** is patterned after the database file name as ".<databasename>-conch".
5557** If the conch file does not exist, or it's contents do not match the
5558** host ID and/or proxy path, then the lock is escalated to an exclusive
5559** lock and the conch file contents is updated with the host ID and proxy
5560** path and the lock is downgraded to a shared lock again. If the conch
5561** is held by another process (with a shared lock), the exclusive lock
5562** will fail and SQLITE_BUSY is returned.
5563**
5564** The proxy file - a single-byte file used for all advisory file locks
5565** normally taken on the database file. This allows for safe sharing
5566** of the database file for multiple readers and writers on the same
5567** host (the conch ensures that they all use the same local lock file).
5568**
drh715ff302008-12-03 22:32:44 +00005569** Requesting the lock proxy does not immediately take the conch, it is
5570** only taken when the first request to lock database file is made.
5571** This matches the semantics of the traditional locking behavior, where
5572** opening a connection to a database file does not take a lock on it.
5573** The shared lock and an open file descriptor are maintained until
5574** the connection to the database is closed.
5575**
5576** The proxy file and the lock file are never deleted so they only need
5577** to be created the first time they are used.
5578**
5579** Configuration options
5580** ---------------------
5581**
5582** SQLITE_PREFER_PROXY_LOCKING
5583**
5584** Database files accessed on non-local file systems are
5585** automatically configured for proxy locking, lock files are
5586** named automatically using the same logic as
5587** PRAGMA lock_proxy_file=":auto:"
5588**
5589** SQLITE_PROXY_DEBUG
5590**
5591** Enables the logging of error messages during host id file
5592** retrieval and creation
5593**
drh715ff302008-12-03 22:32:44 +00005594** LOCKPROXYDIR
5595**
5596** Overrides the default directory used for lock proxy files that
5597** are named automatically via the ":auto:" setting
5598**
5599** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5600**
5601** Permissions to use when creating a directory for storing the
5602** lock proxy files, only used when LOCKPROXYDIR is not set.
5603**
5604**
5605** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5606** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5607** force proxy locking to be used for every database file opened, and 0
5608** will force automatic proxy locking to be disabled for all database
5609** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5610** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5611*/
5612
5613/*
5614** Proxy locking is only available on MacOSX
5615*/
drhd2cb50b2009-01-09 21:41:17 +00005616#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005617
drh715ff302008-12-03 22:32:44 +00005618/*
5619** The proxyLockingContext has the path and file structures for the remote
5620** and local proxy files in it
5621*/
5622typedef struct proxyLockingContext proxyLockingContext;
5623struct proxyLockingContext {
5624 unixFile *conchFile; /* Open conch file */
5625 char *conchFilePath; /* Name of the conch file */
5626 unixFile *lockProxy; /* Open proxy lock file */
5627 char *lockProxyPath; /* Name of the proxy lock file */
5628 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005629 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005630 void *oldLockingContext; /* Original lockingcontext to restore on close */
5631 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5632};
5633
drh7ed97b92010-01-20 13:07:21 +00005634/*
5635** The proxy lock file path for the database at dbPath is written into lPath,
5636** which must point to valid, writable memory large enough for a maxLen length
5637** file path.
drh715ff302008-12-03 22:32:44 +00005638*/
drh715ff302008-12-03 22:32:44 +00005639static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5640 int len;
5641 int dbLen;
5642 int i;
5643
5644#ifdef LOCKPROXYDIR
5645 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5646#else
5647# ifdef _CS_DARWIN_USER_TEMP_DIR
5648 {
drh7ed97b92010-01-20 13:07:21 +00005649 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005650 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5651 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005652 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005653 }
drh7ed97b92010-01-20 13:07:21 +00005654 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005655 }
5656# else
5657 len = strlcpy(lPath, "/tmp/", maxLen);
5658# endif
5659#endif
5660
5661 if( lPath[len-1]!='/' ){
5662 len = strlcat(lPath, "/", maxLen);
5663 }
5664
5665 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005666 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005667 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005668 char c = dbPath[i];
5669 lPath[i+len] = (c=='/')?'_':c;
5670 }
5671 lPath[i+len]='\0';
5672 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005673 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005674 return SQLITE_OK;
5675}
5676
drh7ed97b92010-01-20 13:07:21 +00005677/*
5678 ** Creates the lock file and any missing directories in lockPath
5679 */
5680static int proxyCreateLockPath(const char *lockPath){
5681 int i, len;
5682 char buf[MAXPATHLEN];
5683 int start = 0;
5684
5685 assert(lockPath!=NULL);
5686 /* try to create all the intermediate directories */
5687 len = (int)strlen(lockPath);
5688 buf[0] = lockPath[0];
5689 for( i=1; i<len; i++ ){
5690 if( lockPath[i] == '/' && (i - start > 0) ){
5691 /* only mkdir if leaf dir != "." or "/" or ".." */
5692 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5693 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5694 buf[i]='\0';
5695 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5696 int err=errno;
5697 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005698 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005699 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005700 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005701 return err;
5702 }
5703 }
5704 }
5705 start=i+1;
5706 }
5707 buf[i] = lockPath[i];
5708 }
drh308c2a52010-05-14 11:30:18 +00005709 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005710 return 0;
5711}
5712
drh715ff302008-12-03 22:32:44 +00005713/*
5714** Create a new VFS file descriptor (stored in memory obtained from
5715** sqlite3_malloc) and open the file named "path" in the file descriptor.
5716**
5717** The caller is responsible not only for closing the file descriptor
5718** but also for freeing the memory associated with the file descriptor.
5719*/
drh7ed97b92010-01-20 13:07:21 +00005720static int proxyCreateUnixFile(
5721 const char *path, /* path for the new unixFile */
5722 unixFile **ppFile, /* unixFile created and returned by ref */
5723 int islockfile /* if non zero missing dirs will be created */
5724) {
5725 int fd = -1;
5726 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005727 unixFile *pNew;
5728 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005729 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005730 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005731 int terrno = 0;
5732 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005733
drh7ed97b92010-01-20 13:07:21 +00005734 /* 1. first try to open/create the file
5735 ** 2. if that fails, and this is a lock file (not-conch), try creating
5736 ** the parent directories and then try again.
5737 ** 3. if that fails, try to open the file read-only
5738 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5739 */
5740 pUnused = findReusableFd(path, openFlags);
5741 if( pUnused ){
5742 fd = pUnused->fd;
5743 }else{
5744 pUnused = sqlite3_malloc(sizeof(*pUnused));
5745 if( !pUnused ){
5746 return SQLITE_NOMEM;
5747 }
5748 }
5749 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005750 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005751 terrno = errno;
5752 if( fd<0 && errno==ENOENT && islockfile ){
5753 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005754 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005755 }
5756 }
5757 }
5758 if( fd<0 ){
5759 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005760 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005761 terrno = errno;
5762 }
5763 if( fd<0 ){
5764 if( islockfile ){
5765 return SQLITE_BUSY;
5766 }
5767 switch (terrno) {
5768 case EACCES:
5769 return SQLITE_PERM;
5770 case EIO:
5771 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5772 default:
drh9978c972010-02-23 17:36:32 +00005773 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005774 }
5775 }
5776
5777 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5778 if( pNew==NULL ){
5779 rc = SQLITE_NOMEM;
5780 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005781 }
5782 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005783 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005784 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005785 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005786 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005787 pUnused->fd = fd;
5788 pUnused->flags = openFlags;
5789 pNew->pUnused = pUnused;
5790
drh77197112011-03-15 19:08:48 +00005791 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005792 if( rc==SQLITE_OK ){
5793 *ppFile = pNew;
5794 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005795 }
drh7ed97b92010-01-20 13:07:21 +00005796end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005797 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005798 sqlite3_free(pNew);
5799 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005800 return rc;
5801}
5802
drh7ed97b92010-01-20 13:07:21 +00005803#ifdef SQLITE_TEST
5804/* simulate multiple hosts by creating unique hostid file paths */
5805int sqlite3_hostid_num = 0;
5806#endif
5807
5808#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5809
drh0ab216a2010-07-02 17:10:40 +00005810/* Not always defined in the headers as it ought to be */
5811extern int gethostuuid(uuid_t id, const struct timespec *wait);
5812
drh7ed97b92010-01-20 13:07:21 +00005813/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5814** bytes of writable memory.
5815*/
5816static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005817 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5818 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005819#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5820 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005821 {
5822 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5823 if( gethostuuid(pHostID, &timeout) ){
5824 int err = errno;
5825 if( pError ){
5826 *pError = err;
5827 }
5828 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005829 }
drh7ed97b92010-01-20 13:07:21 +00005830 }
drhe8b0c9b2010-09-25 14:13:17 +00005831#endif
drh7ed97b92010-01-20 13:07:21 +00005832#ifdef SQLITE_TEST
5833 /* simulate multiple hosts by creating unique hostid file paths */
5834 if( sqlite3_hostid_num != 0){
5835 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5836 }
5837#endif
5838
5839 return SQLITE_OK;
5840}
5841
5842/* The conch file contains the header, host id and lock file path
5843 */
5844#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5845#define PROXY_HEADERLEN 1 /* conch file header length */
5846#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5847#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5848
5849/*
5850** Takes an open conch file, copies the contents to a new path and then moves
5851** it back. The newly created file's file descriptor is assigned to the
5852** conch file structure and finally the original conch file descriptor is
5853** closed. Returns zero if successful.
5854*/
5855static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5856 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5857 unixFile *conchFile = pCtx->conchFile;
5858 char tPath[MAXPATHLEN];
5859 char buf[PROXY_MAXCONCHLEN];
5860 char *cPath = pCtx->conchFilePath;
5861 size_t readLen = 0;
5862 size_t pathLen = 0;
5863 char errmsg[64] = "";
5864 int fd = -1;
5865 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005866 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005867
5868 /* create a new path by replace the trailing '-conch' with '-break' */
5869 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5870 if( pathLen>MAXPATHLEN || pathLen<6 ||
5871 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005872 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005873 goto end_breaklock;
5874 }
5875 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005876 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005877 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005878 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005879 goto end_breaklock;
5880 }
5881 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005882 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5883 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005884 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005885 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005886 goto end_breaklock;
5887 }
drhe562be52011-03-02 18:01:10 +00005888 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005889 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005890 goto end_breaklock;
5891 }
5892 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005893 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005894 goto end_breaklock;
5895 }
5896 rc = 0;
5897 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005898 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005899 conchFile->h = fd;
5900 conchFile->openFlags = O_RDWR | O_CREAT;
5901
5902end_breaklock:
5903 if( rc ){
5904 if( fd>=0 ){
5905 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005906 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005907 }
5908 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5909 }
5910 return rc;
5911}
5912
5913/* Take the requested lock on the conch file and break a stale lock if the
5914** host id matches.
5915*/
5916static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5917 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5918 unixFile *conchFile = pCtx->conchFile;
5919 int rc = SQLITE_OK;
5920 int nTries = 0;
5921 struct timespec conchModTime;
5922
5923 do {
5924 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5925 nTries ++;
5926 if( rc==SQLITE_BUSY ){
5927 /* If the lock failed (busy):
5928 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5929 * 2nd try: fail if the mod time changed or host id is different, wait
5930 * 10 sec and try again
5931 * 3rd try: break the lock unless the mod time has changed.
5932 */
5933 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005934 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005935 pFile->lastErrno = errno;
5936 return SQLITE_IOERR_LOCK;
5937 }
5938
5939 if( nTries==1 ){
5940 conchModTime = buf.st_mtimespec;
5941 usleep(500000); /* wait 0.5 sec and try the lock again*/
5942 continue;
5943 }
5944
5945 assert( nTries>1 );
5946 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5947 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5948 return SQLITE_BUSY;
5949 }
5950
5951 if( nTries==2 ){
5952 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005953 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005954 if( len<0 ){
5955 pFile->lastErrno = errno;
5956 return SQLITE_IOERR_LOCK;
5957 }
5958 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5959 /* don't break the lock if the host id doesn't match */
5960 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5961 return SQLITE_BUSY;
5962 }
5963 }else{
5964 /* don't break the lock on short read or a version mismatch */
5965 return SQLITE_BUSY;
5966 }
5967 usleep(10000000); /* wait 10 sec and try the lock again */
5968 continue;
5969 }
5970
5971 assert( nTries==3 );
5972 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5973 rc = SQLITE_OK;
5974 if( lockType==EXCLUSIVE_LOCK ){
5975 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5976 }
5977 if( !rc ){
5978 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5979 }
5980 }
5981 }
5982 } while( rc==SQLITE_BUSY && nTries<3 );
5983
5984 return rc;
5985}
5986
5987/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005988** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5989** lockPath means that the lockPath in the conch file will be used if the
5990** host IDs match, or a new lock path will be generated automatically
5991** and written to the conch file.
5992*/
5993static int proxyTakeConch(unixFile *pFile){
5994 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5995
drh7ed97b92010-01-20 13:07:21 +00005996 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005997 return SQLITE_OK;
5998 }else{
5999 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006000 uuid_t myHostID;
6001 int pError = 0;
6002 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006003 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006004 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006005 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006006 int createConch = 0;
6007 int hostIdMatch = 0;
6008 int readLen = 0;
6009 int tryOldLockPath = 0;
6010 int forceNewLockPath = 0;
6011
drh308c2a52010-05-14 11:30:18 +00006012 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6013 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006014
drh7ed97b92010-01-20 13:07:21 +00006015 rc = proxyGetHostID(myHostID, &pError);
6016 if( (rc&0xff)==SQLITE_IOERR ){
6017 pFile->lastErrno = pError;
6018 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006019 }
drh7ed97b92010-01-20 13:07:21 +00006020 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006021 if( rc!=SQLITE_OK ){
6022 goto end_takeconch;
6023 }
drh7ed97b92010-01-20 13:07:21 +00006024 /* read the existing conch file */
6025 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6026 if( readLen<0 ){
6027 /* I/O error: lastErrno set by seekAndRead */
6028 pFile->lastErrno = conchFile->lastErrno;
6029 rc = SQLITE_IOERR_READ;
6030 goto end_takeconch;
6031 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6032 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6033 /* a short read or version format mismatch means we need to create a new
6034 ** conch file.
6035 */
6036 createConch = 1;
6037 }
6038 /* if the host id matches and the lock path already exists in the conch
6039 ** we'll try to use the path there, if we can't open that path, we'll
6040 ** retry with a new auto-generated path
6041 */
6042 do { /* in case we need to try again for an :auto: named lock file */
6043
6044 if( !createConch && !forceNewLockPath ){
6045 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6046 PROXY_HOSTIDLEN);
6047 /* if the conch has data compare the contents */
6048 if( !pCtx->lockProxyPath ){
6049 /* for auto-named local lock file, just check the host ID and we'll
6050 ** use the local lock file path that's already in there
6051 */
6052 if( hostIdMatch ){
6053 size_t pathLen = (readLen - PROXY_PATHINDEX);
6054
6055 if( pathLen>=MAXPATHLEN ){
6056 pathLen=MAXPATHLEN-1;
6057 }
6058 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6059 lockPath[pathLen] = 0;
6060 tempLockPath = lockPath;
6061 tryOldLockPath = 1;
6062 /* create a copy of the lock path if the conch is taken */
6063 goto end_takeconch;
6064 }
6065 }else if( hostIdMatch
6066 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6067 readLen-PROXY_PATHINDEX)
6068 ){
6069 /* conch host and lock path match */
6070 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006071 }
drh7ed97b92010-01-20 13:07:21 +00006072 }
6073
6074 /* if the conch isn't writable and doesn't match, we can't take it */
6075 if( (conchFile->openFlags&O_RDWR) == 0 ){
6076 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006077 goto end_takeconch;
6078 }
drh7ed97b92010-01-20 13:07:21 +00006079
6080 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006081 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006082 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6083 tempLockPath = lockPath;
6084 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006085 }
drh7ed97b92010-01-20 13:07:21 +00006086
6087 /* update conch with host and path (this will fail if other process
6088 ** has a shared lock already), if the host id matches, use the big
6089 ** stick.
drh715ff302008-12-03 22:32:44 +00006090 */
drh7ed97b92010-01-20 13:07:21 +00006091 futimes(conchFile->h, NULL);
6092 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006093 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006094 /* We are trying for an exclusive lock but another thread in this
6095 ** same process is still holding a shared lock. */
6096 rc = SQLITE_BUSY;
6097 } else {
6098 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006099 }
drh715ff302008-12-03 22:32:44 +00006100 }else{
drh7ed97b92010-01-20 13:07:21 +00006101 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006102 }
drh7ed97b92010-01-20 13:07:21 +00006103 if( rc==SQLITE_OK ){
6104 char writeBuffer[PROXY_MAXCONCHLEN];
6105 int writeSize = 0;
6106
6107 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6108 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6109 if( pCtx->lockProxyPath!=NULL ){
6110 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6111 }else{
6112 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6113 }
6114 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006115 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006116 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6117 fsync(conchFile->h);
6118 /* If we created a new conch file (not just updated the contents of a
6119 ** valid conch file), try to match the permissions of the database
6120 */
6121 if( rc==SQLITE_OK && createConch ){
6122 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006123 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006124 if( err==0 ){
6125 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6126 S_IROTH|S_IWOTH);
6127 /* try to match the database file R/W permissions, ignore failure */
6128#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006129 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006130#else
drhff812312011-02-23 13:33:46 +00006131 do{
drhe562be52011-03-02 18:01:10 +00006132 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006133 }while( rc==(-1) && errno==EINTR );
6134 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006135 int code = errno;
6136 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6137 cmode, code, strerror(code));
6138 } else {
6139 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6140 }
6141 }else{
6142 int code = errno;
6143 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6144 err, code, strerror(code));
6145#endif
6146 }
drh715ff302008-12-03 22:32:44 +00006147 }
6148 }
drh7ed97b92010-01-20 13:07:21 +00006149 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6150
6151 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006152 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006153 if( rc==SQLITE_OK && pFile->openFlags ){
6154 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006155 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006156 }
6157 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006158 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006159 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006160 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006161 if( fd>=0 ){
6162 pFile->h = fd;
6163 }else{
drh9978c972010-02-23 17:36:32 +00006164 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006165 during locking */
6166 }
6167 }
6168 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6169 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6170 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6171 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6172 /* we couldn't create the proxy lock file with the old lock file path
6173 ** so try again via auto-naming
6174 */
6175 forceNewLockPath = 1;
6176 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006177 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006178 }
6179 }
6180 if( rc==SQLITE_OK ){
6181 /* Need to make a copy of path if we extracted the value
6182 ** from the conch file or the path was allocated on the stack
6183 */
6184 if( tempLockPath ){
6185 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6186 if( !pCtx->lockProxyPath ){
6187 rc = SQLITE_NOMEM;
6188 }
6189 }
6190 }
6191 if( rc==SQLITE_OK ){
6192 pCtx->conchHeld = 1;
6193
6194 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6195 afpLockingContext *afpCtx;
6196 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6197 afpCtx->dbPath = pCtx->lockProxyPath;
6198 }
6199 } else {
6200 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6201 }
drh308c2a52010-05-14 11:30:18 +00006202 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6203 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006204 return rc;
drh308c2a52010-05-14 11:30:18 +00006205 } while (1); /* in case we need to retry the :auto: lock file -
6206 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006207 }
6208}
6209
6210/*
6211** If pFile holds a lock on a conch file, then release that lock.
6212*/
6213static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006214 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006215 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6216 unixFile *conchFile; /* Name of the conch file */
6217
6218 pCtx = (proxyLockingContext *)pFile->lockingContext;
6219 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006220 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006221 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006222 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006223 if( pCtx->conchHeld>0 ){
6224 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6225 }
drh715ff302008-12-03 22:32:44 +00006226 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006227 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6228 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006229 return rc;
6230}
6231
6232/*
6233** Given the name of a database file, compute the name of its conch file.
6234** Store the conch filename in memory obtained from sqlite3_malloc().
6235** Make *pConchPath point to the new name. Return SQLITE_OK on success
6236** or SQLITE_NOMEM if unable to obtain memory.
6237**
6238** The caller is responsible for ensuring that the allocated memory
6239** space is eventually freed.
6240**
6241** *pConchPath is set to NULL if a memory allocation error occurs.
6242*/
6243static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6244 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006245 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006246 char *conchPath; /* buffer in which to construct conch name */
6247
6248 /* Allocate space for the conch filename and initialize the name to
6249 ** the name of the original database file. */
6250 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6251 if( conchPath==0 ){
6252 return SQLITE_NOMEM;
6253 }
6254 memcpy(conchPath, dbPath, len+1);
6255
6256 /* now insert a "." before the last / character */
6257 for( i=(len-1); i>=0; i-- ){
6258 if( conchPath[i]=='/' ){
6259 i++;
6260 break;
6261 }
6262 }
6263 conchPath[i]='.';
6264 while ( i<len ){
6265 conchPath[i+1]=dbPath[i];
6266 i++;
6267 }
6268
6269 /* append the "-conch" suffix to the file */
6270 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006271 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006272
6273 return SQLITE_OK;
6274}
6275
6276
6277/* Takes a fully configured proxy locking-style unix file and switches
6278** the local lock file path
6279*/
6280static int switchLockProxyPath(unixFile *pFile, const char *path) {
6281 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6282 char *oldPath = pCtx->lockProxyPath;
6283 int rc = SQLITE_OK;
6284
drh308c2a52010-05-14 11:30:18 +00006285 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006286 return SQLITE_BUSY;
6287 }
6288
6289 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6290 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6291 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6292 return SQLITE_OK;
6293 }else{
6294 unixFile *lockProxy = pCtx->lockProxy;
6295 pCtx->lockProxy=NULL;
6296 pCtx->conchHeld = 0;
6297 if( lockProxy!=NULL ){
6298 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6299 if( rc ) return rc;
6300 sqlite3_free(lockProxy);
6301 }
6302 sqlite3_free(oldPath);
6303 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6304 }
6305
6306 return rc;
6307}
6308
6309/*
6310** pFile is a file that has been opened by a prior xOpen call. dbPath
6311** is a string buffer at least MAXPATHLEN+1 characters in size.
6312**
6313** This routine find the filename associated with pFile and writes it
6314** int dbPath.
6315*/
6316static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006317#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006318 if( pFile->pMethod == &afpIoMethods ){
6319 /* afp style keeps a reference to the db path in the filePath field
6320 ** of the struct */
drhea678832008-12-10 19:26:22 +00006321 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006322 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6323 } else
drh715ff302008-12-03 22:32:44 +00006324#endif
6325 if( pFile->pMethod == &dotlockIoMethods ){
6326 /* dot lock style uses the locking context to store the dot lock
6327 ** file path */
6328 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6329 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6330 }else{
6331 /* all other styles use the locking context to store the db file path */
6332 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006333 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006334 }
6335 return SQLITE_OK;
6336}
6337
6338/*
6339** Takes an already filled in unix file and alters it so all file locking
6340** will be performed on the local proxy lock file. The following fields
6341** are preserved in the locking context so that they can be restored and
6342** the unix structure properly cleaned up at close time:
6343** ->lockingContext
6344** ->pMethod
6345*/
6346static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6347 proxyLockingContext *pCtx;
6348 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6349 char *lockPath=NULL;
6350 int rc = SQLITE_OK;
6351
drh308c2a52010-05-14 11:30:18 +00006352 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006353 return SQLITE_BUSY;
6354 }
6355 proxyGetDbPathForUnixFile(pFile, dbPath);
6356 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6357 lockPath=NULL;
6358 }else{
6359 lockPath=(char *)path;
6360 }
6361
drh308c2a52010-05-14 11:30:18 +00006362 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6363 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006364
6365 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6366 if( pCtx==0 ){
6367 return SQLITE_NOMEM;
6368 }
6369 memset(pCtx, 0, sizeof(*pCtx));
6370
6371 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6372 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006373 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6374 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6375 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6376 ** (c) the file system is read-only, then enable no-locking access.
6377 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6378 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6379 */
6380 struct statfs fsInfo;
6381 struct stat conchInfo;
6382 int goLockless = 0;
6383
drh99ab3b12011-03-02 15:09:07 +00006384 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006385 int err = errno;
6386 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6387 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6388 }
6389 }
6390 if( goLockless ){
6391 pCtx->conchHeld = -1; /* read only FS/ lockless */
6392 rc = SQLITE_OK;
6393 }
6394 }
drh715ff302008-12-03 22:32:44 +00006395 }
6396 if( rc==SQLITE_OK && lockPath ){
6397 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6398 }
6399
6400 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006401 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6402 if( pCtx->dbPath==NULL ){
6403 rc = SQLITE_NOMEM;
6404 }
6405 }
6406 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006407 /* all memory is allocated, proxys are created and assigned,
6408 ** switch the locking context and pMethod then return.
6409 */
drh715ff302008-12-03 22:32:44 +00006410 pCtx->oldLockingContext = pFile->lockingContext;
6411 pFile->lockingContext = pCtx;
6412 pCtx->pOldMethod = pFile->pMethod;
6413 pFile->pMethod = &proxyIoMethods;
6414 }else{
6415 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006416 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006417 sqlite3_free(pCtx->conchFile);
6418 }
drhd56b1212010-08-11 06:14:15 +00006419 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006420 sqlite3_free(pCtx->conchFilePath);
6421 sqlite3_free(pCtx);
6422 }
drh308c2a52010-05-14 11:30:18 +00006423 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6424 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006425 return rc;
6426}
6427
6428
6429/*
6430** This routine handles sqlite3_file_control() calls that are specific
6431** to proxy locking.
6432*/
6433static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6434 switch( op ){
6435 case SQLITE_GET_LOCKPROXYFILE: {
6436 unixFile *pFile = (unixFile*)id;
6437 if( pFile->pMethod == &proxyIoMethods ){
6438 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6439 proxyTakeConch(pFile);
6440 if( pCtx->lockProxyPath ){
6441 *(const char **)pArg = pCtx->lockProxyPath;
6442 }else{
6443 *(const char **)pArg = ":auto: (not held)";
6444 }
6445 } else {
6446 *(const char **)pArg = NULL;
6447 }
6448 return SQLITE_OK;
6449 }
6450 case SQLITE_SET_LOCKPROXYFILE: {
6451 unixFile *pFile = (unixFile*)id;
6452 int rc = SQLITE_OK;
6453 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6454 if( pArg==NULL || (const char *)pArg==0 ){
6455 if( isProxyStyle ){
6456 /* turn off proxy locking - not supported */
6457 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6458 }else{
6459 /* turn off proxy locking - already off - NOOP */
6460 rc = SQLITE_OK;
6461 }
6462 }else{
6463 const char *proxyPath = (const char *)pArg;
6464 if( isProxyStyle ){
6465 proxyLockingContext *pCtx =
6466 (proxyLockingContext*)pFile->lockingContext;
6467 if( !strcmp(pArg, ":auto:")
6468 || (pCtx->lockProxyPath &&
6469 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6470 ){
6471 rc = SQLITE_OK;
6472 }else{
6473 rc = switchLockProxyPath(pFile, proxyPath);
6474 }
6475 }else{
6476 /* turn on proxy file locking */
6477 rc = proxyTransformUnixFile(pFile, proxyPath);
6478 }
6479 }
6480 return rc;
6481 }
6482 default: {
6483 assert( 0 ); /* The call assures that only valid opcodes are sent */
6484 }
6485 }
6486 /*NOTREACHED*/
6487 return SQLITE_ERROR;
6488}
6489
6490/*
6491** Within this division (the proxying locking implementation) the procedures
6492** above this point are all utilities. The lock-related methods of the
6493** proxy-locking sqlite3_io_method object follow.
6494*/
6495
6496
6497/*
6498** This routine checks if there is a RESERVED lock held on the specified
6499** file by this or any other process. If such a lock is held, set *pResOut
6500** to a non-zero value otherwise *pResOut is set to zero. The return value
6501** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6502*/
6503static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6504 unixFile *pFile = (unixFile*)id;
6505 int rc = proxyTakeConch(pFile);
6506 if( rc==SQLITE_OK ){
6507 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006508 if( pCtx->conchHeld>0 ){
6509 unixFile *proxy = pCtx->lockProxy;
6510 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6511 }else{ /* conchHeld < 0 is lockless */
6512 pResOut=0;
6513 }
drh715ff302008-12-03 22:32:44 +00006514 }
6515 return rc;
6516}
6517
6518/*
drh308c2a52010-05-14 11:30:18 +00006519** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006520** of the following:
6521**
6522** (1) SHARED_LOCK
6523** (2) RESERVED_LOCK
6524** (3) PENDING_LOCK
6525** (4) EXCLUSIVE_LOCK
6526**
6527** Sometimes when requesting one lock state, additional lock states
6528** are inserted in between. The locking might fail on one of the later
6529** transitions leaving the lock state different from what it started but
6530** still short of its goal. The following chart shows the allowed
6531** transitions and the inserted intermediate states:
6532**
6533** UNLOCKED -> SHARED
6534** SHARED -> RESERVED
6535** SHARED -> (PENDING) -> EXCLUSIVE
6536** RESERVED -> (PENDING) -> EXCLUSIVE
6537** PENDING -> EXCLUSIVE
6538**
6539** This routine will only increase a lock. Use the sqlite3OsUnlock()
6540** routine to lower a locking level.
6541*/
drh308c2a52010-05-14 11:30:18 +00006542static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006543 unixFile *pFile = (unixFile*)id;
6544 int rc = proxyTakeConch(pFile);
6545 if( rc==SQLITE_OK ){
6546 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006547 if( pCtx->conchHeld>0 ){
6548 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006549 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6550 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006551 }else{
6552 /* conchHeld < 0 is lockless */
6553 }
drh715ff302008-12-03 22:32:44 +00006554 }
6555 return rc;
6556}
6557
6558
6559/*
drh308c2a52010-05-14 11:30:18 +00006560** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006561** must be either NO_LOCK or SHARED_LOCK.
6562**
6563** If the locking level of the file descriptor is already at or below
6564** the requested locking level, this routine is a no-op.
6565*/
drh308c2a52010-05-14 11:30:18 +00006566static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006567 unixFile *pFile = (unixFile*)id;
6568 int rc = proxyTakeConch(pFile);
6569 if( rc==SQLITE_OK ){
6570 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006571 if( pCtx->conchHeld>0 ){
6572 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006573 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6574 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006575 }else{
6576 /* conchHeld < 0 is lockless */
6577 }
drh715ff302008-12-03 22:32:44 +00006578 }
6579 return rc;
6580}
6581
6582/*
6583** Close a file that uses proxy locks.
6584*/
6585static int proxyClose(sqlite3_file *id) {
6586 if( id ){
6587 unixFile *pFile = (unixFile*)id;
6588 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6589 unixFile *lockProxy = pCtx->lockProxy;
6590 unixFile *conchFile = pCtx->conchFile;
6591 int rc = SQLITE_OK;
6592
6593 if( lockProxy ){
6594 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6595 if( rc ) return rc;
6596 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6597 if( rc ) return rc;
6598 sqlite3_free(lockProxy);
6599 pCtx->lockProxy = 0;
6600 }
6601 if( conchFile ){
6602 if( pCtx->conchHeld ){
6603 rc = proxyReleaseConch(pFile);
6604 if( rc ) return rc;
6605 }
6606 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6607 if( rc ) return rc;
6608 sqlite3_free(conchFile);
6609 }
drhd56b1212010-08-11 06:14:15 +00006610 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006611 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006612 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006613 /* restore the original locking context and pMethod then close it */
6614 pFile->lockingContext = pCtx->oldLockingContext;
6615 pFile->pMethod = pCtx->pOldMethod;
6616 sqlite3_free(pCtx);
6617 return pFile->pMethod->xClose(id);
6618 }
6619 return SQLITE_OK;
6620}
6621
6622
6623
drhd2cb50b2009-01-09 21:41:17 +00006624#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006625/*
6626** The proxy locking style is intended for use with AFP filesystems.
6627** And since AFP is only supported on MacOSX, the proxy locking is also
6628** restricted to MacOSX.
6629**
6630**
6631******************* End of the proxy lock implementation **********************
6632******************************************************************************/
6633
drh734c9862008-11-28 15:37:20 +00006634/*
danielk1977e339d652008-06-28 11:23:00 +00006635** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006636**
6637** This routine registers all VFS implementations for unix-like operating
6638** systems. This routine, and the sqlite3_os_end() routine that follows,
6639** should be the only routines in this file that are visible from other
6640** files.
drh6b9d6dd2008-12-03 19:34:47 +00006641**
6642** This routine is called once during SQLite initialization and by a
6643** single thread. The memory allocation and mutex subsystems have not
6644** necessarily been initialized when this routine is called, and so they
6645** should not be used.
drh153c62c2007-08-24 03:51:33 +00006646*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006647int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006648 /*
6649 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006650 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6651 ** to the "finder" function. (pAppData is a pointer to a pointer because
6652 ** silly C90 rules prohibit a void* from being cast to a function pointer
6653 ** and so we have to go through the intermediate pointer to avoid problems
6654 ** when compiling with -pedantic-errors on GCC.)
6655 **
6656 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006657 ** finder-function. The finder-function returns a pointer to the
6658 ** sqlite_io_methods object that implements the desired locking
6659 ** behaviors. See the division above that contains the IOMETHODS
6660 ** macro for addition information on finder-functions.
6661 **
6662 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6663 ** object. But the "autolockIoFinder" available on MacOSX does a little
6664 ** more than that; it looks at the filesystem type that hosts the
6665 ** database file and tries to choose an locking method appropriate for
6666 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006667 */
drh7708e972008-11-29 00:56:52 +00006668 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006669 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006670 sizeof(unixFile), /* szOsFile */ \
6671 MAX_PATHNAME, /* mxPathname */ \
6672 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006673 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006674 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006675 unixOpen, /* xOpen */ \
6676 unixDelete, /* xDelete */ \
6677 unixAccess, /* xAccess */ \
6678 unixFullPathname, /* xFullPathname */ \
6679 unixDlOpen, /* xDlOpen */ \
6680 unixDlError, /* xDlError */ \
6681 unixDlSym, /* xDlSym */ \
6682 unixDlClose, /* xDlClose */ \
6683 unixRandomness, /* xRandomness */ \
6684 unixSleep, /* xSleep */ \
6685 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006686 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006687 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006688 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006689 unixGetSystemCall, /* xGetSystemCall */ \
6690 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006691 }
6692
drh6b9d6dd2008-12-03 19:34:47 +00006693 /*
6694 ** All default VFSes for unix are contained in the following array.
6695 **
6696 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6697 ** by the SQLite core when the VFS is registered. So the following
6698 ** array cannot be const.
6699 */
danielk1977e339d652008-06-28 11:23:00 +00006700 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006701#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006702 UNIXVFS("unix", autolockIoFinder ),
6703#else
6704 UNIXVFS("unix", posixIoFinder ),
6705#endif
6706 UNIXVFS("unix-none", nolockIoFinder ),
6707 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006708 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006709#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006710 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006711#endif
6712#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006713 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006714#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006715 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006716#endif
chw78a13182009-04-07 05:35:03 +00006717#endif
drhd2cb50b2009-01-09 21:41:17 +00006718#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006719 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006720 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006721 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006722#endif
drh153c62c2007-08-24 03:51:33 +00006723 };
drh6b9d6dd2008-12-03 19:34:47 +00006724 unsigned int i; /* Loop counter */
6725
drh2aa5a002011-04-13 13:42:25 +00006726 /* Double-check that the aSyscall[] array has been constructed
6727 ** correctly. See ticket [bb3a86e890c8e96ab] */
6728 assert( ArraySize(aSyscall)==16 );
6729
drh6b9d6dd2008-12-03 19:34:47 +00006730 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006731 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006732 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006733 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006734 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006735}
danielk1977e339d652008-06-28 11:23:00 +00006736
6737/*
drh6b9d6dd2008-12-03 19:34:47 +00006738** Shutdown the operating system interface.
6739**
6740** Some operating systems might need to do some cleanup in this routine,
6741** to release dynamically allocated objects. But not on unix.
6742** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006743*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006744int sqlite3_os_end(void){
6745 return SQLITE_OK;
6746}
drhdce8bdb2007-08-16 13:01:44 +00006747
danielk197729bafea2008-06-26 10:41:19 +00006748#endif /* SQLITE_OS_UNIX */