blob: 682e74c958a0ebef77bda6ffe67d5877eb06df3d [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:
680 case ESTALE:
681 case ENOSYS:
682 /* these should force the client to close the file and reconnect */
683
684 default:
685 return sqliteIOErr;
686 }
687}
688
689
690
691/******************************************************************************
692****************** Begin Unique File ID Utility Used By VxWorks ***************
693**
694** On most versions of unix, we can get a unique ID for a file by concatenating
695** the device number and the inode number. But this does not work on VxWorks.
696** On VxWorks, a unique file id must be based on the canonical filename.
697**
698** A pointer to an instance of the following structure can be used as a
699** unique file ID in VxWorks. Each instance of this structure contains
700** a copy of the canonical filename. There is also a reference count.
701** The structure is reclaimed when the number of pointers to it drops to
702** zero.
703**
704** There are never very many files open at one time and lookups are not
705** a performance-critical path, so it is sufficient to put these
706** structures on a linked list.
707*/
708struct vxworksFileId {
709 struct vxworksFileId *pNext; /* Next in a list of them all */
710 int nRef; /* Number of references to this one */
711 int nName; /* Length of the zCanonicalName[] string */
712 char *zCanonicalName; /* Canonical filename */
713};
714
715#if OS_VXWORKS
716/*
drh9b35ea62008-11-29 02:20:26 +0000717** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000718** variable:
719*/
720static struct vxworksFileId *vxworksFileList = 0;
721
722/*
723** Simplify a filename into its canonical form
724** by making the following changes:
725**
726** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000727** * convert /./ into just /
728** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000729**
730** Changes are made in-place. Return the new name length.
731**
732** The original filename is in z[0..n-1]. Return the number of
733** characters in the simplified name.
734*/
735static int vxworksSimplifyName(char *z, int n){
736 int i, j;
737 while( n>1 && z[n-1]=='/' ){ n--; }
738 for(i=j=0; i<n; i++){
739 if( z[i]=='/' ){
740 if( z[i+1]=='/' ) continue;
741 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
742 i += 1;
743 continue;
744 }
745 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
746 while( j>0 && z[j-1]!='/' ){ j--; }
747 if( j>0 ){ j--; }
748 i += 2;
749 continue;
750 }
751 }
752 z[j++] = z[i];
753 }
754 z[j] = 0;
755 return j;
756}
757
758/*
759** Find a unique file ID for the given absolute pathname. Return
760** a pointer to the vxworksFileId object. This pointer is the unique
761** file ID.
762**
763** The nRef field of the vxworksFileId object is incremented before
764** the object is returned. A new vxworksFileId object is created
765** and added to the global list if necessary.
766**
767** If a memory allocation error occurs, return NULL.
768*/
769static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
770 struct vxworksFileId *pNew; /* search key and new file ID */
771 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
772 int n; /* Length of zAbsoluteName string */
773
774 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000775 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000776 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
777 if( pNew==0 ) return 0;
778 pNew->zCanonicalName = (char*)&pNew[1];
779 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
780 n = vxworksSimplifyName(pNew->zCanonicalName, n);
781
782 /* Search for an existing entry that matching the canonical name.
783 ** If found, increment the reference count and return a pointer to
784 ** the existing file ID.
785 */
786 unixEnterMutex();
787 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
788 if( pCandidate->nName==n
789 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
790 ){
791 sqlite3_free(pNew);
792 pCandidate->nRef++;
793 unixLeaveMutex();
794 return pCandidate;
795 }
796 }
797
798 /* No match was found. We will make a new file ID */
799 pNew->nRef = 1;
800 pNew->nName = n;
801 pNew->pNext = vxworksFileList;
802 vxworksFileList = pNew;
803 unixLeaveMutex();
804 return pNew;
805}
806
807/*
808** Decrement the reference count on a vxworksFileId object. Free
809** the object when the reference count reaches zero.
810*/
811static void vxworksReleaseFileId(struct vxworksFileId *pId){
812 unixEnterMutex();
813 assert( pId->nRef>0 );
814 pId->nRef--;
815 if( pId->nRef==0 ){
816 struct vxworksFileId **pp;
817 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
818 assert( *pp==pId );
819 *pp = pId->pNext;
820 sqlite3_free(pId);
821 }
822 unixLeaveMutex();
823}
824#endif /* OS_VXWORKS */
825/*************** End of Unique File ID Utility Used By VxWorks ****************
826******************************************************************************/
827
828
829/******************************************************************************
830*************************** Posix Advisory Locking ****************************
831**
drh9b35ea62008-11-29 02:20:26 +0000832** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000833** section 6.5.2.2 lines 483 through 490 specify that when a process
834** sets or clears a lock, that operation overrides any prior locks set
835** by the same process. It does not explicitly say so, but this implies
836** that it overrides locks set by the same process using a different
837** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000838**
839** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000840** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
841**
842** Suppose ./file1 and ./file2 are really the same file (because
843** one is a hard or symbolic link to the other) then if you set
844** an exclusive lock on fd1, then try to get an exclusive lock
845** on fd2, it works. I would have expected the second lock to
846** fail since there was already a lock on the file due to fd1.
847** But not so. Since both locks came from the same process, the
848** second overrides the first, even though they were on different
849** file descriptors opened on different file names.
850**
drh734c9862008-11-28 15:37:20 +0000851** This means that we cannot use POSIX locks to synchronize file access
852** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000853** to synchronize access for threads in separate processes, but not
854** threads within the same process.
855**
856** To work around the problem, SQLite has to manage file locks internally
857** on its own. Whenever a new database is opened, we have to find the
858** specific inode of the database file (the inode is determined by the
859** st_dev and st_ino fields of the stat structure that fstat() fills in)
860** and check for locks already existing on that inode. When locks are
861** created or removed, we have to look at our own internal record of the
862** locks to see if another thread has previously set a lock on that same
863** inode.
864**
drh9b35ea62008-11-29 02:20:26 +0000865** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
866** For VxWorks, we have to use the alternative unique ID system based on
867** canonical filename and implemented in the previous division.)
868**
danielk1977ad94b582007-08-20 06:44:22 +0000869** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000870** descriptor. It is now a structure that holds the integer file
871** descriptor and a pointer to a structure that describes the internal
872** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000873** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000874** point to the same locking structure. The locking structure keeps
875** a reference count (so we will know when to delete it) and a "cnt"
876** field that tells us its internal lock status. cnt==0 means the
877** file is unlocked. cnt==-1 means the file has an exclusive lock.
878** cnt>0 means there are cnt shared locks on the file.
879**
880** Any attempt to lock or unlock a file first checks the locking
881** structure. The fcntl() system call is only invoked to set a
882** POSIX lock if the internal lock structure transitions between
883** a locked and an unlocked state.
884**
drh734c9862008-11-28 15:37:20 +0000885** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000886**
887** If you close a file descriptor that points to a file that has locks,
888** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000889** released. To work around this problem, each unixInodeInfo object
890** maintains a count of the number of pending locks on tha inode.
891** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000892** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000893** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000894** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000895** be closed and that list is walked (and cleared) when the last lock
896** clears.
897**
drh9b35ea62008-11-29 02:20:26 +0000898** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000899**
drh9b35ea62008-11-29 02:20:26 +0000900** Many older versions of linux use the LinuxThreads library which is
901** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000902** A cannot be modified or overridden by a different thread B.
903** Only thread A can modify the lock. Locking behavior is correct
904** if the appliation uses the newer Native Posix Thread Library (NPTL)
905** on linux - with NPTL a lock created by thread A can override locks
906** in thread B. But there is no way to know at compile-time which
907** threading library is being used. So there is no way to know at
908** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000909** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000910** current process.
drh5fdae772004-06-29 03:29:00 +0000911**
drh8af6c222010-05-14 12:43:01 +0000912** SQLite used to support LinuxThreads. But support for LinuxThreads
913** was dropped beginning with version 3.7.0. SQLite will still work with
914** LinuxThreads provided that (1) there is no more than one connection
915** per database file in the same process and (2) database connections
916** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000917*/
918
919/*
920** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000921** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000922*/
923struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000924 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000925#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000926 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000927#else
drh107886a2008-11-21 22:21:50 +0000928 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000929#endif
930};
931
932/*
drhbbd42a62004-05-22 17:41:58 +0000933** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000934** inode. Or, on LinuxThreads, there is one of these structures for
935** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000936**
danielk1977ad94b582007-08-20 06:44:22 +0000937** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000938** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000939** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000940*/
drh8af6c222010-05-14 12:43:01 +0000941struct unixInodeInfo {
942 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000943 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000944 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
945 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000946 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000947 unixShmNode *pShmNode; /* Shared memory associated with this inode */
948 int nLock; /* Number of outstanding file locks */
949 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
950 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
951 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000952#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000953 unsigned long long sharedByte; /* for AFP simulated shared lock */
954#endif
drh6c7d5c52008-11-21 20:32:33 +0000955#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000956 sem_t *pSem; /* Named POSIX semaphore */
957 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000958#endif
drhbbd42a62004-05-22 17:41:58 +0000959};
960
drhda0e7682008-07-30 15:27:54 +0000961/*
drh8af6c222010-05-14 12:43:01 +0000962** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000963*/
drhd91c68f2010-05-14 14:52:25 +0000964static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000965
drh5fdae772004-06-29 03:29:00 +0000966/*
dane18d4952011-02-21 11:46:24 +0000967**
968** This function - unixLogError_x(), is only ever called via the macro
969** unixLogError().
970**
971** It is invoked after an error occurs in an OS function and errno has been
972** set. It logs a message using sqlite3_log() containing the current value of
973** errno and, if possible, the human-readable equivalent from strerror() or
974** strerror_r().
975**
976** The first argument passed to the macro should be the error code that
977** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
978** The two subsequent arguments should be the name of the OS function that
979** failed (e.g. "unlink", "open") and the the associated file-system path,
980** if any.
981*/
drh0e9365c2011-03-02 02:08:13 +0000982#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
983static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000984 int errcode, /* SQLite error code */
985 const char *zFunc, /* Name of OS function that failed */
986 const char *zPath, /* File path associated with error */
987 int iLine /* Source line number where error occurred */
988){
989 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000990 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000991
992 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
993 ** the strerror() function to obtain the human-readable error message
994 ** equivalent to errno. Otherwise, use strerror_r().
995 */
996#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
997 char aErr[80];
998 memset(aErr, 0, sizeof(aErr));
999 zErr = aErr;
1000
1001 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1002 ** assume that the system provides the the GNU version of strerror_r() that
1003 ** returns a pointer to a buffer containing the error message. That pointer
1004 ** may point to aErr[], or it may point to some static storage somewhere.
1005 ** Otherwise, assume that the system provides the POSIX version of
1006 ** strerror_r(), which always writes an error message into aErr[].
1007 **
1008 ** If the code incorrectly assumes that it is the POSIX version that is
1009 ** available, the error message will often be an empty string. Not a
1010 ** huge problem. Incorrectly concluding that the GNU version is available
1011 ** could lead to a segfault though.
1012 */
1013#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1014 zErr =
1015# endif
drh0e9365c2011-03-02 02:08:13 +00001016 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001017
1018#elif SQLITE_THREADSAFE
1019 /* This is a threadsafe build, but strerror_r() is not available. */
1020 zErr = "";
1021#else
1022 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001023 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001024#endif
1025
1026 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001027 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001028 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001029 "os_unix.c:%d: (%d) %s(%s) - %s",
1030 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001031 );
1032
1033 return errcode;
1034}
1035
drh0e9365c2011-03-02 02:08:13 +00001036/*
1037** Close a file descriptor.
1038**
1039** We assume that close() almost always works, since it is only in a
1040** very sick application or on a very sick platform that it might fail.
1041** If it does fail, simply leak the file descriptor, but do log the
1042** error.
1043**
1044** Note that it is not safe to retry close() after EINTR since the
1045** file descriptor might have already been reused by another thread.
1046** So we don't even try to recover from an EINTR. Just log the error
1047** and move on.
1048*/
1049static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001050 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001051 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1052 pFile ? pFile->zPath : 0, lineno);
1053 }
1054}
dane18d4952011-02-21 11:46:24 +00001055
1056/*
danb0ac3e32010-06-16 10:55:42 +00001057** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001058*/
drh0e9365c2011-03-02 02:08:13 +00001059static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001060 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001061 UnixUnusedFd *p;
1062 UnixUnusedFd *pNext;
1063 for(p=pInode->pUnused; p; p=pNext){
1064 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001065 robust_close(pFile, p->fd, __LINE__);
1066 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001067 }
drh0e9365c2011-03-02 02:08:13 +00001068 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001069}
1070
1071/*
drh8af6c222010-05-14 12:43:01 +00001072** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001073**
1074** The mutex entered using the unixEnterMutex() function must be held
1075** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001076*/
danb0ac3e32010-06-16 10:55:42 +00001077static void releaseInodeInfo(unixFile *pFile){
1078 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001079 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001080 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001081 pInode->nRef--;
1082 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001083 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001084 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001085 if( pInode->pPrev ){
1086 assert( pInode->pPrev->pNext==pInode );
1087 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001088 }else{
drh8af6c222010-05-14 12:43:01 +00001089 assert( inodeList==pInode );
1090 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001091 }
drh8af6c222010-05-14 12:43:01 +00001092 if( pInode->pNext ){
1093 assert( pInode->pNext->pPrev==pInode );
1094 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001095 }
drh8af6c222010-05-14 12:43:01 +00001096 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001097 }
drhbbd42a62004-05-22 17:41:58 +00001098 }
1099}
1100
1101/*
drh8af6c222010-05-14 12:43:01 +00001102** Given a file descriptor, locate the unixInodeInfo object that
1103** describes that file descriptor. Create a new one if necessary. The
1104** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001105**
dan9359c7b2009-08-21 08:29:10 +00001106** The mutex entered using the unixEnterMutex() function must be held
1107** when this function is called.
1108**
drh6c7d5c52008-11-21 20:32:33 +00001109** Return an appropriate error code.
1110*/
drh8af6c222010-05-14 12:43:01 +00001111static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001112 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001113 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001114){
1115 int rc; /* System call return code */
1116 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001117 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1118 struct stat statbuf; /* Low-level file information */
1119 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001120
dan9359c7b2009-08-21 08:29:10 +00001121 assert( unixMutexHeld() );
1122
drh6c7d5c52008-11-21 20:32:33 +00001123 /* Get low-level information about the file that we can used to
1124 ** create a unique name for the file.
1125 */
1126 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001127 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001128 if( rc!=0 ){
1129 pFile->lastErrno = errno;
1130#ifdef EOVERFLOW
1131 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1132#endif
1133 return SQLITE_IOERR;
1134 }
1135
drheb0d74f2009-02-03 15:27:02 +00001136#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001137 /* On OS X on an msdos filesystem, the inode number is reported
1138 ** incorrectly for zero-size files. See ticket #3260. To work
1139 ** around this problem (we consider it a bug in OS X, not SQLite)
1140 ** we always increase the file size to 1 by writing a single byte
1141 ** prior to accessing the inode number. The one byte written is
1142 ** an ASCII 'S' character which also happens to be the first byte
1143 ** in the header of every SQLite database. In this way, if there
1144 ** is a race condition such that another thread has already populated
1145 ** the first page of the database, no damage is done.
1146 */
drh7ed97b92010-01-20 13:07:21 +00001147 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001148 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001149 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001150 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001151 return SQLITE_IOERR;
1152 }
drh99ab3b12011-03-02 15:09:07 +00001153 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001154 if( rc!=0 ){
1155 pFile->lastErrno = errno;
1156 return SQLITE_IOERR;
1157 }
1158 }
drheb0d74f2009-02-03 15:27:02 +00001159#endif
drh6c7d5c52008-11-21 20:32:33 +00001160
drh8af6c222010-05-14 12:43:01 +00001161 memset(&fileId, 0, sizeof(fileId));
1162 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001163#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001164 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001165#else
drh8af6c222010-05-14 12:43:01 +00001166 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001167#endif
drh8af6c222010-05-14 12:43:01 +00001168 pInode = inodeList;
1169 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1170 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001171 }
drh8af6c222010-05-14 12:43:01 +00001172 if( pInode==0 ){
1173 pInode = sqlite3_malloc( sizeof(*pInode) );
1174 if( pInode==0 ){
1175 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001176 }
drh8af6c222010-05-14 12:43:01 +00001177 memset(pInode, 0, sizeof(*pInode));
1178 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1179 pInode->nRef = 1;
1180 pInode->pNext = inodeList;
1181 pInode->pPrev = 0;
1182 if( inodeList ) inodeList->pPrev = pInode;
1183 inodeList = pInode;
1184 }else{
1185 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001186 }
drh8af6c222010-05-14 12:43:01 +00001187 *ppInode = pInode;
1188 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001189}
drh6c7d5c52008-11-21 20:32:33 +00001190
aswift5b1a2562008-08-22 00:22:35 +00001191
1192/*
danielk197713adf8a2004-06-03 16:08:41 +00001193** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001194** file by this or any other process. If such a lock is held, set *pResOut
1195** to a non-zero value otherwise *pResOut is set to zero. The return value
1196** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001197*/
danielk1977861f7452008-06-05 11:39:11 +00001198static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001199 int rc = SQLITE_OK;
1200 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001201 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001202
danielk1977861f7452008-06-05 11:39:11 +00001203 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1204
drh054889e2005-11-30 03:20:31 +00001205 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001206 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001207
1208 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001209 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001210 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001211 }
1212
drh2ac3ee92004-06-07 16:27:46 +00001213 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001214 */
danielk197709480a92009-02-09 05:32:32 +00001215#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001216 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001217 struct flock lock;
1218 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001219 lock.l_start = RESERVED_BYTE;
1220 lock.l_len = 1;
1221 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001222 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1223 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1224 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001225 } else if( lock.l_type!=F_UNLCK ){
1226 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001227 }
1228 }
danielk197709480a92009-02-09 05:32:32 +00001229#endif
danielk197713adf8a2004-06-03 16:08:41 +00001230
drh6c7d5c52008-11-21 20:32:33 +00001231 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001232 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001233
aswift5b1a2562008-08-22 00:22:35 +00001234 *pResOut = reserved;
1235 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001236}
1237
1238/*
drha7e61d82011-03-12 17:02:57 +00001239** Attempt to set a system-lock on the file pFile. The lock is
1240** described by pLock.
1241**
drh77197112011-03-15 19:08:48 +00001242** If the pFile was opened read/write from unix-excl, then the only lock
1243** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001244** the first time any lock is attempted. All subsequent system locking
1245** operations become no-ops. Locking operations still happen internally,
1246** in order to coordinate access between separate database connections
1247** within this process, but all of that is handled in memory and the
1248** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001249**
1250** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1251** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1252** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001253**
1254** Zero is returned if the call completes successfully, or -1 if a call
1255** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001256*/
1257static int unixFileLock(unixFile *pFile, struct flock *pLock){
1258 int rc;
drh3cb93392011-03-12 18:10:44 +00001259 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001260 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001261 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001262 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1263 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1264 ){
drh3cb93392011-03-12 18:10:44 +00001265 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001266 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001267 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001268 lock.l_whence = SEEK_SET;
1269 lock.l_start = SHARED_FIRST;
1270 lock.l_len = SHARED_SIZE;
1271 lock.l_type = F_WRLCK;
1272 rc = osFcntl(pFile->h, F_SETLK, &lock);
1273 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001274 pInode->bProcessLock = 1;
1275 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001276 }else{
1277 rc = 0;
1278 }
1279 }else{
1280 rc = osFcntl(pFile->h, F_SETLK, pLock);
1281 }
1282 return rc;
1283}
1284
1285/*
drh308c2a52010-05-14 11:30:18 +00001286** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001287** of the following:
1288**
drh2ac3ee92004-06-07 16:27:46 +00001289** (1) SHARED_LOCK
1290** (2) RESERVED_LOCK
1291** (3) PENDING_LOCK
1292** (4) EXCLUSIVE_LOCK
1293**
drhb3e04342004-06-08 00:47:47 +00001294** Sometimes when requesting one lock state, additional lock states
1295** are inserted in between. The locking might fail on one of the later
1296** transitions leaving the lock state different from what it started but
1297** still short of its goal. The following chart shows the allowed
1298** transitions and the inserted intermediate states:
1299**
1300** UNLOCKED -> SHARED
1301** SHARED -> RESERVED
1302** SHARED -> (PENDING) -> EXCLUSIVE
1303** RESERVED -> (PENDING) -> EXCLUSIVE
1304** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001305**
drha6abd042004-06-09 17:37:22 +00001306** This routine will only increase a lock. Use the sqlite3OsUnlock()
1307** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001308*/
drh308c2a52010-05-14 11:30:18 +00001309static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001310 /* The following describes the implementation of the various locks and
1311 ** lock transitions in terms of the POSIX advisory shared and exclusive
1312 ** lock primitives (called read-locks and write-locks below, to avoid
1313 ** confusion with SQLite lock names). The algorithms are complicated
1314 ** slightly in order to be compatible with windows systems simultaneously
1315 ** accessing the same database file, in case that is ever required.
1316 **
1317 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1318 ** byte', each single bytes at well known offsets, and the 'shared byte
1319 ** range', a range of 510 bytes at a well known offset.
1320 **
1321 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1322 ** byte'. If this is successful, a random byte from the 'shared byte
1323 ** range' is read-locked and the lock on the 'pending byte' released.
1324 **
danielk197790ba3bd2004-06-25 08:32:25 +00001325 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1326 ** A RESERVED lock is implemented by grabbing a write-lock on the
1327 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001328 **
1329 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001330 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1331 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1332 ** obtained, but existing SHARED locks are allowed to persist. A process
1333 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1334 ** This property is used by the algorithm for rolling back a journal file
1335 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001336 **
danielk197790ba3bd2004-06-25 08:32:25 +00001337 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1338 ** implemented by obtaining a write-lock on the entire 'shared byte
1339 ** range'. Since all other locks require a read-lock on one of the bytes
1340 ** within this range, this ensures that no other locks are held on the
1341 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001342 **
1343 ** The reason a single byte cannot be used instead of the 'shared byte
1344 ** range' is that some versions of windows do not support read-locks. By
1345 ** locking a random byte from a range, concurrent SHARED locks may exist
1346 ** even if the locking primitive used is always a write-lock.
1347 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001348 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001349 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001350 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001351 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001352 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001353
drh054889e2005-11-30 03:20:31 +00001354 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001355 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1356 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001357 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001358
1359 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001360 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001361 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001362 */
drh308c2a52010-05-14 11:30:18 +00001363 if( pFile->eFileLock>=eFileLock ){
1364 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1365 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001366 return SQLITE_OK;
1367 }
1368
drh0c2694b2009-09-03 16:23:44 +00001369 /* Make sure the locking sequence is correct.
1370 ** (1) We never move from unlocked to anything higher than shared lock.
1371 ** (2) SQLite never explicitly requests a pendig lock.
1372 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001373 */
drh308c2a52010-05-14 11:30:18 +00001374 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1375 assert( eFileLock!=PENDING_LOCK );
1376 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001377
drh8af6c222010-05-14 12:43:01 +00001378 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001379 */
drh6c7d5c52008-11-21 20:32:33 +00001380 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001381 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001382
danielk1977ad94b582007-08-20 06:44:22 +00001383 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001384 ** handle that precludes the requested lock, return BUSY.
1385 */
drh8af6c222010-05-14 12:43:01 +00001386 if( (pFile->eFileLock!=pInode->eFileLock &&
1387 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001388 ){
1389 rc = SQLITE_BUSY;
1390 goto end_lock;
1391 }
1392
1393 /* If a SHARED lock is requested, and some thread using this PID already
1394 ** has a SHARED or RESERVED lock, then increment reference counts and
1395 ** return SQLITE_OK.
1396 */
drh308c2a52010-05-14 11:30:18 +00001397 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001398 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001399 assert( eFileLock==SHARED_LOCK );
1400 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001401 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001402 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001403 pInode->nShared++;
1404 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001405 goto end_lock;
1406 }
1407
danielk19779a1d0ab2004-06-01 14:09:28 +00001408
drh3cde3bb2004-06-12 02:17:14 +00001409 /* A PENDING lock is needed before acquiring a SHARED lock and before
1410 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1411 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001412 */
drh0c2694b2009-09-03 16:23:44 +00001413 lock.l_len = 1L;
1414 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001415 if( eFileLock==SHARED_LOCK
1416 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001417 ){
drh308c2a52010-05-14 11:30:18 +00001418 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001419 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001420 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001421 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001422 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001423 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001424 pFile->lastErrno = tErrno;
1425 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001426 goto end_lock;
1427 }
drh3cde3bb2004-06-12 02:17:14 +00001428 }
1429
1430
1431 /* If control gets to this point, then actually go ahead and make
1432 ** operating system calls for the specified lock.
1433 */
drh308c2a52010-05-14 11:30:18 +00001434 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001435 assert( pInode->nShared==0 );
1436 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001437 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001438
drh2ac3ee92004-06-07 16:27:46 +00001439 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001440 lock.l_start = SHARED_FIRST;
1441 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001442 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001443 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001444 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001445 }
dan661d71a2011-03-30 19:08:03 +00001446
drh2ac3ee92004-06-07 16:27:46 +00001447 /* Drop the temporary PENDING lock */
1448 lock.l_start = PENDING_BYTE;
1449 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001450 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001451 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1452 /* This could happen with a network mount */
1453 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001454 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001455 }
dan661d71a2011-03-30 19:08:03 +00001456
1457 if( rc ){
1458 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001459 pFile->lastErrno = tErrno;
1460 }
dan661d71a2011-03-30 19:08:03 +00001461 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001462 }else{
drh308c2a52010-05-14 11:30:18 +00001463 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001464 pInode->nLock++;
1465 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001466 }
drh8af6c222010-05-14 12:43:01 +00001467 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001468 /* We are trying for an exclusive lock but another thread in this
1469 ** same process is still holding a shared lock. */
1470 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001471 }else{
drh3cde3bb2004-06-12 02:17:14 +00001472 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001473 ** assumed that there is a SHARED or greater lock on the file
1474 ** already.
1475 */
drh308c2a52010-05-14 11:30:18 +00001476 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001477 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001478
1479 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1480 if( eFileLock==RESERVED_LOCK ){
1481 lock.l_start = RESERVED_BYTE;
1482 lock.l_len = 1L;
1483 }else{
1484 lock.l_start = SHARED_FIRST;
1485 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001486 }
dan661d71a2011-03-30 19:08:03 +00001487
1488 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001489 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001490 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001491 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001492 pFile->lastErrno = tErrno;
1493 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001494 }
drhbbd42a62004-05-22 17:41:58 +00001495 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001496
drh8f941bc2009-01-14 23:03:40 +00001497
1498#ifndef NDEBUG
1499 /* Set up the transaction-counter change checking flags when
1500 ** transitioning from a SHARED to a RESERVED lock. The change
1501 ** from SHARED to RESERVED marks the beginning of a normal
1502 ** write operation (not a hot journal rollback).
1503 */
1504 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001505 && pFile->eFileLock<=SHARED_LOCK
1506 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001507 ){
1508 pFile->transCntrChng = 0;
1509 pFile->dbUpdate = 0;
1510 pFile->inNormalWrite = 1;
1511 }
1512#endif
1513
1514
danielk1977ecb2a962004-06-02 06:30:16 +00001515 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001516 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001517 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001518 }else if( eFileLock==EXCLUSIVE_LOCK ){
1519 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001520 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001521 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001522
1523end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001524 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001525 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1526 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001527 return rc;
1528}
1529
1530/*
dan08da86a2009-08-21 17:18:03 +00001531** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001532** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001533*/
1534static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001535 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001536 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001537 p->pNext = pInode->pUnused;
1538 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001539 pFile->h = -1;
1540 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001541}
1542
1543/*
drh308c2a52010-05-14 11:30:18 +00001544** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001545** must be either NO_LOCK or SHARED_LOCK.
1546**
1547** If the locking level of the file descriptor is already at or below
1548** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001549**
1550** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1551** the byte range is divided into 2 parts and the first part is unlocked then
1552** set to a read lock, then the other part is simply unlocked. This works
1553** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1554** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001555*/
drha7e61d82011-03-12 17:02:57 +00001556static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001557 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001558 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001559 struct flock lock;
1560 int rc = SQLITE_OK;
1561 int h;
drha6abd042004-06-09 17:37:22 +00001562
drh054889e2005-11-30 03:20:31 +00001563 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001564 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001565 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001566 getpid()));
drha6abd042004-06-09 17:37:22 +00001567
drh308c2a52010-05-14 11:30:18 +00001568 assert( eFileLock<=SHARED_LOCK );
1569 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001570 return SQLITE_OK;
1571 }
drh6c7d5c52008-11-21 20:32:33 +00001572 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001573 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001574 pInode = pFile->pInode;
1575 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001576 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001577 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001578 SimulateIOErrorBenign(1);
1579 SimulateIOError( h=(-1) )
1580 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001581
1582#ifndef NDEBUG
1583 /* When reducing a lock such that other processes can start
1584 ** reading the database file again, make sure that the
1585 ** transaction counter was updated if any part of the database
1586 ** file changed. If the transaction counter is not updated,
1587 ** other connections to the same file might not realize that
1588 ** the file has changed and hence might not know to flush their
1589 ** cache. The use of a stale cache can lead to database corruption.
1590 */
dan7c246102010-04-12 19:00:29 +00001591#if 0
drh8f941bc2009-01-14 23:03:40 +00001592 assert( pFile->inNormalWrite==0
1593 || pFile->dbUpdate==0
1594 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001595#endif
drh8f941bc2009-01-14 23:03:40 +00001596 pFile->inNormalWrite = 0;
1597#endif
1598
drh7ed97b92010-01-20 13:07:21 +00001599 /* downgrading to a shared lock on NFS involves clearing the write lock
1600 ** before establishing the readlock - to avoid a race condition we downgrade
1601 ** the lock in 2 blocks, so that part of the range will be covered by a
1602 ** write lock until the rest is covered by a read lock:
1603 ** 1: [WWWWW]
1604 ** 2: [....W]
1605 ** 3: [RRRRW]
1606 ** 4: [RRRR.]
1607 */
drh308c2a52010-05-14 11:30:18 +00001608 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001609
1610#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001611 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001612 assert( handleNFSUnlock==0 );
1613#endif
1614#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001615 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001616 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001617 off_t divSize = SHARED_SIZE - 1;
1618
1619 lock.l_type = F_UNLCK;
1620 lock.l_whence = SEEK_SET;
1621 lock.l_start = SHARED_FIRST;
1622 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001623 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001624 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001625 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001626 if( IS_LOCK_ERROR(rc) ){
1627 pFile->lastErrno = tErrno;
1628 }
1629 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001630 }
drh7ed97b92010-01-20 13:07:21 +00001631 lock.l_type = F_RDLCK;
1632 lock.l_whence = SEEK_SET;
1633 lock.l_start = SHARED_FIRST;
1634 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001635 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001636 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001637 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1638 if( IS_LOCK_ERROR(rc) ){
1639 pFile->lastErrno = tErrno;
1640 }
1641 goto end_unlock;
1642 }
1643 lock.l_type = F_UNLCK;
1644 lock.l_whence = SEEK_SET;
1645 lock.l_start = SHARED_FIRST+divSize;
1646 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001647 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001648 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001649 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001650 if( IS_LOCK_ERROR(rc) ){
1651 pFile->lastErrno = tErrno;
1652 }
1653 goto end_unlock;
1654 }
drh30f776f2011-02-25 03:25:07 +00001655 }else
1656#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1657 {
drh7ed97b92010-01-20 13:07:21 +00001658 lock.l_type = F_RDLCK;
1659 lock.l_whence = SEEK_SET;
1660 lock.l_start = SHARED_FIRST;
1661 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001662 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001663 /* In theory, the call to unixFileLock() cannot fail because another
1664 ** process is holding an incompatible lock. If it does, this
1665 ** indicates that the other process is not following the locking
1666 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1667 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1668 ** an assert to fail). */
1669 rc = SQLITE_IOERR_RDLOCK;
1670 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001671 goto end_unlock;
1672 }
drh9c105bb2004-10-02 20:38:28 +00001673 }
1674 }
drhbbd42a62004-05-22 17:41:58 +00001675 lock.l_type = F_UNLCK;
1676 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001677 lock.l_start = PENDING_BYTE;
1678 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001679 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001680 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001681 }else{
danea83bc62011-04-01 11:56:32 +00001682 rc = SQLITE_IOERR_UNLOCK;
1683 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001684 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001685 }
drhbbd42a62004-05-22 17:41:58 +00001686 }
drh308c2a52010-05-14 11:30:18 +00001687 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001688 /* Decrement the shared lock counter. Release the lock using an
1689 ** OS call only when all threads in this same process have released
1690 ** the lock.
1691 */
drh8af6c222010-05-14 12:43:01 +00001692 pInode->nShared--;
1693 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001694 lock.l_type = F_UNLCK;
1695 lock.l_whence = SEEK_SET;
1696 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001697 SimulateIOErrorBenign(1);
1698 SimulateIOError( h=(-1) )
1699 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001700 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001701 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001702 }else{
danea83bc62011-04-01 11:56:32 +00001703 rc = SQLITE_IOERR_UNLOCK;
1704 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001705 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001706 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001707 }
drha6abd042004-06-09 17:37:22 +00001708 }
1709
drhbbd42a62004-05-22 17:41:58 +00001710 /* Decrement the count of locks against this same file. When the
1711 ** count reaches zero, close any other file descriptors whose close
1712 ** was deferred because of outstanding locks.
1713 */
drh8af6c222010-05-14 12:43:01 +00001714 pInode->nLock--;
1715 assert( pInode->nLock>=0 );
1716 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001717 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001718 }
1719 }
aswift5b1a2562008-08-22 00:22:35 +00001720
1721end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001722 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001723 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001724 return rc;
drhbbd42a62004-05-22 17:41:58 +00001725}
1726
1727/*
drh308c2a52010-05-14 11:30:18 +00001728** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001729** must be either NO_LOCK or SHARED_LOCK.
1730**
1731** If the locking level of the file descriptor is already at or below
1732** the requested locking level, this routine is a no-op.
1733*/
drh308c2a52010-05-14 11:30:18 +00001734static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001735 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001736}
1737
1738/*
danielk1977e339d652008-06-28 11:23:00 +00001739** This function performs the parts of the "close file" operation
1740** common to all locking schemes. It closes the directory and file
1741** handles, if they are valid, and sets all fields of the unixFile
1742** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001743**
1744** It is *not* necessary to hold the mutex when this routine is called,
1745** even on VxWorks. A mutex will be acquired on VxWorks by the
1746** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001747*/
1748static int closeUnixFile(sqlite3_file *id){
1749 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001750 if( pFile->dirfd>=0 ){
1751 robust_close(pFile, pFile->dirfd, __LINE__);
1752 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001753 }
dan661d71a2011-03-30 19:08:03 +00001754 if( pFile->h>=0 ){
1755 robust_close(pFile, pFile->h, __LINE__);
1756 pFile->h = -1;
1757 }
1758#if OS_VXWORKS
1759 if( pFile->pId ){
1760 if( pFile->isDelete ){
1761 unlink(pFile->pId->zCanonicalName);
1762 }
1763 vxworksReleaseFileId(pFile->pId);
1764 pFile->pId = 0;
1765 }
1766#endif
1767 OSTRACE(("CLOSE %-3d\n", pFile->h));
1768 OpenCounter(-1);
1769 sqlite3_free(pFile->pUnused);
1770 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001771 return SQLITE_OK;
1772}
1773
1774/*
danielk1977e3026632004-06-22 11:29:02 +00001775** Close a file.
1776*/
danielk197762079062007-08-15 17:08:46 +00001777static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001778 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001779 unixFile *pFile = (unixFile *)id;
1780 unixUnlock(id, NO_LOCK);
1781 unixEnterMutex();
1782
1783 /* unixFile.pInode is always valid here. Otherwise, a different close
1784 ** routine (e.g. nolockClose()) would be called instead.
1785 */
1786 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1787 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1788 /* If there are outstanding locks, do not actually close the file just
1789 ** yet because that would clear those locks. Instead, add the file
1790 ** descriptor to pInode->pUnused list. It will be automatically closed
1791 ** when the last lock is cleared.
1792 */
1793 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001794 }
dan661d71a2011-03-30 19:08:03 +00001795 releaseInodeInfo(pFile);
1796 rc = closeUnixFile(id);
1797 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001798 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001799}
1800
drh734c9862008-11-28 15:37:20 +00001801/************** End of the posix advisory lock implementation *****************
1802******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001803
drh734c9862008-11-28 15:37:20 +00001804/******************************************************************************
1805****************************** No-op Locking **********************************
1806**
1807** Of the various locking implementations available, this is by far the
1808** simplest: locking is ignored. No attempt is made to lock the database
1809** file for reading or writing.
1810**
1811** This locking mode is appropriate for use on read-only databases
1812** (ex: databases that are burned into CD-ROM, for example.) It can
1813** also be used if the application employs some external mechanism to
1814** prevent simultaneous access of the same database by two or more
1815** database connections. But there is a serious risk of database
1816** corruption if this locking mode is used in situations where multiple
1817** database connections are accessing the same database file at the same
1818** time and one or more of those connections are writing.
1819*/
drhbfe66312006-10-03 17:40:40 +00001820
drh734c9862008-11-28 15:37:20 +00001821static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1822 UNUSED_PARAMETER(NotUsed);
1823 *pResOut = 0;
1824 return SQLITE_OK;
1825}
drh734c9862008-11-28 15:37:20 +00001826static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1827 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1828 return SQLITE_OK;
1829}
drh734c9862008-11-28 15:37:20 +00001830static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1831 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1832 return SQLITE_OK;
1833}
1834
1835/*
drh9b35ea62008-11-29 02:20:26 +00001836** Close the file.
drh734c9862008-11-28 15:37:20 +00001837*/
1838static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001839 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001840}
1841
1842/******************* End of the no-op lock implementation *********************
1843******************************************************************************/
1844
1845/******************************************************************************
1846************************* Begin dot-file Locking ******************************
1847**
drh0c2694b2009-09-03 16:23:44 +00001848** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001849** files in order to control access to the database. This works on just
1850** about every filesystem imaginable. But there are serious downsides:
1851**
1852** (1) There is zero concurrency. A single reader blocks all other
1853** connections from reading or writing the database.
1854**
1855** (2) An application crash or power loss can leave stale lock files
1856** sitting around that need to be cleared manually.
1857**
1858** Nevertheless, a dotlock is an appropriate locking mode for use if no
1859** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001860**
1861** Dotfile locking works by creating a file in the same directory as the
1862** database and with the same name but with a ".lock" extension added.
1863** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1864** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001865*/
1866
1867/*
1868** The file suffix added to the data base filename in order to create the
1869** lock file.
1870*/
1871#define DOTLOCK_SUFFIX ".lock"
1872
drh7708e972008-11-29 00:56:52 +00001873/*
1874** This routine checks if there is a RESERVED lock held on the specified
1875** file by this or any other process. If such a lock is held, set *pResOut
1876** to a non-zero value otherwise *pResOut is set to zero. The return value
1877** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1878**
1879** In dotfile locking, either a lock exists or it does not. So in this
1880** variation of CheckReservedLock(), *pResOut is set to true if any lock
1881** is held on the file and false if the file is unlocked.
1882*/
drh734c9862008-11-28 15:37:20 +00001883static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1884 int rc = SQLITE_OK;
1885 int reserved = 0;
1886 unixFile *pFile = (unixFile*)id;
1887
1888 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1889
1890 assert( pFile );
1891
1892 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001893 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001894 /* Either this connection or some other connection in the same process
1895 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001896 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001897 }else{
1898 /* The lock is held if and only if the lockfile exists */
1899 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001900 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001901 }
drh308c2a52010-05-14 11:30:18 +00001902 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001903 *pResOut = reserved;
1904 return rc;
1905}
1906
drh7708e972008-11-29 00:56:52 +00001907/*
drh308c2a52010-05-14 11:30:18 +00001908** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001909** of the following:
1910**
1911** (1) SHARED_LOCK
1912** (2) RESERVED_LOCK
1913** (3) PENDING_LOCK
1914** (4) EXCLUSIVE_LOCK
1915**
1916** Sometimes when requesting one lock state, additional lock states
1917** are inserted in between. The locking might fail on one of the later
1918** transitions leaving the lock state different from what it started but
1919** still short of its goal. The following chart shows the allowed
1920** transitions and the inserted intermediate states:
1921**
1922** UNLOCKED -> SHARED
1923** SHARED -> RESERVED
1924** SHARED -> (PENDING) -> EXCLUSIVE
1925** RESERVED -> (PENDING) -> EXCLUSIVE
1926** PENDING -> EXCLUSIVE
1927**
1928** This routine will only increase a lock. Use the sqlite3OsUnlock()
1929** routine to lower a locking level.
1930**
1931** With dotfile locking, we really only support state (4): EXCLUSIVE.
1932** But we track the other locking levels internally.
1933*/
drh308c2a52010-05-14 11:30:18 +00001934static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001935 unixFile *pFile = (unixFile*)id;
1936 int fd;
1937 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001938 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001939
drh7708e972008-11-29 00:56:52 +00001940
1941 /* If we have any lock, then the lock file already exists. All we have
1942 ** to do is adjust our internal record of the lock level.
1943 */
drh308c2a52010-05-14 11:30:18 +00001944 if( pFile->eFileLock > NO_LOCK ){
1945 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001946 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001947#ifdef HAVE_UTIME
1948 utime(zLockFile, NULL);
1949#else
drh734c9862008-11-28 15:37:20 +00001950 utimes(zLockFile, NULL);
1951#endif
drh7708e972008-11-29 00:56:52 +00001952 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001953 }
1954
1955 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001956 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001957 if( fd<0 ){
1958 /* failed to open/create the file, someone else may have stolen the lock */
1959 int tErrno = errno;
1960 if( EEXIST == tErrno ){
1961 rc = SQLITE_BUSY;
1962 } else {
1963 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1964 if( IS_LOCK_ERROR(rc) ){
1965 pFile->lastErrno = tErrno;
1966 }
1967 }
drh7708e972008-11-29 00:56:52 +00001968 return rc;
drh734c9862008-11-28 15:37:20 +00001969 }
drh0e9365c2011-03-02 02:08:13 +00001970 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001971
1972 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001973 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001974 return rc;
1975}
1976
drh7708e972008-11-29 00:56:52 +00001977/*
drh308c2a52010-05-14 11:30:18 +00001978** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001979** must be either NO_LOCK or SHARED_LOCK.
1980**
1981** If the locking level of the file descriptor is already at or below
1982** the requested locking level, this routine is a no-op.
1983**
1984** When the locking level reaches NO_LOCK, delete the lock file.
1985*/
drh308c2a52010-05-14 11:30:18 +00001986static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001987 unixFile *pFile = (unixFile*)id;
1988 char *zLockFile = (char *)pFile->lockingContext;
1989
1990 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001991 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1992 pFile->eFileLock, getpid()));
1993 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001994
1995 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00001996 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00001997 return SQLITE_OK;
1998 }
drh7708e972008-11-29 00:56:52 +00001999
2000 /* To downgrade to shared, simply update our internal notion of the
2001 ** lock state. No need to mess with the file on disk.
2002 */
drh308c2a52010-05-14 11:30:18 +00002003 if( eFileLock==SHARED_LOCK ){
2004 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002005 return SQLITE_OK;
2006 }
2007
drh7708e972008-11-29 00:56:52 +00002008 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002009 assert( eFileLock==NO_LOCK );
drh7708e972008-11-29 00:56:52 +00002010 if( unlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00002011 int rc = 0;
2012 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002013 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002014 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002015 }
2016 if( IS_LOCK_ERROR(rc) ){
2017 pFile->lastErrno = tErrno;
2018 }
2019 return rc;
2020 }
drh308c2a52010-05-14 11:30:18 +00002021 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002022 return SQLITE_OK;
2023}
2024
2025/*
drh9b35ea62008-11-29 02:20:26 +00002026** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002027*/
2028static int dotlockClose(sqlite3_file *id) {
2029 int rc;
2030 if( id ){
2031 unixFile *pFile = (unixFile*)id;
2032 dotlockUnlock(id, NO_LOCK);
2033 sqlite3_free(pFile->lockingContext);
2034 }
drh734c9862008-11-28 15:37:20 +00002035 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002036 return rc;
2037}
2038/****************** End of the dot-file lock implementation *******************
2039******************************************************************************/
2040
2041/******************************************************************************
2042************************** Begin flock Locking ********************************
2043**
2044** Use the flock() system call to do file locking.
2045**
drh6b9d6dd2008-12-03 19:34:47 +00002046** flock() locking is like dot-file locking in that the various
2047** fine-grain locking levels supported by SQLite are collapsed into
2048** a single exclusive lock. In other words, SHARED, RESERVED, and
2049** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2050** still works when you do this, but concurrency is reduced since
2051** only a single process can be reading the database at a time.
2052**
drh734c9862008-11-28 15:37:20 +00002053** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2054** compiling for VXWORKS.
2055*/
2056#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002057
drh6b9d6dd2008-12-03 19:34:47 +00002058/*
drhff812312011-02-23 13:33:46 +00002059** Retry flock() calls that fail with EINTR
2060*/
2061#ifdef EINTR
2062static int robust_flock(int fd, int op){
2063 int rc;
2064 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2065 return rc;
2066}
2067#else
drh5c819272011-02-23 14:00:12 +00002068# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002069#endif
2070
2071
2072/*
drh6b9d6dd2008-12-03 19:34:47 +00002073** This routine checks if there is a RESERVED lock held on the specified
2074** file by this or any other process. If such a lock is held, set *pResOut
2075** to a non-zero value otherwise *pResOut is set to zero. The return value
2076** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2077*/
drh734c9862008-11-28 15:37:20 +00002078static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2079 int rc = SQLITE_OK;
2080 int reserved = 0;
2081 unixFile *pFile = (unixFile*)id;
2082
2083 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2084
2085 assert( pFile );
2086
2087 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002088 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002089 reserved = 1;
2090 }
2091
2092 /* Otherwise see if some other process holds it. */
2093 if( !reserved ){
2094 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002095 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002096 if( !lrc ){
2097 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002098 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002099 if ( lrc ) {
2100 int tErrno = errno;
2101 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002102 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002103 if( IS_LOCK_ERROR(lrc) ){
2104 pFile->lastErrno = tErrno;
2105 rc = lrc;
2106 }
2107 }
2108 } else {
2109 int tErrno = errno;
2110 reserved = 1;
2111 /* someone else might have it reserved */
2112 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2113 if( IS_LOCK_ERROR(lrc) ){
2114 pFile->lastErrno = tErrno;
2115 rc = lrc;
2116 }
2117 }
2118 }
drh308c2a52010-05-14 11:30:18 +00002119 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002120
2121#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2122 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2123 rc = SQLITE_OK;
2124 reserved=1;
2125 }
2126#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2127 *pResOut = reserved;
2128 return rc;
2129}
2130
drh6b9d6dd2008-12-03 19:34:47 +00002131/*
drh308c2a52010-05-14 11:30:18 +00002132** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002133** of the following:
2134**
2135** (1) SHARED_LOCK
2136** (2) RESERVED_LOCK
2137** (3) PENDING_LOCK
2138** (4) EXCLUSIVE_LOCK
2139**
2140** Sometimes when requesting one lock state, additional lock states
2141** are inserted in between. The locking might fail on one of the later
2142** transitions leaving the lock state different from what it started but
2143** still short of its goal. The following chart shows the allowed
2144** transitions and the inserted intermediate states:
2145**
2146** UNLOCKED -> SHARED
2147** SHARED -> RESERVED
2148** SHARED -> (PENDING) -> EXCLUSIVE
2149** RESERVED -> (PENDING) -> EXCLUSIVE
2150** PENDING -> EXCLUSIVE
2151**
2152** flock() only really support EXCLUSIVE locks. We track intermediate
2153** lock states in the sqlite3_file structure, but all locks SHARED or
2154** above are really EXCLUSIVE locks and exclude all other processes from
2155** access the file.
2156**
2157** This routine will only increase a lock. Use the sqlite3OsUnlock()
2158** routine to lower a locking level.
2159*/
drh308c2a52010-05-14 11:30:18 +00002160static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002161 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002162 unixFile *pFile = (unixFile*)id;
2163
2164 assert( pFile );
2165
2166 /* if we already have a lock, it is exclusive.
2167 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002168 if (pFile->eFileLock > NO_LOCK) {
2169 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002170 return SQLITE_OK;
2171 }
2172
2173 /* grab an exclusive lock */
2174
drhff812312011-02-23 13:33:46 +00002175 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002176 int tErrno = errno;
2177 /* didn't get, must be busy */
2178 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2179 if( IS_LOCK_ERROR(rc) ){
2180 pFile->lastErrno = tErrno;
2181 }
2182 } else {
2183 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002184 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002185 }
drh308c2a52010-05-14 11:30:18 +00002186 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2187 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002188#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2189 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2190 rc = SQLITE_BUSY;
2191 }
2192#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2193 return rc;
2194}
2195
drh6b9d6dd2008-12-03 19:34:47 +00002196
2197/*
drh308c2a52010-05-14 11:30:18 +00002198** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002199** must be either NO_LOCK or SHARED_LOCK.
2200**
2201** If the locking level of the file descriptor is already at or below
2202** the requested locking level, this routine is a no-op.
2203*/
drh308c2a52010-05-14 11:30:18 +00002204static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002205 unixFile *pFile = (unixFile*)id;
2206
2207 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002208 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2209 pFile->eFileLock, getpid()));
2210 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002211
2212 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002213 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002214 return SQLITE_OK;
2215 }
2216
2217 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002218 if (eFileLock==SHARED_LOCK) {
2219 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002220 return SQLITE_OK;
2221 }
2222
2223 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002224 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002225#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002226 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002227#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002228 return SQLITE_IOERR_UNLOCK;
2229 }else{
drh308c2a52010-05-14 11:30:18 +00002230 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002231 return SQLITE_OK;
2232 }
2233}
2234
2235/*
2236** Close a file.
2237*/
2238static int flockClose(sqlite3_file *id) {
2239 if( id ){
2240 flockUnlock(id, NO_LOCK);
2241 }
2242 return closeUnixFile(id);
2243}
2244
2245#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2246
2247/******************* End of the flock lock implementation *********************
2248******************************************************************************/
2249
2250/******************************************************************************
2251************************ Begin Named Semaphore Locking ************************
2252**
2253** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002254**
2255** Semaphore locking is like dot-lock and flock in that it really only
2256** supports EXCLUSIVE locking. Only a single process can read or write
2257** the database file at a time. This reduces potential concurrency, but
2258** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002259*/
2260#if OS_VXWORKS
2261
drh6b9d6dd2008-12-03 19:34:47 +00002262/*
2263** This routine checks if there is a RESERVED lock held on the specified
2264** file by this or any other process. If such a lock is held, set *pResOut
2265** to a non-zero value otherwise *pResOut is set to zero. The return value
2266** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2267*/
drh734c9862008-11-28 15:37:20 +00002268static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2269 int rc = SQLITE_OK;
2270 int reserved = 0;
2271 unixFile *pFile = (unixFile*)id;
2272
2273 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2274
2275 assert( pFile );
2276
2277 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002278 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002279 reserved = 1;
2280 }
2281
2282 /* Otherwise see if some other process holds it. */
2283 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002284 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002285 struct stat statBuf;
2286
2287 if( sem_trywait(pSem)==-1 ){
2288 int tErrno = errno;
2289 if( EAGAIN != tErrno ){
2290 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2291 pFile->lastErrno = tErrno;
2292 } else {
2293 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002294 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002295 }
2296 }else{
2297 /* we could have it if we want it */
2298 sem_post(pSem);
2299 }
2300 }
drh308c2a52010-05-14 11:30:18 +00002301 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002302
2303 *pResOut = reserved;
2304 return rc;
2305}
2306
drh6b9d6dd2008-12-03 19:34:47 +00002307/*
drh308c2a52010-05-14 11:30:18 +00002308** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002309** of the following:
2310**
2311** (1) SHARED_LOCK
2312** (2) RESERVED_LOCK
2313** (3) PENDING_LOCK
2314** (4) EXCLUSIVE_LOCK
2315**
2316** Sometimes when requesting one lock state, additional lock states
2317** are inserted in between. The locking might fail on one of the later
2318** transitions leaving the lock state different from what it started but
2319** still short of its goal. The following chart shows the allowed
2320** transitions and the inserted intermediate states:
2321**
2322** UNLOCKED -> SHARED
2323** SHARED -> RESERVED
2324** SHARED -> (PENDING) -> EXCLUSIVE
2325** RESERVED -> (PENDING) -> EXCLUSIVE
2326** PENDING -> EXCLUSIVE
2327**
2328** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2329** lock states in the sqlite3_file structure, but all locks SHARED or
2330** above are really EXCLUSIVE locks and exclude all other processes from
2331** access the file.
2332**
2333** This routine will only increase a lock. Use the sqlite3OsUnlock()
2334** routine to lower a locking level.
2335*/
drh308c2a52010-05-14 11:30:18 +00002336static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002337 unixFile *pFile = (unixFile*)id;
2338 int fd;
drh8af6c222010-05-14 12:43:01 +00002339 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002340 int rc = SQLITE_OK;
2341
2342 /* if we already have a lock, it is exclusive.
2343 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002344 if (pFile->eFileLock > NO_LOCK) {
2345 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002346 rc = SQLITE_OK;
2347 goto sem_end_lock;
2348 }
2349
2350 /* lock semaphore now but bail out when already locked. */
2351 if( sem_trywait(pSem)==-1 ){
2352 rc = SQLITE_BUSY;
2353 goto sem_end_lock;
2354 }
2355
2356 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002357 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002358
2359 sem_end_lock:
2360 return rc;
2361}
2362
drh6b9d6dd2008-12-03 19:34:47 +00002363/*
drh308c2a52010-05-14 11:30:18 +00002364** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002365** must be either NO_LOCK or SHARED_LOCK.
2366**
2367** If the locking level of the file descriptor is already at or below
2368** the requested locking level, this routine is a no-op.
2369*/
drh308c2a52010-05-14 11:30:18 +00002370static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002371 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002372 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002373
2374 assert( pFile );
2375 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002376 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2377 pFile->eFileLock, getpid()));
2378 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002379
2380 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002381 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002382 return SQLITE_OK;
2383 }
2384
2385 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002386 if (eFileLock==SHARED_LOCK) {
2387 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002388 return SQLITE_OK;
2389 }
2390
2391 /* no, really unlock. */
2392 if ( sem_post(pSem)==-1 ) {
2393 int rc, tErrno = errno;
2394 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2395 if( IS_LOCK_ERROR(rc) ){
2396 pFile->lastErrno = tErrno;
2397 }
2398 return rc;
2399 }
drh308c2a52010-05-14 11:30:18 +00002400 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002401 return SQLITE_OK;
2402}
2403
2404/*
2405 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002406 */
drh734c9862008-11-28 15:37:20 +00002407static int semClose(sqlite3_file *id) {
2408 if( id ){
2409 unixFile *pFile = (unixFile*)id;
2410 semUnlock(id, NO_LOCK);
2411 assert( pFile );
2412 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002413 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002414 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002415 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002416 }
2417 return SQLITE_OK;
2418}
2419
2420#endif /* OS_VXWORKS */
2421/*
2422** Named semaphore locking is only available on VxWorks.
2423**
2424*************** End of the named semaphore lock implementation ****************
2425******************************************************************************/
2426
2427
2428/******************************************************************************
2429*************************** Begin AFP Locking *********************************
2430**
2431** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2432** on Apple Macintosh computers - both OS9 and OSX.
2433**
2434** Third-party implementations of AFP are available. But this code here
2435** only works on OSX.
2436*/
2437
drhd2cb50b2009-01-09 21:41:17 +00002438#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002439/*
2440** The afpLockingContext structure contains all afp lock specific state
2441*/
drhbfe66312006-10-03 17:40:40 +00002442typedef struct afpLockingContext afpLockingContext;
2443struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002444 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002445 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002446};
2447
2448struct ByteRangeLockPB2
2449{
2450 unsigned long long offset; /* offset to first byte to lock */
2451 unsigned long long length; /* nbr of bytes to lock */
2452 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2453 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2454 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2455 int fd; /* file desc to assoc this lock with */
2456};
2457
drhfd131da2007-08-07 17:13:03 +00002458#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002459
drh6b9d6dd2008-12-03 19:34:47 +00002460/*
2461** This is a utility for setting or clearing a bit-range lock on an
2462** AFP filesystem.
2463**
2464** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2465*/
2466static int afpSetLock(
2467 const char *path, /* Name of the file to be locked or unlocked */
2468 unixFile *pFile, /* Open file descriptor on path */
2469 unsigned long long offset, /* First byte to be locked */
2470 unsigned long long length, /* Number of bytes to lock */
2471 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002472){
drh6b9d6dd2008-12-03 19:34:47 +00002473 struct ByteRangeLockPB2 pb;
2474 int err;
drhbfe66312006-10-03 17:40:40 +00002475
2476 pb.unLockFlag = setLockFlag ? 0 : 1;
2477 pb.startEndFlag = 0;
2478 pb.offset = offset;
2479 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002480 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002481
drh308c2a52010-05-14 11:30:18 +00002482 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002483 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002484 offset, length));
drhbfe66312006-10-03 17:40:40 +00002485 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2486 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002487 int rc;
2488 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002489 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2490 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002491#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2492 rc = SQLITE_BUSY;
2493#else
drh734c9862008-11-28 15:37:20 +00002494 rc = sqliteErrorFromPosixError(tErrno,
2495 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002496#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002497 if( IS_LOCK_ERROR(rc) ){
2498 pFile->lastErrno = tErrno;
2499 }
2500 return rc;
drhbfe66312006-10-03 17:40:40 +00002501 } else {
aswift5b1a2562008-08-22 00:22:35 +00002502 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002503 }
2504}
2505
drh6b9d6dd2008-12-03 19:34:47 +00002506/*
2507** This routine checks if there is a RESERVED lock held on the specified
2508** file by this or any other process. If such a lock is held, set *pResOut
2509** to a non-zero value otherwise *pResOut is set to zero. The return value
2510** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2511*/
danielk1977e339d652008-06-28 11:23:00 +00002512static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002513 int rc = SQLITE_OK;
2514 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002515 unixFile *pFile = (unixFile*)id;
2516
aswift5b1a2562008-08-22 00:22:35 +00002517 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2518
2519 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002520 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002521 if( context->reserved ){
2522 *pResOut = 1;
2523 return SQLITE_OK;
2524 }
drh8af6c222010-05-14 12:43:01 +00002525 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002526
2527 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002528 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002529 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002530 }
2531
2532 /* Otherwise see if some other process holds it.
2533 */
aswift5b1a2562008-08-22 00:22:35 +00002534 if( !reserved ){
2535 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002536 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002537 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002538 /* if we succeeded in taking the reserved lock, unlock it to restore
2539 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002540 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002541 } else {
2542 /* if we failed to get the lock then someone else must have it */
2543 reserved = 1;
2544 }
2545 if( IS_LOCK_ERROR(lrc) ){
2546 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002547 }
2548 }
drhbfe66312006-10-03 17:40:40 +00002549
drh7ed97b92010-01-20 13:07:21 +00002550 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002551 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002552
2553 *pResOut = reserved;
2554 return rc;
drhbfe66312006-10-03 17:40:40 +00002555}
2556
drh6b9d6dd2008-12-03 19:34:47 +00002557/*
drh308c2a52010-05-14 11:30:18 +00002558** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002559** of the following:
2560**
2561** (1) SHARED_LOCK
2562** (2) RESERVED_LOCK
2563** (3) PENDING_LOCK
2564** (4) EXCLUSIVE_LOCK
2565**
2566** Sometimes when requesting one lock state, additional lock states
2567** are inserted in between. The locking might fail on one of the later
2568** transitions leaving the lock state different from what it started but
2569** still short of its goal. The following chart shows the allowed
2570** transitions and the inserted intermediate states:
2571**
2572** UNLOCKED -> SHARED
2573** SHARED -> RESERVED
2574** SHARED -> (PENDING) -> EXCLUSIVE
2575** RESERVED -> (PENDING) -> EXCLUSIVE
2576** PENDING -> EXCLUSIVE
2577**
2578** This routine will only increase a lock. Use the sqlite3OsUnlock()
2579** routine to lower a locking level.
2580*/
drh308c2a52010-05-14 11:30:18 +00002581static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002582 int rc = SQLITE_OK;
2583 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002584 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002585 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002586
2587 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002588 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2589 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002590 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002591
drhbfe66312006-10-03 17:40:40 +00002592 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002593 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002594 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002595 */
drh308c2a52010-05-14 11:30:18 +00002596 if( pFile->eFileLock>=eFileLock ){
2597 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2598 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002599 return SQLITE_OK;
2600 }
2601
2602 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002603 ** (1) We never move from unlocked to anything higher than shared lock.
2604 ** (2) SQLite never explicitly requests a pendig lock.
2605 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002606 */
drh308c2a52010-05-14 11:30:18 +00002607 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2608 assert( eFileLock!=PENDING_LOCK );
2609 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002610
drh8af6c222010-05-14 12:43:01 +00002611 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002612 */
drh6c7d5c52008-11-21 20:32:33 +00002613 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002614 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002615
2616 /* If some thread using this PID has a lock via a different unixFile*
2617 ** handle that precludes the requested lock, return BUSY.
2618 */
drh8af6c222010-05-14 12:43:01 +00002619 if( (pFile->eFileLock!=pInode->eFileLock &&
2620 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002621 ){
2622 rc = SQLITE_BUSY;
2623 goto afp_end_lock;
2624 }
2625
2626 /* If a SHARED lock is requested, and some thread using this PID already
2627 ** has a SHARED or RESERVED lock, then increment reference counts and
2628 ** return SQLITE_OK.
2629 */
drh308c2a52010-05-14 11:30:18 +00002630 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002631 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002632 assert( eFileLock==SHARED_LOCK );
2633 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002634 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002635 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002636 pInode->nShared++;
2637 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002638 goto afp_end_lock;
2639 }
drhbfe66312006-10-03 17:40:40 +00002640
2641 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002642 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2643 ** be released.
2644 */
drh308c2a52010-05-14 11:30:18 +00002645 if( eFileLock==SHARED_LOCK
2646 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002647 ){
2648 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002649 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002650 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002651 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002652 goto afp_end_lock;
2653 }
2654 }
2655
2656 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002657 ** operating system calls for the specified lock.
2658 */
drh308c2a52010-05-14 11:30:18 +00002659 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002660 int lrc1, lrc2, lrc1Errno;
2661 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002662
drh8af6c222010-05-14 12:43:01 +00002663 assert( pInode->nShared==0 );
2664 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002665
2666 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002667 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002668 /* note that the quality of the randomness doesn't matter that much */
2669 lk = random();
drh8af6c222010-05-14 12:43:01 +00002670 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002671 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002672 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002673 if( IS_LOCK_ERROR(lrc1) ){
2674 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002675 }
aswift5b1a2562008-08-22 00:22:35 +00002676 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002677 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002678
aswift5b1a2562008-08-22 00:22:35 +00002679 if( IS_LOCK_ERROR(lrc1) ) {
2680 pFile->lastErrno = lrc1Errno;
2681 rc = lrc1;
2682 goto afp_end_lock;
2683 } else if( IS_LOCK_ERROR(lrc2) ){
2684 rc = lrc2;
2685 goto afp_end_lock;
2686 } else if( lrc1 != SQLITE_OK ) {
2687 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002688 } else {
drh308c2a52010-05-14 11:30:18 +00002689 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002690 pInode->nLock++;
2691 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002692 }
drh8af6c222010-05-14 12:43:01 +00002693 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002694 /* We are trying for an exclusive lock but another thread in this
2695 ** same process is still holding a shared lock. */
2696 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002697 }else{
2698 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2699 ** assumed that there is a SHARED or greater lock on the file
2700 ** already.
2701 */
2702 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002703 assert( 0!=pFile->eFileLock );
2704 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002705 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002706 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002707 if( !failed ){
2708 context->reserved = 1;
2709 }
drhbfe66312006-10-03 17:40:40 +00002710 }
drh308c2a52010-05-14 11:30:18 +00002711 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002712 /* Acquire an EXCLUSIVE lock */
2713
2714 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002715 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002716 */
drh6b9d6dd2008-12-03 19:34:47 +00002717 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002718 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002719 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002720 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002721 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002722 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002723 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002724 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002725 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2726 ** a critical I/O error
2727 */
2728 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2729 SQLITE_IOERR_LOCK;
2730 goto afp_end_lock;
2731 }
2732 }else{
aswift5b1a2562008-08-22 00:22:35 +00002733 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002734 }
2735 }
aswift5b1a2562008-08-22 00:22:35 +00002736 if( failed ){
2737 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002738 }
2739 }
2740
2741 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002742 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002743 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002744 }else if( eFileLock==EXCLUSIVE_LOCK ){
2745 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002746 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002747 }
2748
2749afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002750 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002751 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2752 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002753 return rc;
2754}
2755
2756/*
drh308c2a52010-05-14 11:30:18 +00002757** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002758** must be either NO_LOCK or SHARED_LOCK.
2759**
2760** If the locking level of the file descriptor is already at or below
2761** the requested locking level, this routine is a no-op.
2762*/
drh308c2a52010-05-14 11:30:18 +00002763static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002764 int rc = SQLITE_OK;
2765 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002766 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002767 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2768 int skipShared = 0;
2769#ifdef SQLITE_TEST
2770 int h = pFile->h;
2771#endif
drhbfe66312006-10-03 17:40:40 +00002772
2773 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002774 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002775 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002776 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002777
drh308c2a52010-05-14 11:30:18 +00002778 assert( eFileLock<=SHARED_LOCK );
2779 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002780 return SQLITE_OK;
2781 }
drh6c7d5c52008-11-21 20:32:33 +00002782 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002783 pInode = pFile->pInode;
2784 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002785 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002786 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002787 SimulateIOErrorBenign(1);
2788 SimulateIOError( h=(-1) )
2789 SimulateIOErrorBenign(0);
2790
2791#ifndef NDEBUG
2792 /* When reducing a lock such that other processes can start
2793 ** reading the database file again, make sure that the
2794 ** transaction counter was updated if any part of the database
2795 ** file changed. If the transaction counter is not updated,
2796 ** other connections to the same file might not realize that
2797 ** the file has changed and hence might not know to flush their
2798 ** cache. The use of a stale cache can lead to database corruption.
2799 */
2800 assert( pFile->inNormalWrite==0
2801 || pFile->dbUpdate==0
2802 || pFile->transCntrChng==1 );
2803 pFile->inNormalWrite = 0;
2804#endif
aswiftaebf4132008-11-21 00:10:35 +00002805
drh308c2a52010-05-14 11:30:18 +00002806 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002807 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002808 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002809 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002810 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002811 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2812 } else {
2813 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002814 }
2815 }
drh308c2a52010-05-14 11:30:18 +00002816 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002817 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002818 }
drh308c2a52010-05-14 11:30:18 +00002819 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002820 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2821 if( !rc ){
2822 context->reserved = 0;
2823 }
aswiftaebf4132008-11-21 00:10:35 +00002824 }
drh8af6c222010-05-14 12:43:01 +00002825 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2826 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002827 }
aswiftaebf4132008-11-21 00:10:35 +00002828 }
drh308c2a52010-05-14 11:30:18 +00002829 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002830
drh7ed97b92010-01-20 13:07:21 +00002831 /* Decrement the shared lock counter. Release the lock using an
2832 ** OS call only when all threads in this same process have released
2833 ** the lock.
2834 */
drh8af6c222010-05-14 12:43:01 +00002835 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2836 pInode->nShared--;
2837 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002838 SimulateIOErrorBenign(1);
2839 SimulateIOError( h=(-1) )
2840 SimulateIOErrorBenign(0);
2841 if( !skipShared ){
2842 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2843 }
2844 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002845 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002846 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002847 }
2848 }
2849 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002850 pInode->nLock--;
2851 assert( pInode->nLock>=0 );
2852 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002853 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002854 }
2855 }
drhbfe66312006-10-03 17:40:40 +00002856 }
drh7ed97b92010-01-20 13:07:21 +00002857
drh6c7d5c52008-11-21 20:32:33 +00002858 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002859 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002860 return rc;
2861}
2862
2863/*
drh339eb0b2008-03-07 15:34:11 +00002864** Close a file & cleanup AFP specific locking context
2865*/
danielk1977e339d652008-06-28 11:23:00 +00002866static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002867 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002868 if( id ){
2869 unixFile *pFile = (unixFile*)id;
2870 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002871 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002872 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002873 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002874 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002875 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002876 ** the last lock is cleared.
2877 */
dan08da86a2009-08-21 17:18:03 +00002878 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002879 }
danb0ac3e32010-06-16 10:55:42 +00002880 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002881 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002882 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002883 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002884 }
drh7ed97b92010-01-20 13:07:21 +00002885 return rc;
drhbfe66312006-10-03 17:40:40 +00002886}
2887
drhd2cb50b2009-01-09 21:41:17 +00002888#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002889/*
2890** The code above is the AFP lock implementation. The code is specific
2891** to MacOSX and does not work on other unix platforms. No alternative
2892** is available. If you don't compile for a mac, then the "unix-afp"
2893** VFS is not available.
2894**
2895********************* End of the AFP lock implementation **********************
2896******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002897
drh7ed97b92010-01-20 13:07:21 +00002898/******************************************************************************
2899*************************** Begin NFS Locking ********************************/
2900
2901#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2902/*
drh308c2a52010-05-14 11:30:18 +00002903 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002904 ** must be either NO_LOCK or SHARED_LOCK.
2905 **
2906 ** If the locking level of the file descriptor is already at or below
2907 ** the requested locking level, this routine is a no-op.
2908 */
drh308c2a52010-05-14 11:30:18 +00002909static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002910 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002911}
2912
2913#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2914/*
2915** The code above is the NFS lock implementation. The code is specific
2916** to MacOSX and does not work on other unix platforms. No alternative
2917** is available.
2918**
2919********************* End of the NFS lock implementation **********************
2920******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002921
2922/******************************************************************************
2923**************** Non-locking sqlite3_file methods *****************************
2924**
2925** The next division contains implementations for all methods of the
2926** sqlite3_file object other than the locking methods. The locking
2927** methods were defined in divisions above (one locking method per
2928** division). Those methods that are common to all locking modes
2929** are gather together into this division.
2930*/
drhbfe66312006-10-03 17:40:40 +00002931
2932/*
drh734c9862008-11-28 15:37:20 +00002933** Seek to the offset passed as the second argument, then read cnt
2934** bytes into pBuf. Return the number of bytes actually read.
2935**
2936** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2937** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2938** one system to another. Since SQLite does not define USE_PREAD
2939** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2940** See tickets #2741 and #2681.
2941**
2942** To avoid stomping the errno value on a failed read the lastErrno value
2943** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002944*/
drh734c9862008-11-28 15:37:20 +00002945static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2946 int got;
drh7ed97b92010-01-20 13:07:21 +00002947#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002948 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002949#endif
drh734c9862008-11-28 15:37:20 +00002950 TIMER_START;
2951#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002952 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002953 SimulateIOError( got = -1 );
2954#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002955 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002956 SimulateIOError( got = -1 );
2957#else
2958 newOffset = lseek(id->h, offset, SEEK_SET);
2959 SimulateIOError( newOffset-- );
2960 if( newOffset!=offset ){
2961 if( newOffset == -1 ){
2962 ((unixFile*)id)->lastErrno = errno;
2963 }else{
2964 ((unixFile*)id)->lastErrno = 0;
2965 }
2966 return -1;
2967 }
drhe562be52011-03-02 18:01:10 +00002968 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002969#endif
2970 TIMER_END;
2971 if( got<0 ){
2972 ((unixFile*)id)->lastErrno = errno;
2973 }
drh308c2a52010-05-14 11:30:18 +00002974 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002975 return got;
drhbfe66312006-10-03 17:40:40 +00002976}
2977
2978/*
drh734c9862008-11-28 15:37:20 +00002979** Read data from a file into a buffer. Return SQLITE_OK if all
2980** bytes were read successfully and SQLITE_IOERR if anything goes
2981** wrong.
drh339eb0b2008-03-07 15:34:11 +00002982*/
drh734c9862008-11-28 15:37:20 +00002983static int unixRead(
2984 sqlite3_file *id,
2985 void *pBuf,
2986 int amt,
2987 sqlite3_int64 offset
2988){
dan08da86a2009-08-21 17:18:03 +00002989 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002990 int got;
2991 assert( id );
drh08c6d442009-02-09 17:34:07 +00002992
dan08da86a2009-08-21 17:18:03 +00002993 /* If this is a database file (not a journal, master-journal or temp
2994 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00002995#if 0
dane946c392009-08-22 11:39:46 +00002996 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00002997 || offset>=PENDING_BYTE+512
2998 || offset+amt<=PENDING_BYTE
2999 );
dan7c246102010-04-12 19:00:29 +00003000#endif
drh08c6d442009-02-09 17:34:07 +00003001
dan08da86a2009-08-21 17:18:03 +00003002 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003003 if( got==amt ){
3004 return SQLITE_OK;
3005 }else if( got<0 ){
3006 /* lastErrno set by seekAndRead */
3007 return SQLITE_IOERR_READ;
3008 }else{
dan08da86a2009-08-21 17:18:03 +00003009 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003010 /* Unread parts of the buffer must be zero-filled */
3011 memset(&((char*)pBuf)[got], 0, amt-got);
3012 return SQLITE_IOERR_SHORT_READ;
3013 }
3014}
3015
3016/*
3017** Seek to the offset in id->offset then read cnt bytes into pBuf.
3018** Return the number of bytes actually read. Update the offset.
3019**
3020** To avoid stomping the errno value on a failed write the lastErrno value
3021** is set before returning.
3022*/
3023static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3024 int got;
drh7ed97b92010-01-20 13:07:21 +00003025#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003026 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003027#endif
drh734c9862008-11-28 15:37:20 +00003028 TIMER_START;
3029#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003030 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003031#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003032 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003033#else
3034 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003035 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003036 if( newOffset!=offset ){
3037 if( newOffset == -1 ){
3038 ((unixFile*)id)->lastErrno = errno;
3039 }else{
3040 ((unixFile*)id)->lastErrno = 0;
3041 }
3042 return -1;
3043 }
drhe562be52011-03-02 18:01:10 +00003044 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003045#endif
3046 TIMER_END;
3047 if( got<0 ){
3048 ((unixFile*)id)->lastErrno = errno;
3049 }
3050
drh308c2a52010-05-14 11:30:18 +00003051 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003052 return got;
3053}
3054
3055
3056/*
3057** Write data from a buffer into a file. Return SQLITE_OK on success
3058** or some other error code on failure.
3059*/
3060static int unixWrite(
3061 sqlite3_file *id,
3062 const void *pBuf,
3063 int amt,
3064 sqlite3_int64 offset
3065){
dan08da86a2009-08-21 17:18:03 +00003066 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003067 int wrote = 0;
3068 assert( id );
3069 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003070
dan08da86a2009-08-21 17:18:03 +00003071 /* If this is a database file (not a journal, master-journal or temp
3072 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003073#if 0
dane946c392009-08-22 11:39:46 +00003074 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003075 || offset>=PENDING_BYTE+512
3076 || offset+amt<=PENDING_BYTE
3077 );
dan7c246102010-04-12 19:00:29 +00003078#endif
drh08c6d442009-02-09 17:34:07 +00003079
drh8f941bc2009-01-14 23:03:40 +00003080#ifndef NDEBUG
3081 /* If we are doing a normal write to a database file (as opposed to
3082 ** doing a hot-journal rollback or a write to some file other than a
3083 ** normal database file) then record the fact that the database
3084 ** has changed. If the transaction counter is modified, record that
3085 ** fact too.
3086 */
dan08da86a2009-08-21 17:18:03 +00003087 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003088 pFile->dbUpdate = 1; /* The database has been modified */
3089 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003090 int rc;
drh8f941bc2009-01-14 23:03:40 +00003091 char oldCntr[4];
3092 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003093 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003094 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003095 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003096 pFile->transCntrChng = 1; /* The transaction counter has changed */
3097 }
3098 }
3099 }
3100#endif
3101
dan08da86a2009-08-21 17:18:03 +00003102 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003103 amt -= wrote;
3104 offset += wrote;
3105 pBuf = &((char*)pBuf)[wrote];
3106 }
3107 SimulateIOError(( wrote=(-1), amt=1 ));
3108 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003109
drh734c9862008-11-28 15:37:20 +00003110 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003111 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003112 /* lastErrno set by seekAndWrite */
3113 return SQLITE_IOERR_WRITE;
3114 }else{
dan08da86a2009-08-21 17:18:03 +00003115 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003116 return SQLITE_FULL;
3117 }
3118 }
dan6e09d692010-07-27 18:34:15 +00003119
drh734c9862008-11-28 15:37:20 +00003120 return SQLITE_OK;
3121}
3122
3123#ifdef SQLITE_TEST
3124/*
3125** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003126** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003127*/
3128int sqlite3_sync_count = 0;
3129int sqlite3_fullsync_count = 0;
3130#endif
3131
3132/*
drh89240432009-03-25 01:06:01 +00003133** We do not trust systems to provide a working fdatasync(). Some do.
3134** Others do no. To be safe, we will stick with the (slower) fsync().
3135** If you know that your system does support fdatasync() correctly,
3136** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003137*/
drh89240432009-03-25 01:06:01 +00003138#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003139# define fdatasync fsync
3140#endif
3141
3142/*
3143** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3144** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3145** only available on Mac OS X. But that could change.
3146*/
3147#ifdef F_FULLFSYNC
3148# define HAVE_FULLFSYNC 1
3149#else
3150# define HAVE_FULLFSYNC 0
3151#endif
3152
3153
3154/*
3155** The fsync() system call does not work as advertised on many
3156** unix systems. The following procedure is an attempt to make
3157** it work better.
3158**
3159** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3160** for testing when we want to run through the test suite quickly.
3161** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3162** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3163** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003164**
3165** SQLite sets the dataOnly flag if the size of the file is unchanged.
3166** The idea behind dataOnly is that it should only write the file content
3167** to disk, not the inode. We only set dataOnly if the file size is
3168** unchanged since the file size is part of the inode. However,
3169** Ted Ts'o tells us that fdatasync() will also write the inode if the
3170** file size has changed. The only real difference between fdatasync()
3171** and fsync(), Ted tells us, is that fdatasync() will not flush the
3172** inode if the mtime or owner or other inode attributes have changed.
3173** We only care about the file size, not the other file attributes, so
3174** as far as SQLite is concerned, an fdatasync() is always adequate.
3175** So, we always use fdatasync() if it is available, regardless of
3176** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003177*/
3178static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003179 int rc;
drh734c9862008-11-28 15:37:20 +00003180
3181 /* The following "ifdef/elif/else/" block has the same structure as
3182 ** the one below. It is replicated here solely to avoid cluttering
3183 ** up the real code with the UNUSED_PARAMETER() macros.
3184 */
3185#ifdef SQLITE_NO_SYNC
3186 UNUSED_PARAMETER(fd);
3187 UNUSED_PARAMETER(fullSync);
3188 UNUSED_PARAMETER(dataOnly);
3189#elif HAVE_FULLFSYNC
3190 UNUSED_PARAMETER(dataOnly);
3191#else
3192 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003193 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003194#endif
3195
3196 /* Record the number of times that we do a normal fsync() and
3197 ** FULLSYNC. This is used during testing to verify that this procedure
3198 ** gets called with the correct arguments.
3199 */
3200#ifdef SQLITE_TEST
3201 if( fullSync ) sqlite3_fullsync_count++;
3202 sqlite3_sync_count++;
3203#endif
3204
3205 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3206 ** no-op
3207 */
3208#ifdef SQLITE_NO_SYNC
3209 rc = SQLITE_OK;
3210#elif HAVE_FULLFSYNC
3211 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003212 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003213 }else{
3214 rc = 1;
3215 }
3216 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003217 ** It shouldn't be possible for fullfsync to fail on the local
3218 ** file system (on OSX), so failure indicates that FULLFSYNC
3219 ** isn't supported for this file system. So, attempt an fsync
3220 ** and (for now) ignore the overhead of a superfluous fcntl call.
3221 ** It'd be better to detect fullfsync support once and avoid
3222 ** the fcntl call every time sync is called.
3223 */
drh734c9862008-11-28 15:37:20 +00003224 if( rc ) rc = fsync(fd);
3225
drh7ed97b92010-01-20 13:07:21 +00003226#elif defined(__APPLE__)
3227 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3228 ** so currently we default to the macro that redefines fdatasync to fsync
3229 */
3230 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003231#else
drh0b647ff2009-03-21 14:41:04 +00003232 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003233#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003234 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003235 rc = fsync(fd);
3236 }
drh0b647ff2009-03-21 14:41:04 +00003237#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003238#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3239
3240 if( OS_VXWORKS && rc!= -1 ){
3241 rc = 0;
3242 }
chw97185482008-11-17 08:05:31 +00003243 return rc;
drhbfe66312006-10-03 17:40:40 +00003244}
3245
drh734c9862008-11-28 15:37:20 +00003246/*
3247** Make sure all writes to a particular file are committed to disk.
3248**
3249** If dataOnly==0 then both the file itself and its metadata (file
3250** size, access time, etc) are synced. If dataOnly!=0 then only the
3251** file data is synced.
3252**
3253** Under Unix, also make sure that the directory entry for the file
3254** has been created by fsync-ing the directory that contains the file.
3255** If we do not do this and we encounter a power failure, the directory
3256** entry for the journal might not exist after we reboot. The next
3257** SQLite to access the file will not know that the journal exists (because
3258** the directory entry for the journal was never created) and the transaction
3259** will not roll back - possibly leading to database corruption.
3260*/
3261static int unixSync(sqlite3_file *id, int flags){
3262 int rc;
3263 unixFile *pFile = (unixFile*)id;
3264
3265 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3266 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3267
3268 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3269 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3270 || (flags&0x0F)==SQLITE_SYNC_FULL
3271 );
3272
3273 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3274 ** line is to test that doing so does not cause any problems.
3275 */
3276 SimulateDiskfullError( return SQLITE_FULL );
3277
3278 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003279 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003280 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3281 SimulateIOError( rc=1 );
3282 if( rc ){
3283 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003284 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003285 }
3286 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003287 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3288 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003289#ifndef SQLITE_DISABLE_DIRSYNC
3290 /* The directory sync is only attempted if full_fsync is
3291 ** turned off or unavailable. If a full_fsync occurred above,
3292 ** then the directory sync is superfluous.
3293 */
3294 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3295 /*
3296 ** We have received multiple reports of fsync() returning
3297 ** errors when applied to directories on certain file systems.
3298 ** A failed directory sync is not a big deal. So it seems
3299 ** better to ignore the error. Ticket #1657
3300 */
3301 /* pFile->lastErrno = errno; */
3302 /* return SQLITE_IOERR; */
3303 }
3304#endif
drh0e9365c2011-03-02 02:08:13 +00003305 /* Only need to sync once, so close the directory when we are done */
3306 robust_close(pFile, pFile->dirfd, __LINE__);
3307 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003308 }
3309 return rc;
3310}
3311
3312/*
3313** Truncate an open file to a specified size
3314*/
3315static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003316 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003317 int rc;
dan6e09d692010-07-27 18:34:15 +00003318 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003319 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003320
3321 /* If the user has configured a chunk-size for this file, truncate the
3322 ** file so that it consists of an integer number of chunks (i.e. the
3323 ** actual file size after the operation may be larger than the requested
3324 ** size).
3325 */
3326 if( pFile->szChunk ){
3327 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3328 }
3329
drhff812312011-02-23 13:33:46 +00003330 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003331 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003332 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003333 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003334 }else{
drh3313b142009-11-06 04:13:18 +00003335#ifndef NDEBUG
3336 /* If we are doing a normal write to a database file (as opposed to
3337 ** doing a hot-journal rollback or a write to some file other than a
3338 ** normal database file) and we truncate the file to zero length,
3339 ** that effectively updates the change counter. This might happen
3340 ** when restoring a database using the backup API from a zero-length
3341 ** source.
3342 */
dan6e09d692010-07-27 18:34:15 +00003343 if( pFile->inNormalWrite && nByte==0 ){
3344 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003345 }
3346#endif
3347
drh734c9862008-11-28 15:37:20 +00003348 return SQLITE_OK;
3349 }
3350}
3351
3352/*
3353** Determine the current size of a file in bytes
3354*/
3355static int unixFileSize(sqlite3_file *id, i64 *pSize){
3356 int rc;
3357 struct stat buf;
3358 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003359 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003360 SimulateIOError( rc=1 );
3361 if( rc!=0 ){
3362 ((unixFile*)id)->lastErrno = errno;
3363 return SQLITE_IOERR_FSTAT;
3364 }
3365 *pSize = buf.st_size;
3366
drh8af6c222010-05-14 12:43:01 +00003367 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003368 ** writes a single byte into that file in order to work around a bug
3369 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3370 ** layers, we need to report this file size as zero even though it is
3371 ** really 1. Ticket #3260.
3372 */
3373 if( *pSize==1 ) *pSize = 0;
3374
3375
3376 return SQLITE_OK;
3377}
3378
drhd2cb50b2009-01-09 21:41:17 +00003379#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003380/*
3381** Handler for proxy-locking file-control verbs. Defined below in the
3382** proxying locking division.
3383*/
3384static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003385#endif
drh715ff302008-12-03 22:32:44 +00003386
dan502019c2010-07-28 14:26:17 +00003387/*
3388** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3389** file-control operation.
3390**
3391** If the user has configured a chunk-size for this file, it could be
3392** that the file needs to be extended at this point. Otherwise, the
3393** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3394*/
3395static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3396 if( pFile->szChunk ){
3397 i64 nSize; /* Required file size */
3398 struct stat buf; /* Used to hold return values of fstat() */
3399
drh99ab3b12011-03-02 15:09:07 +00003400 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003401
3402 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3403 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003404
dan502019c2010-07-28 14:26:17 +00003405#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003406 /* The code below is handling the return value of osFallocate()
3407 ** correctly. posix_fallocate() is defined to "returns zero on success,
3408 ** or an error number on failure". See the manpage for details. */
3409 int err;
drhff812312011-02-23 13:33:46 +00003410 do{
dan661d71a2011-03-30 19:08:03 +00003411 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3412 }while( err==EINTR );
3413 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003414#else
3415 /* If the OS does not have posix_fallocate(), fake it. First use
3416 ** ftruncate() to set the file size, then write a single byte to
3417 ** the last byte in each block within the extended region. This
3418 ** is the same technique used by glibc to implement posix_fallocate()
3419 ** on systems that do not have a real fallocate() system call.
3420 */
3421 int nBlk = buf.st_blksize; /* File-system block size */
3422 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003423
drhff812312011-02-23 13:33:46 +00003424 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003425 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003426 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003427 }
3428 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003429 while( iWrite<nSize ){
3430 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3431 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003432 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003433 }
dan502019c2010-07-28 14:26:17 +00003434#endif
3435 }
3436 }
3437
3438 return SQLITE_OK;
3439}
danielk1977ad94b582007-08-20 06:44:22 +00003440
danielk1977e3026632004-06-22 11:29:02 +00003441/*
drh9e33c2c2007-08-31 18:34:59 +00003442** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003443*/
drhcc6bb3e2007-08-31 16:11:35 +00003444static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drh9e33c2c2007-08-31 18:34:59 +00003445 switch( op ){
3446 case SQLITE_FCNTL_LOCKSTATE: {
drh308c2a52010-05-14 11:30:18 +00003447 *(int*)pArg = ((unixFile*)id)->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003448 return SQLITE_OK;
3449 }
drh7708e972008-11-29 00:56:52 +00003450 case SQLITE_LAST_ERRNO: {
3451 *(int*)pArg = ((unixFile*)id)->lastErrno;
3452 return SQLITE_OK;
3453 }
dan6e09d692010-07-27 18:34:15 +00003454 case SQLITE_FCNTL_CHUNK_SIZE: {
3455 ((unixFile*)id)->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003456 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003457 }
drh9ff27ec2010-05-19 19:26:05 +00003458 case SQLITE_FCNTL_SIZE_HINT: {
dan502019c2010-07-28 14:26:17 +00003459 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
drh9ff27ec2010-05-19 19:26:05 +00003460 }
drh8f941bc2009-01-14 23:03:40 +00003461#ifndef NDEBUG
3462 /* The pager calls this method to signal that it has done
3463 ** a rollback and that the database is therefore unchanged and
3464 ** it hence it is OK for the transaction change counter to be
3465 ** unchanged.
3466 */
3467 case SQLITE_FCNTL_DB_UNCHANGED: {
3468 ((unixFile*)id)->dbUpdate = 0;
3469 return SQLITE_OK;
3470 }
3471#endif
drhd2cb50b2009-01-09 21:41:17 +00003472#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003473 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003474 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003475 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003476 }
drhd2cb50b2009-01-09 21:41:17 +00003477#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003478 case SQLITE_FCNTL_SYNC_OMITTED: {
3479 return SQLITE_OK; /* A no-op */
3480 }
drh9e33c2c2007-08-31 18:34:59 +00003481 }
drh0b52b7d2011-01-26 19:46:22 +00003482 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003483}
3484
3485/*
danielk1977a3d4c882007-03-23 10:08:38 +00003486** Return the sector size in bytes of the underlying block device for
3487** the specified file. This is almost always 512 bytes, but may be
3488** larger for some devices.
3489**
3490** SQLite code assumes this function cannot fail. It also assumes that
3491** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003492** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003493** same for both.
3494*/
danielk1977397d65f2008-11-19 11:35:39 +00003495static int unixSectorSize(sqlite3_file *NotUsed){
3496 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003497 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003498}
3499
danielk197790949c22007-08-17 16:50:38 +00003500/*
danielk1977397d65f2008-11-19 11:35:39 +00003501** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003502*/
danielk1977397d65f2008-11-19 11:35:39 +00003503static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3504 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003505 return 0;
3506}
3507
drhd9e5c4f2010-05-12 18:01:39 +00003508#ifndef SQLITE_OMIT_WAL
3509
3510
3511/*
drhd91c68f2010-05-14 14:52:25 +00003512** Object used to represent an shared memory buffer.
3513**
3514** When multiple threads all reference the same wal-index, each thread
3515** has its own unixShm object, but they all point to a single instance
3516** of this unixShmNode object. In other words, each wal-index is opened
3517** only once per process.
3518**
3519** Each unixShmNode object is connected to a single unixInodeInfo object.
3520** We could coalesce this object into unixInodeInfo, but that would mean
3521** every open file that does not use shared memory (in other words, most
3522** open files) would have to carry around this extra information. So
3523** the unixInodeInfo object contains a pointer to this unixShmNode object
3524** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003525**
3526** unixMutexHeld() must be true when creating or destroying
3527** this object or while reading or writing the following fields:
3528**
3529** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003530**
3531** The following fields are read-only after the object is created:
3532**
3533** fid
3534** zFilename
3535**
drhd91c68f2010-05-14 14:52:25 +00003536** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003537** unixMutexHeld() is true when reading or writing any other field
3538** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003539*/
drhd91c68f2010-05-14 14:52:25 +00003540struct unixShmNode {
3541 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003542 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003543 char *zFilename; /* Name of the mmapped file */
3544 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003545 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003546 u16 nRegion; /* Size of array apRegion */
3547 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003548 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003549 int nRef; /* Number of unixShm objects pointing to this */
3550 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003551#ifdef SQLITE_DEBUG
3552 u8 exclMask; /* Mask of exclusive locks held */
3553 u8 sharedMask; /* Mask of shared locks held */
3554 u8 nextShmId; /* Next available unixShm.id value */
3555#endif
3556};
3557
3558/*
drhd9e5c4f2010-05-12 18:01:39 +00003559** Structure used internally by this VFS to record the state of an
3560** open shared memory connection.
3561**
drhd91c68f2010-05-14 14:52:25 +00003562** The following fields are initialized when this object is created and
3563** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003564**
drhd91c68f2010-05-14 14:52:25 +00003565** unixShm.pFile
3566** unixShm.id
3567**
3568** All other fields are read/write. The unixShm.pFile->mutex must be held
3569** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003570*/
3571struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003572 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3573 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003574 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003575 u16 sharedMask; /* Mask of shared locks held */
3576 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003577#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003578 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003579#endif
3580};
3581
3582/*
drhd9e5c4f2010-05-12 18:01:39 +00003583** Constants used for locking
3584*/
drhbd9676c2010-06-23 17:58:38 +00003585#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003586#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003587
drhd9e5c4f2010-05-12 18:01:39 +00003588/*
drh73b64e42010-05-30 19:55:15 +00003589** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003590**
3591** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3592** otherwise.
3593*/
3594static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003595 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3596 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003597 int ofst, /* First byte of the locking range */
3598 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003599){
3600 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003601 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003602
drhd91c68f2010-05-14 14:52:25 +00003603 /* Access to the unixShmNode object is serialized by the caller */
3604 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003605
drh73b64e42010-05-30 19:55:15 +00003606 /* Shared locks never span more than one byte */
3607 assert( n==1 || lockType!=F_RDLCK );
3608
3609 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003610 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003611
drh3cb93392011-03-12 18:10:44 +00003612 if( pShmNode->h>=0 ){
3613 /* Initialize the locking parameters */
3614 memset(&f, 0, sizeof(f));
3615 f.l_type = lockType;
3616 f.l_whence = SEEK_SET;
3617 f.l_start = ofst;
3618 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003619
drh3cb93392011-03-12 18:10:44 +00003620 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3621 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3622 }
drhd9e5c4f2010-05-12 18:01:39 +00003623
3624 /* Update the global lock state and do debug tracing */
3625#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003626 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003627 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003628 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003629 if( rc==SQLITE_OK ){
3630 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003631 OSTRACE(("unlock %d ok", ofst));
3632 pShmNode->exclMask &= ~mask;
3633 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003634 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003635 OSTRACE(("read-lock %d ok", ofst));
3636 pShmNode->exclMask &= ~mask;
3637 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003638 }else{
3639 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003640 OSTRACE(("write-lock %d ok", ofst));
3641 pShmNode->exclMask |= mask;
3642 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003643 }
3644 }else{
3645 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003646 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003647 }else if( lockType==F_RDLCK ){
3648 OSTRACE(("read-lock failed"));
3649 }else{
3650 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003651 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003652 }
3653 }
drh20e1f082010-05-31 16:10:12 +00003654 OSTRACE((" - afterwards %03x,%03x\n",
3655 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003656 }
drhd9e5c4f2010-05-12 18:01:39 +00003657#endif
3658
3659 return rc;
3660}
3661
drhd9e5c4f2010-05-12 18:01:39 +00003662
3663/*
drhd91c68f2010-05-14 14:52:25 +00003664** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003665**
3666** This is not a VFS shared-memory method; it is a utility function called
3667** by VFS shared-memory methods.
3668*/
drhd91c68f2010-05-14 14:52:25 +00003669static void unixShmPurge(unixFile *pFd){
3670 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003671 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003672 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003673 int i;
drhd91c68f2010-05-14 14:52:25 +00003674 assert( p->pInode==pFd->pInode );
3675 if( p->mutex ) sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003676 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003677 if( p->h>=0 ){
3678 munmap(p->apRegion[i], p->szRegion);
3679 }else{
3680 sqlite3_free(p->apRegion[i]);
3681 }
dan13a3cb82010-06-11 19:04:21 +00003682 }
dan18801912010-06-14 14:07:50 +00003683 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003684 if( p->h>=0 ){
3685 robust_close(pFd, p->h, __LINE__);
3686 p->h = -1;
3687 }
drhd91c68f2010-05-14 14:52:25 +00003688 p->pInode->pShmNode = 0;
3689 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003690 }
3691}
3692
3693/*
danda9fe0c2010-07-13 18:44:03 +00003694** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003695** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003696**
drh7234c6d2010-06-19 15:10:09 +00003697** The file used to implement shared-memory is in the same directory
3698** as the open database file and has the same name as the open database
3699** file with the "-shm" suffix added. For example, if the database file
3700** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003701** for shared memory will be called "/home/user1/config.db-shm".
3702**
3703** Another approach to is to use files in /dev/shm or /dev/tmp or an
3704** some other tmpfs mount. But if a file in a different directory
3705** from the database file is used, then differing access permissions
3706** or a chroot() might cause two different processes on the same
3707** database to end up using different files for shared memory -
3708** meaning that their memory would not really be shared - resulting
3709** in database corruption. Nevertheless, this tmpfs file usage
3710** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3711** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3712** option results in an incompatible build of SQLite; builds of SQLite
3713** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3714** same database file at the same time, database corruption will likely
3715** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3716** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003717**
3718** When opening a new shared-memory file, if no other instances of that
3719** file are currently open, in this process or in other processes, then
3720** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003721**
3722** If the original database file (pDbFd) is using the "unix-excl" VFS
3723** that means that an exclusive lock is held on the database file and
3724** that no other processes are able to read or write the database. In
3725** that case, we do not really need shared memory. No shared memory
3726** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003727*/
danda9fe0c2010-07-13 18:44:03 +00003728static int unixOpenSharedMemory(unixFile *pDbFd){
3729 struct unixShm *p = 0; /* The connection to be opened */
3730 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3731 int rc; /* Result code */
3732 unixInodeInfo *pInode; /* The inode of fd */
3733 char *zShmFilename; /* Name of the file used for SHM */
3734 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003735
danda9fe0c2010-07-13 18:44:03 +00003736 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003737 p = sqlite3_malloc( sizeof(*p) );
3738 if( p==0 ) return SQLITE_NOMEM;
3739 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003740 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003741
danda9fe0c2010-07-13 18:44:03 +00003742 /* Check to see if a unixShmNode object already exists. Reuse an existing
3743 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003744 */
3745 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003746 pInode = pDbFd->pInode;
3747 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003748 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003749 struct stat sStat; /* fstat() info for database file */
3750
3751 /* Call fstat() to figure out the permissions on the database file. If
3752 ** a new *-shm file is created, an attempt will be made to create it
3753 ** with the same permissions. The actual permissions the file is created
3754 ** with are subject to the current umask setting.
3755 */
drh3cb93392011-03-12 18:10:44 +00003756 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003757 rc = SQLITE_IOERR_FSTAT;
3758 goto shm_open_err;
3759 }
3760
drha4ced192010-07-15 18:32:40 +00003761#ifdef SQLITE_SHM_DIRECTORY
3762 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3763#else
drh7234c6d2010-06-19 15:10:09 +00003764 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003765#endif
drh7234c6d2010-06-19 15:10:09 +00003766 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003767 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003768 rc = SQLITE_NOMEM;
3769 goto shm_open_err;
3770 }
drhd91c68f2010-05-14 14:52:25 +00003771 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003772 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003773#ifdef SQLITE_SHM_DIRECTORY
3774 sqlite3_snprintf(nShmFilename, zShmFilename,
3775 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3776 (u32)sStat.st_ino, (u32)sStat.st_dev);
3777#else
drh7234c6d2010-06-19 15:10:09 +00003778 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003779 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003780#endif
drhd91c68f2010-05-14 14:52:25 +00003781 pShmNode->h = -1;
3782 pDbFd->pInode->pShmNode = pShmNode;
3783 pShmNode->pInode = pDbFd->pInode;
3784 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3785 if( pShmNode->mutex==0 ){
3786 rc = SQLITE_NOMEM;
3787 goto shm_open_err;
3788 }
drhd9e5c4f2010-05-12 18:01:39 +00003789
drh3cb93392011-03-12 18:10:44 +00003790 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003791 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3792 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003793 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003794 const char *zRO;
3795 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003796 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003797 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3798 (sStat.st_mode & 0777));
3799 pShmNode->isReadonly = 1;
3800 }
3801 if( pShmNode->h<0 ){
3802 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3803 goto shm_open_err;
3804 }
drhd9e5c4f2010-05-12 18:01:39 +00003805 }
drh3cb93392011-03-12 18:10:44 +00003806
3807 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003808 ** If not, truncate the file to zero length.
3809 */
3810 rc = SQLITE_OK;
3811 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3812 if( robust_ftruncate(pShmNode->h, 0) ){
3813 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003814 }
3815 }
drh66dfec8b2011-06-01 20:01:49 +00003816 if( rc==SQLITE_OK ){
3817 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3818 }
3819 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003820 }
drhd9e5c4f2010-05-12 18:01:39 +00003821 }
3822
drhd91c68f2010-05-14 14:52:25 +00003823 /* Make the new connection a child of the unixShmNode */
3824 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003825#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003826 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003827#endif
drhd91c68f2010-05-14 14:52:25 +00003828 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003829 pDbFd->pShm = p;
3830 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003831
3832 /* The reference count on pShmNode has already been incremented under
3833 ** the cover of the unixEnterMutex() mutex and the pointer from the
3834 ** new (struct unixShm) object to the pShmNode has been set. All that is
3835 ** left to do is to link the new object into the linked list starting
3836 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3837 ** mutex.
3838 */
3839 sqlite3_mutex_enter(pShmNode->mutex);
3840 p->pNext = pShmNode->pFirst;
3841 pShmNode->pFirst = p;
3842 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003843 return SQLITE_OK;
3844
3845 /* Jump here on any error */
3846shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003847 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003848 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003849 unixLeaveMutex();
3850 return rc;
3851}
3852
3853/*
danda9fe0c2010-07-13 18:44:03 +00003854** This function is called to obtain a pointer to region iRegion of the
3855** shared-memory associated with the database file fd. Shared-memory regions
3856** are numbered starting from zero. Each shared-memory region is szRegion
3857** bytes in size.
3858**
3859** If an error occurs, an error code is returned and *pp is set to NULL.
3860**
3861** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3862** region has not been allocated (by any client, including one running in a
3863** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3864** bExtend is non-zero and the requested shared-memory region has not yet
3865** been allocated, it is allocated by this function.
3866**
3867** If the shared-memory region has already been allocated or is allocated by
3868** this call as described above, then it is mapped into this processes
3869** address space (if it is not already), *pp is set to point to the mapped
3870** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003871*/
danda9fe0c2010-07-13 18:44:03 +00003872static int unixShmMap(
3873 sqlite3_file *fd, /* Handle open on database file */
3874 int iRegion, /* Region to retrieve */
3875 int szRegion, /* Size of regions */
3876 int bExtend, /* True to extend file if necessary */
3877 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003878){
danda9fe0c2010-07-13 18:44:03 +00003879 unixFile *pDbFd = (unixFile*)fd;
3880 unixShm *p;
3881 unixShmNode *pShmNode;
3882 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003883
danda9fe0c2010-07-13 18:44:03 +00003884 /* If the shared-memory file has not yet been opened, open it now. */
3885 if( pDbFd->pShm==0 ){
3886 rc = unixOpenSharedMemory(pDbFd);
3887 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003888 }
drhd9e5c4f2010-05-12 18:01:39 +00003889
danda9fe0c2010-07-13 18:44:03 +00003890 p = pDbFd->pShm;
3891 pShmNode = p->pShmNode;
3892 sqlite3_mutex_enter(pShmNode->mutex);
3893 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003894 assert( pShmNode->pInode==pDbFd->pInode );
3895 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3896 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003897
3898 if( pShmNode->nRegion<=iRegion ){
3899 char **apNew; /* New apRegion[] array */
3900 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3901 struct stat sStat; /* Used by fstat() */
3902
3903 pShmNode->szRegion = szRegion;
3904
drh3cb93392011-03-12 18:10:44 +00003905 if( pShmNode->h>=0 ){
3906 /* The requested region is not mapped into this processes address space.
3907 ** Check to see if it has been allocated (i.e. if the wal-index file is
3908 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003909 */
drh3cb93392011-03-12 18:10:44 +00003910 if( osFstat(pShmNode->h, &sStat) ){
3911 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003912 goto shmpage_out;
3913 }
drh3cb93392011-03-12 18:10:44 +00003914
3915 if( sStat.st_size<nByte ){
3916 /* The requested memory region does not exist. If bExtend is set to
3917 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3918 **
3919 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3920 ** the requested memory region.
3921 */
3922 if( !bExtend ) goto shmpage_out;
3923 if( robust_ftruncate(pShmNode->h, nByte) ){
3924 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3925 pShmNode->zFilename);
3926 goto shmpage_out;
3927 }
3928 }
danda9fe0c2010-07-13 18:44:03 +00003929 }
3930
3931 /* Map the requested memory region into this processes address space. */
3932 apNew = (char **)sqlite3_realloc(
3933 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3934 );
3935 if( !apNew ){
3936 rc = SQLITE_IOERR_NOMEM;
3937 goto shmpage_out;
3938 }
3939 pShmNode->apRegion = apNew;
3940 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003941 void *pMem;
3942 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00003943 pMem = mmap(0, szRegion,
3944 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00003945 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3946 );
3947 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00003948 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00003949 goto shmpage_out;
3950 }
3951 }else{
3952 pMem = sqlite3_malloc(szRegion);
3953 if( pMem==0 ){
3954 rc = SQLITE_NOMEM;
3955 goto shmpage_out;
3956 }
3957 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003958 }
3959 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3960 pShmNode->nRegion++;
3961 }
3962 }
3963
3964shmpage_out:
3965 if( pShmNode->nRegion>iRegion ){
3966 *pp = pShmNode->apRegion[iRegion];
3967 }else{
3968 *pp = 0;
3969 }
drh66dfec8b2011-06-01 20:01:49 +00003970 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00003971 sqlite3_mutex_leave(pShmNode->mutex);
3972 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003973}
3974
3975/*
drhd9e5c4f2010-05-12 18:01:39 +00003976** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00003977**
3978** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3979** different here than in posix. In xShmLock(), one can go from unlocked
3980** to shared and back or from unlocked to exclusive and back. But one may
3981** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00003982*/
3983static int unixShmLock(
3984 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00003985 int ofst, /* First lock to acquire or release */
3986 int n, /* Number of locks to acquire or release */
3987 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00003988){
drh73b64e42010-05-30 19:55:15 +00003989 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3990 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3991 unixShm *pX; /* For looping over all siblings */
3992 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3993 int rc = SQLITE_OK; /* Result code */
3994 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00003995
drhd91c68f2010-05-14 14:52:25 +00003996 assert( pShmNode==pDbFd->pInode->pShmNode );
3997 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00003998 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003999 assert( n>=1 );
4000 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4001 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4002 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4003 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4004 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004005 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4006 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004007
drhc99597c2010-05-31 01:41:15 +00004008 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004009 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004010 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004011 if( flags & SQLITE_SHM_UNLOCK ){
4012 u16 allMask = 0; /* Mask of locks held by siblings */
4013
4014 /* See if any siblings hold this same lock */
4015 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4016 if( pX==p ) continue;
4017 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4018 allMask |= pX->sharedMask;
4019 }
4020
4021 /* Unlock the system-level locks */
4022 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004023 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004024 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004025 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004026 }
drh73b64e42010-05-30 19:55:15 +00004027
4028 /* Undo the local locks */
4029 if( rc==SQLITE_OK ){
4030 p->exclMask &= ~mask;
4031 p->sharedMask &= ~mask;
4032 }
4033 }else if( flags & SQLITE_SHM_SHARED ){
4034 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4035
4036 /* Find out which shared locks are already held by sibling connections.
4037 ** If any sibling already holds an exclusive lock, go ahead and return
4038 ** SQLITE_BUSY.
4039 */
4040 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004041 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004042 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004043 break;
4044 }
4045 allShared |= pX->sharedMask;
4046 }
4047
4048 /* Get shared locks at the system level, if necessary */
4049 if( rc==SQLITE_OK ){
4050 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004051 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004052 }else{
drh73b64e42010-05-30 19:55:15 +00004053 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004054 }
drhd9e5c4f2010-05-12 18:01:39 +00004055 }
drh73b64e42010-05-30 19:55:15 +00004056
4057 /* Get the local shared locks */
4058 if( rc==SQLITE_OK ){
4059 p->sharedMask |= mask;
4060 }
4061 }else{
4062 /* Make sure no sibling connections hold locks that will block this
4063 ** lock. If any do, return SQLITE_BUSY right away.
4064 */
4065 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004066 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4067 rc = SQLITE_BUSY;
4068 break;
4069 }
4070 }
4071
4072 /* Get the exclusive locks at the system level. Then if successful
4073 ** also mark the local connection as being locked.
4074 */
4075 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004076 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004077 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004078 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004079 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004080 }
drhd9e5c4f2010-05-12 18:01:39 +00004081 }
4082 }
drhd91c68f2010-05-14 14:52:25 +00004083 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004084 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4085 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004086 return rc;
4087}
4088
drh286a2882010-05-20 23:51:06 +00004089/*
4090** Implement a memory barrier or memory fence on shared memory.
4091**
4092** All loads and stores begun before the barrier must complete before
4093** any load or store begun after the barrier.
4094*/
4095static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004096 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004097){
drhff828942010-06-26 21:34:06 +00004098 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004099 unixEnterMutex();
4100 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004101}
4102
dan18801912010-06-14 14:07:50 +00004103/*
danda9fe0c2010-07-13 18:44:03 +00004104** Close a connection to shared-memory. Delete the underlying
4105** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004106**
4107** If there is no shared memory associated with the connection then this
4108** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004109*/
danda9fe0c2010-07-13 18:44:03 +00004110static int unixShmUnmap(
4111 sqlite3_file *fd, /* The underlying database file */
4112 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004113){
danda9fe0c2010-07-13 18:44:03 +00004114 unixShm *p; /* The connection to be closed */
4115 unixShmNode *pShmNode; /* The underlying shared-memory file */
4116 unixShm **pp; /* For looping over sibling connections */
4117 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004118
danda9fe0c2010-07-13 18:44:03 +00004119 pDbFd = (unixFile*)fd;
4120 p = pDbFd->pShm;
4121 if( p==0 ) return SQLITE_OK;
4122 pShmNode = p->pShmNode;
4123
4124 assert( pShmNode==pDbFd->pInode->pShmNode );
4125 assert( pShmNode->pInode==pDbFd->pInode );
4126
4127 /* Remove connection p from the set of connections associated
4128 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004129 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004130 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4131 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004132
danda9fe0c2010-07-13 18:44:03 +00004133 /* Free the connection p */
4134 sqlite3_free(p);
4135 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004136 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004137
4138 /* If pShmNode->nRef has reached 0, then close the underlying
4139 ** shared-memory file, too */
4140 unixEnterMutex();
4141 assert( pShmNode->nRef>0 );
4142 pShmNode->nRef--;
4143 if( pShmNode->nRef==0 ){
drh3cb93392011-03-12 18:10:44 +00004144 if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004145 unixShmPurge(pDbFd);
4146 }
4147 unixLeaveMutex();
4148
4149 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004150}
drh286a2882010-05-20 23:51:06 +00004151
danda9fe0c2010-07-13 18:44:03 +00004152
drhd9e5c4f2010-05-12 18:01:39 +00004153#else
drh6b017cc2010-06-14 18:01:46 +00004154# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004155# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004156# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004157# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004158#endif /* #ifndef SQLITE_OMIT_WAL */
4159
drh734c9862008-11-28 15:37:20 +00004160/*
4161** Here ends the implementation of all sqlite3_file methods.
4162**
4163********************** End sqlite3_file Methods *******************************
4164******************************************************************************/
4165
4166/*
drh6b9d6dd2008-12-03 19:34:47 +00004167** This division contains definitions of sqlite3_io_methods objects that
4168** implement various file locking strategies. It also contains definitions
4169** of "finder" functions. A finder-function is used to locate the appropriate
4170** sqlite3_io_methods object for a particular database file. The pAppData
4171** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4172** the correct finder-function for that VFS.
4173**
4174** Most finder functions return a pointer to a fixed sqlite3_io_methods
4175** object. The only interesting finder-function is autolockIoFinder, which
4176** looks at the filesystem type and tries to guess the best locking
4177** strategy from that.
4178**
drh1875f7a2008-12-08 18:19:17 +00004179** For finder-funtion F, two objects are created:
4180**
4181** (1) The real finder-function named "FImpt()".
4182**
dane946c392009-08-22 11:39:46 +00004183** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004184**
4185**
4186** A pointer to the F pointer is used as the pAppData value for VFS
4187** objects. We have to do this instead of letting pAppData point
4188** directly at the finder-function since C90 rules prevent a void*
4189** from be cast into a function pointer.
4190**
drh6b9d6dd2008-12-03 19:34:47 +00004191**
drh7708e972008-11-29 00:56:52 +00004192** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004193**
drh7708e972008-11-29 00:56:52 +00004194** * A constant sqlite3_io_methods object call METHOD that has locking
4195** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4196**
4197** * An I/O method finder function called FINDER that returns a pointer
4198** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004199*/
drhd9e5c4f2010-05-12 18:01:39 +00004200#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004201static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004202 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004203 CLOSE, /* xClose */ \
4204 unixRead, /* xRead */ \
4205 unixWrite, /* xWrite */ \
4206 unixTruncate, /* xTruncate */ \
4207 unixSync, /* xSync */ \
4208 unixFileSize, /* xFileSize */ \
4209 LOCK, /* xLock */ \
4210 UNLOCK, /* xUnlock */ \
4211 CKLOCK, /* xCheckReservedLock */ \
4212 unixFileControl, /* xFileControl */ \
4213 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004214 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004215 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004216 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004217 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004218 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004219}; \
drh0c2694b2009-09-03 16:23:44 +00004220static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4221 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004222 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004223} \
drh0c2694b2009-09-03 16:23:44 +00004224static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004225 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004226
4227/*
4228** Here are all of the sqlite3_io_methods objects for each of the
4229** locking strategies. Functions that return pointers to these methods
4230** are also created.
4231*/
4232IOMETHODS(
4233 posixIoFinder, /* Finder function name */
4234 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004235 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004236 unixClose, /* xClose method */
4237 unixLock, /* xLock method */
4238 unixUnlock, /* xUnlock method */
4239 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004240)
drh7708e972008-11-29 00:56:52 +00004241IOMETHODS(
4242 nolockIoFinder, /* Finder function name */
4243 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004244 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004245 nolockClose, /* xClose method */
4246 nolockLock, /* xLock method */
4247 nolockUnlock, /* xUnlock method */
4248 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004249)
drh7708e972008-11-29 00:56:52 +00004250IOMETHODS(
4251 dotlockIoFinder, /* Finder function name */
4252 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004253 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004254 dotlockClose, /* xClose method */
4255 dotlockLock, /* xLock method */
4256 dotlockUnlock, /* xUnlock method */
4257 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004258)
drh7708e972008-11-29 00:56:52 +00004259
chw78a13182009-04-07 05:35:03 +00004260#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004261IOMETHODS(
4262 flockIoFinder, /* Finder function name */
4263 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004264 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004265 flockClose, /* xClose method */
4266 flockLock, /* xLock method */
4267 flockUnlock, /* xUnlock method */
4268 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004269)
drh7708e972008-11-29 00:56:52 +00004270#endif
4271
drh6c7d5c52008-11-21 20:32:33 +00004272#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004273IOMETHODS(
4274 semIoFinder, /* Finder function name */
4275 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004276 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004277 semClose, /* xClose method */
4278 semLock, /* xLock method */
4279 semUnlock, /* xUnlock method */
4280 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004281)
aswiftaebf4132008-11-21 00:10:35 +00004282#endif
drh7708e972008-11-29 00:56:52 +00004283
drhd2cb50b2009-01-09 21:41:17 +00004284#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004285IOMETHODS(
4286 afpIoFinder, /* Finder function name */
4287 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004288 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004289 afpClose, /* xClose method */
4290 afpLock, /* xLock method */
4291 afpUnlock, /* xUnlock method */
4292 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004293)
drh715ff302008-12-03 22:32:44 +00004294#endif
4295
4296/*
4297** The proxy locking method is a "super-method" in the sense that it
4298** opens secondary file descriptors for the conch and lock files and
4299** it uses proxy, dot-file, AFP, and flock() locking methods on those
4300** secondary files. For this reason, the division that implements
4301** proxy locking is located much further down in the file. But we need
4302** to go ahead and define the sqlite3_io_methods and finder function
4303** for proxy locking here. So we forward declare the I/O methods.
4304*/
drhd2cb50b2009-01-09 21:41:17 +00004305#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004306static int proxyClose(sqlite3_file*);
4307static int proxyLock(sqlite3_file*, int);
4308static int proxyUnlock(sqlite3_file*, int);
4309static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004310IOMETHODS(
4311 proxyIoFinder, /* Finder function name */
4312 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004313 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004314 proxyClose, /* xClose method */
4315 proxyLock, /* xLock method */
4316 proxyUnlock, /* xUnlock method */
4317 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004318)
aswiftaebf4132008-11-21 00:10:35 +00004319#endif
drh7708e972008-11-29 00:56:52 +00004320
drh7ed97b92010-01-20 13:07:21 +00004321/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4322#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4323IOMETHODS(
4324 nfsIoFinder, /* Finder function name */
4325 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004326 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004327 unixClose, /* xClose method */
4328 unixLock, /* xLock method */
4329 nfsUnlock, /* xUnlock method */
4330 unixCheckReservedLock /* xCheckReservedLock method */
4331)
4332#endif
drh7708e972008-11-29 00:56:52 +00004333
drhd2cb50b2009-01-09 21:41:17 +00004334#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004335/*
drh6b9d6dd2008-12-03 19:34:47 +00004336** This "finder" function attempts to determine the best locking strategy
4337** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004338** object that implements that strategy.
4339**
4340** This is for MacOSX only.
4341*/
drh1875f7a2008-12-08 18:19:17 +00004342static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004343 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004344 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004345){
4346 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004347 const char *zFilesystem; /* Filesystem type name */
4348 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004349 } aMap[] = {
4350 { "hfs", &posixIoMethods },
4351 { "ufs", &posixIoMethods },
4352 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004353 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004354 { "webdav", &nolockIoMethods },
4355 { 0, 0 }
4356 };
4357 int i;
4358 struct statfs fsInfo;
4359 struct flock lockInfo;
4360
4361 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004362 /* If filePath==NULL that means we are dealing with a transient file
4363 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004364 return &nolockIoMethods;
4365 }
4366 if( statfs(filePath, &fsInfo) != -1 ){
4367 if( fsInfo.f_flags & MNT_RDONLY ){
4368 return &nolockIoMethods;
4369 }
4370 for(i=0; aMap[i].zFilesystem; i++){
4371 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4372 return aMap[i].pMethods;
4373 }
4374 }
4375 }
4376
4377 /* Default case. Handles, amongst others, "nfs".
4378 ** Test byte-range lock using fcntl(). If the call succeeds,
4379 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004380 */
drh7708e972008-11-29 00:56:52 +00004381 lockInfo.l_len = 1;
4382 lockInfo.l_start = 0;
4383 lockInfo.l_whence = SEEK_SET;
4384 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004385 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004386 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4387 return &nfsIoMethods;
4388 } else {
4389 return &posixIoMethods;
4390 }
drh7708e972008-11-29 00:56:52 +00004391 }else{
4392 return &dotlockIoMethods;
4393 }
4394}
drh0c2694b2009-09-03 16:23:44 +00004395static const sqlite3_io_methods
4396 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004397
drhd2cb50b2009-01-09 21:41:17 +00004398#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004399
chw78a13182009-04-07 05:35:03 +00004400#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4401/*
4402** This "finder" function attempts to determine the best locking strategy
4403** for the database file "filePath". It then returns the sqlite3_io_methods
4404** object that implements that strategy.
4405**
4406** This is for VXWorks only.
4407*/
4408static const sqlite3_io_methods *autolockIoFinderImpl(
4409 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004410 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004411){
4412 struct flock lockInfo;
4413
4414 if( !filePath ){
4415 /* If filePath==NULL that means we are dealing with a transient file
4416 ** that does not need to be locked. */
4417 return &nolockIoMethods;
4418 }
4419
4420 /* Test if fcntl() is supported and use POSIX style locks.
4421 ** Otherwise fall back to the named semaphore method.
4422 */
4423 lockInfo.l_len = 1;
4424 lockInfo.l_start = 0;
4425 lockInfo.l_whence = SEEK_SET;
4426 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004427 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004428 return &posixIoMethods;
4429 }else{
4430 return &semIoMethods;
4431 }
4432}
drh0c2694b2009-09-03 16:23:44 +00004433static const sqlite3_io_methods
4434 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004435
4436#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4437
drh7708e972008-11-29 00:56:52 +00004438/*
4439** An abstract type for a pointer to a IO method finder function:
4440*/
drh0c2694b2009-09-03 16:23:44 +00004441typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004442
aswiftaebf4132008-11-21 00:10:35 +00004443
drh734c9862008-11-28 15:37:20 +00004444/****************************************************************************
4445**************************** sqlite3_vfs methods ****************************
4446**
4447** This division contains the implementation of methods on the
4448** sqlite3_vfs object.
4449*/
4450
danielk1977a3d4c882007-03-23 10:08:38 +00004451/*
danielk1977e339d652008-06-28 11:23:00 +00004452** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004453*/
4454static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004455 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004456 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004457 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004458 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004459 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004460 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004461 int isDelete, /* Delete on close if true */
4462 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004463){
drh7708e972008-11-29 00:56:52 +00004464 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004465 unixFile *pNew = (unixFile *)pId;
4466 int rc = SQLITE_OK;
4467
drh8af6c222010-05-14 12:43:01 +00004468 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004469
dane946c392009-08-22 11:39:46 +00004470 /* Parameter isDelete is only used on vxworks. Express this explicitly
4471 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004472 */
drh7708e972008-11-29 00:56:52 +00004473 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004474
dan00157392010-10-05 11:33:15 +00004475 /* Usually the path zFilename should not be a relative pathname. The
4476 ** exception is when opening the proxy "conch" file in builds that
4477 ** include the special Apple locking styles.
4478 */
dan00157392010-10-05 11:33:15 +00004479#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004480 assert( zFilename==0 || zFilename[0]=='/'
4481 || pVfs->pAppData==(void*)&autolockIoFinder );
4482#else
4483 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004484#endif
dan00157392010-10-05 11:33:15 +00004485
drh308c2a52010-05-14 11:30:18 +00004486 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004487 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004488 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004489 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004490 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4491 pNew->ctrlFlags = UNIXFILE_EXCL;
4492 }else{
4493 pNew->ctrlFlags = 0;
4494 }
drh77197112011-03-15 19:08:48 +00004495 if( isReadOnly ){
4496 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4497 }
drh339eb0b2008-03-07 15:34:11 +00004498
drh6c7d5c52008-11-21 20:32:33 +00004499#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004500 pNew->pId = vxworksFindFileId(zFilename);
4501 if( pNew->pId==0 ){
4502 noLock = 1;
4503 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004504 }
4505#endif
4506
drhda0e7682008-07-30 15:27:54 +00004507 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004508 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004509 }else{
drh0c2694b2009-09-03 16:23:44 +00004510 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004511#if SQLITE_ENABLE_LOCKING_STYLE
4512 /* Cache zFilename in the locking context (AFP and dotlock override) for
4513 ** proxyLock activation is possible (remote proxy is based on db name)
4514 ** zFilename remains valid until file is closed, to support */
4515 pNew->lockingContext = (void*)zFilename;
4516#endif
drhda0e7682008-07-30 15:27:54 +00004517 }
danielk1977e339d652008-06-28 11:23:00 +00004518
drh7ed97b92010-01-20 13:07:21 +00004519 if( pLockingStyle == &posixIoMethods
4520#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4521 || pLockingStyle == &nfsIoMethods
4522#endif
4523 ){
drh7708e972008-11-29 00:56:52 +00004524 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004525 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004526 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004527 /* If an error occured in findInodeInfo(), close the file descriptor
4528 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004529 ** in two scenarios:
4530 **
4531 ** (a) A call to fstat() failed.
4532 ** (b) A malloc failed.
4533 **
4534 ** Scenario (b) may only occur if the process is holding no other
4535 ** file descriptors open on the same file. If there were other file
4536 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004537 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004538 ** handle h - as it is guaranteed that no posix locks will be released
4539 ** by doing so.
4540 **
4541 ** If scenario (a) caused the error then things are not so safe. The
4542 ** implicit assumption here is that if fstat() fails, things are in
4543 ** such bad shape that dropping a lock or two doesn't matter much.
4544 */
drh0e9365c2011-03-02 02:08:13 +00004545 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004546 h = -1;
4547 }
drh7708e972008-11-29 00:56:52 +00004548 unixLeaveMutex();
4549 }
danielk1977e339d652008-06-28 11:23:00 +00004550
drhd2cb50b2009-01-09 21:41:17 +00004551#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004552 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004553 /* AFP locking uses the file path so it needs to be included in
4554 ** the afpLockingContext.
4555 */
4556 afpLockingContext *pCtx;
4557 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4558 if( pCtx==0 ){
4559 rc = SQLITE_NOMEM;
4560 }else{
4561 /* NB: zFilename exists and remains valid until the file is closed
4562 ** according to requirement F11141. So we do not need to make a
4563 ** copy of the filename. */
4564 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004565 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004566 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004567 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004568 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004569 if( rc!=SQLITE_OK ){
4570 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004571 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004572 h = -1;
4573 }
drh7708e972008-11-29 00:56:52 +00004574 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004575 }
drh7708e972008-11-29 00:56:52 +00004576 }
4577#endif
danielk1977e339d652008-06-28 11:23:00 +00004578
drh7708e972008-11-29 00:56:52 +00004579 else if( pLockingStyle == &dotlockIoMethods ){
4580 /* Dotfile locking uses the file path so it needs to be included in
4581 ** the dotlockLockingContext
4582 */
4583 char *zLockFile;
4584 int nFilename;
drhea678832008-12-10 19:26:22 +00004585 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004586 zLockFile = (char *)sqlite3_malloc(nFilename);
4587 if( zLockFile==0 ){
4588 rc = SQLITE_NOMEM;
4589 }else{
4590 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004591 }
drh7708e972008-11-29 00:56:52 +00004592 pNew->lockingContext = zLockFile;
4593 }
danielk1977e339d652008-06-28 11:23:00 +00004594
drh6c7d5c52008-11-21 20:32:33 +00004595#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004596 else if( pLockingStyle == &semIoMethods ){
4597 /* Named semaphore locking uses the file path so it needs to be
4598 ** included in the semLockingContext
4599 */
4600 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004601 rc = findInodeInfo(pNew, &pNew->pInode);
4602 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4603 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004604 int n;
drh2238dcc2009-08-27 17:56:20 +00004605 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004606 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004607 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004608 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004609 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4610 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004611 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004612 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004613 }
chw97185482008-11-17 08:05:31 +00004614 }
drh7708e972008-11-29 00:56:52 +00004615 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004616 }
drh7708e972008-11-29 00:56:52 +00004617#endif
aswift5b1a2562008-08-22 00:22:35 +00004618
4619 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004620#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004621 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004622 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004623 h = -1;
chw97185482008-11-17 08:05:31 +00004624 unlink(zFilename);
4625 isDelete = 0;
4626 }
4627 pNew->isDelete = isDelete;
4628#endif
danielk1977e339d652008-06-28 11:23:00 +00004629 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004630 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4631 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004632 }else{
drh7708e972008-11-29 00:56:52 +00004633 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004634 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004635 }
danielk1977e339d652008-06-28 11:23:00 +00004636 return rc;
drh054889e2005-11-30 03:20:31 +00004637}
drh9c06c952005-11-26 00:25:00 +00004638
danielk1977ad94b582007-08-20 06:44:22 +00004639/*
4640** Open a file descriptor to the directory containing file zFilename.
4641** If successful, *pFd is set to the opened file descriptor and
4642** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4643** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4644** value.
4645**
4646** If SQLITE_OK is returned, the caller is responsible for closing
4647** the file descriptor *pFd using close().
4648*/
danielk1977fee2d252007-08-18 10:59:19 +00004649static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004650 int ii;
drh777b17a2007-09-20 10:02:54 +00004651 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004652 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004653
drh153c62c2007-08-24 03:51:33 +00004654 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004655 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004656 if( ii>0 ){
4657 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004658 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004659 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004660#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004661 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004662#endif
drh308c2a52010-05-14 11:30:18 +00004663 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004664 }
4665 }
danielk1977fee2d252007-08-18 10:59:19 +00004666 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004667 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004668}
4669
danielk1977b4b47412007-08-17 15:53:36 +00004670/*
drh8b3cf822010-06-01 21:02:51 +00004671** Return the name of a directory in which to put temporary files.
4672** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004673*/
drh7234c6d2010-06-19 15:10:09 +00004674static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004675 static const char *azDirs[] = {
4676 0,
aswiftaebf4132008-11-21 00:10:35 +00004677 0,
danielk197717b90b52008-06-06 11:11:25 +00004678 "/var/tmp",
4679 "/usr/tmp",
4680 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004681 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004682 };
drh8b3cf822010-06-01 21:02:51 +00004683 unsigned int i;
4684 struct stat buf;
4685 const char *zDir = 0;
4686
4687 azDirs[0] = sqlite3_temp_directory;
4688 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004689 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004690 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004691 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004692 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004693 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004694 break;
4695 }
4696 return zDir;
4697}
4698
4699/*
4700** Create a temporary file name in zBuf. zBuf must be allocated
4701** by the calling process and must be big enough to hold at least
4702** pVfs->mxPathname bytes.
4703*/
4704static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004705 static const unsigned char zChars[] =
4706 "abcdefghijklmnopqrstuvwxyz"
4707 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4708 "0123456789";
drh41022642008-11-21 00:24:42 +00004709 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004710 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004711
4712 /* It's odd to simulate an io-error here, but really this is just
4713 ** using the io-error infrastructure to test that SQLite handles this
4714 ** function failing.
4715 */
4716 SimulateIOError( return SQLITE_IOERR );
4717
drh7234c6d2010-06-19 15:10:09 +00004718 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004719 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004720
4721 /* Check that the output buffer is large enough for the temporary file
4722 ** name. If it is not, return SQLITE_ERROR.
4723 */
danielk197700e13612008-11-17 19:18:54 +00004724 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004725 return SQLITE_ERROR;
4726 }
4727
4728 do{
4729 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004730 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004731 sqlite3_randomness(15, &zBuf[j]);
4732 for(i=0; i<15; i++, j++){
4733 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4734 }
4735 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004736 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004737 return SQLITE_OK;
4738}
4739
drhd2cb50b2009-01-09 21:41:17 +00004740#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004741/*
4742** Routine to transform a unixFile into a proxy-locking unixFile.
4743** Implementation in the proxy-lock division, but used by unixOpen()
4744** if SQLITE_PREFER_PROXY_LOCKING is defined.
4745*/
4746static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004747#endif
drhc66d5b62008-12-03 22:48:32 +00004748
dan08da86a2009-08-21 17:18:03 +00004749/*
4750** Search for an unused file descriptor that was opened on the database
4751** file (not a journal or master-journal file) identified by pathname
4752** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4753** argument to this function.
4754**
4755** Such a file descriptor may exist if a database connection was closed
4756** but the associated file descriptor could not be closed because some
4757** other file descriptor open on the same file is holding a file-lock.
4758** Refer to comments in the unixClose() function and the lengthy comment
4759** describing "Posix Advisory Locking" at the start of this file for
4760** further details. Also, ticket #4018.
4761**
4762** If a suitable file descriptor is found, then it is returned. If no
4763** such file descriptor is located, -1 is returned.
4764*/
dane946c392009-08-22 11:39:46 +00004765static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4766 UnixUnusedFd *pUnused = 0;
4767
4768 /* Do not search for an unused file descriptor on vxworks. Not because
4769 ** vxworks would not benefit from the change (it might, we're not sure),
4770 ** but because no way to test it is currently available. It is better
4771 ** not to risk breaking vxworks support for the sake of such an obscure
4772 ** feature. */
4773#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004774 struct stat sStat; /* Results of stat() call */
4775
4776 /* A stat() call may fail for various reasons. If this happens, it is
4777 ** almost certain that an open() call on the same path will also fail.
4778 ** For this reason, if an error occurs in the stat() call here, it is
4779 ** ignored and -1 is returned. The caller will try to open a new file
4780 ** descriptor on the same path, fail, and return an error to SQLite.
4781 **
4782 ** Even if a subsequent open() call does succeed, the consequences of
4783 ** not searching for a resusable file descriptor are not dire. */
4784 if( 0==stat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004785 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004786
4787 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004788 pInode = inodeList;
4789 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4790 || pInode->fileId.ino!=sStat.st_ino) ){
4791 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004792 }
drh8af6c222010-05-14 12:43:01 +00004793 if( pInode ){
dane946c392009-08-22 11:39:46 +00004794 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004795 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004796 pUnused = *pp;
4797 if( pUnused ){
4798 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004799 }
4800 }
4801 unixLeaveMutex();
4802 }
dane946c392009-08-22 11:39:46 +00004803#endif /* if !OS_VXWORKS */
4804 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004805}
danielk197717b90b52008-06-06 11:11:25 +00004806
4807/*
danddb0ac42010-07-14 14:48:58 +00004808** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004809** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004810** and a value suitable for passing as the third argument to open(2) is
4811** written to *pMode. If an IO error occurs, an SQLite error code is
4812** returned and the value of *pMode is not modified.
4813**
4814** If the file being opened is a temporary file, it is always created with
4815** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004816** is a database or master journal file, it is created with the permissions
4817** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004818**
drh8ab58662010-07-15 18:38:39 +00004819** Finally, if the file being opened is a WAL or regular journal file, then
4820** this function queries the file-system for the permissions on the
4821** corresponding database file and sets *pMode to this value. Whenever
4822** possible, WAL and journal files are created using the same permissions
4823** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004824**
4825** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4826** original filename is unavailable. But 8_3_NAMES is only used for
4827** FAT filesystems and permissions do not matter there, so just use
4828** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004829*/
4830static int findCreateFileMode(
4831 const char *zPath, /* Path of file (possibly) being created */
4832 int flags, /* Flags passed as 4th argument to xOpen() */
4833 mode_t *pMode /* OUT: Permissions to open file with */
4834){
4835 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004836 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004837 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004838 char zDb[MAX_PATHNAME+1]; /* Database file path */
4839 int nDb; /* Number of valid bytes in zDb */
4840 struct stat sStat; /* Output of stat() on database file */
4841
dana0c989d2010-11-05 18:07:37 +00004842 /* zPath is a path to a WAL or journal file. The following block derives
4843 ** the path to the associated database file from zPath. This block handles
4844 ** the following naming conventions:
4845 **
4846 ** "<path to db>-journal"
4847 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004848 ** "<path to db>-journalNN"
4849 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004850 **
drh81cc5162011-05-17 20:36:21 +00004851 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004852 ** used by the test_multiplex.c module.
4853 */
4854 nDb = sqlite3Strlen30(zPath) - 1;
drh81cc5162011-05-17 20:36:21 +00004855 while( nDb>0 && zPath[nDb]!='-' ) nDb--;
4856 if( nDb==0 ) return SQLITE_OK;
danddb0ac42010-07-14 14:48:58 +00004857 memcpy(zDb, zPath, nDb);
4858 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004859
danddb0ac42010-07-14 14:48:58 +00004860 if( 0==stat(zDb, &sStat) ){
4861 *pMode = sStat.st_mode & 0777;
4862 }else{
4863 rc = SQLITE_IOERR_FSTAT;
4864 }
4865 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4866 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004867 }
4868 return rc;
4869}
4870
4871/*
danielk1977ad94b582007-08-20 06:44:22 +00004872** Open the file zPath.
4873**
danielk1977b4b47412007-08-17 15:53:36 +00004874** Previously, the SQLite OS layer used three functions in place of this
4875** one:
4876**
4877** sqlite3OsOpenReadWrite();
4878** sqlite3OsOpenReadOnly();
4879** sqlite3OsOpenExclusive();
4880**
4881** These calls correspond to the following combinations of flags:
4882**
4883** ReadWrite() -> (READWRITE | CREATE)
4884** ReadOnly() -> (READONLY)
4885** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4886**
4887** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4888** true, the file was configured to be automatically deleted when the
4889** file handle closed. To achieve the same effect using this new
4890** interface, add the DELETEONCLOSE flag to those specified above for
4891** OpenExclusive().
4892*/
4893static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004894 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4895 const char *zPath, /* Pathname of file to be opened */
4896 sqlite3_file *pFile, /* The file descriptor to be filled in */
4897 int flags, /* Input flags to control the opening */
4898 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004899){
dan08da86a2009-08-21 17:18:03 +00004900 unixFile *p = (unixFile *)pFile;
4901 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004902 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004903 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004904 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004905 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004906 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004907
4908 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4909 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4910 int isCreate = (flags & SQLITE_OPEN_CREATE);
4911 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4912 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004913#if SQLITE_ENABLE_LOCKING_STYLE
4914 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4915#endif
danielk1977b4b47412007-08-17 15:53:36 +00004916
danielk1977fee2d252007-08-18 10:59:19 +00004917 /* If creating a master or main-file journal, this function will open
4918 ** a file-descriptor on the directory too. The first time unixSync()
4919 ** is called the directory file descriptor will be fsync()ed and close()d.
4920 */
danddb0ac42010-07-14 14:48:58 +00004921 int isOpenDirectory = (isCreate && (
4922 eType==SQLITE_OPEN_MASTER_JOURNAL
4923 || eType==SQLITE_OPEN_MAIN_JOURNAL
4924 || eType==SQLITE_OPEN_WAL
4925 ));
danielk1977fee2d252007-08-18 10:59:19 +00004926
danielk197717b90b52008-06-06 11:11:25 +00004927 /* If argument zPath is a NULL pointer, this function is required to open
4928 ** a temporary file. Use this buffer to store the file name in.
4929 */
4930 char zTmpname[MAX_PATHNAME+1];
4931 const char *zName = zPath;
4932
danielk1977fee2d252007-08-18 10:59:19 +00004933 /* Check the following statements are true:
4934 **
4935 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4936 ** (b) if CREATE is set, then READWRITE must also be set, and
4937 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004938 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004939 */
danielk1977b4b47412007-08-17 15:53:36 +00004940 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004941 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004942 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004943 assert(isDelete==0 || isCreate);
4944
danddb0ac42010-07-14 14:48:58 +00004945 /* The main DB, main journal, WAL file and master journal are never
4946 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004947 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4948 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4949 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004950 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004951
danielk1977fee2d252007-08-18 10:59:19 +00004952 /* Assert that the upper layer has set one of the "file-type" flags. */
4953 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4954 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4955 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004956 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004957 );
4958
dan08da86a2009-08-21 17:18:03 +00004959 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004960
dan08da86a2009-08-21 17:18:03 +00004961 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004962 UnixUnusedFd *pUnused;
4963 pUnused = findReusableFd(zName, flags);
4964 if( pUnused ){
4965 fd = pUnused->fd;
4966 }else{
dan6aa657f2009-08-24 18:57:58 +00004967 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004968 if( !pUnused ){
4969 return SQLITE_NOMEM;
4970 }
4971 }
4972 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004973 }else if( !zName ){
4974 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004975 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00004976 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00004977 if( rc!=SQLITE_OK ){
4978 return rc;
4979 }
4980 zName = zTmpname;
4981 }
4982
dan08da86a2009-08-21 17:18:03 +00004983 /* Determine the value of the flags parameter passed to POSIX function
4984 ** open(). These must be calculated even if open() is not called, as
4985 ** they may be stored as part of the file handle and used by the
4986 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00004987 if( isReadonly ) openFlags |= O_RDONLY;
4988 if( isReadWrite ) openFlags |= O_RDWR;
4989 if( isCreate ) openFlags |= O_CREAT;
4990 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
4991 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00004992
danielk1977b4b47412007-08-17 15:53:36 +00004993 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00004994 mode_t openMode; /* Permissions to create file with */
4995 rc = findCreateFileMode(zName, flags, &openMode);
4996 if( rc!=SQLITE_OK ){
4997 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00004998 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004999 return rc;
5000 }
drhad4f1e52011-03-04 15:43:57 +00005001 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005002 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005003 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5004 /* Failed to open the file for read/write access. Try read-only. */
5005 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005006 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005007 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005008 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005009 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005010 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005011 }
5012 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005013 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005014 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005015 }
danielk1977b4b47412007-08-17 15:53:36 +00005016 }
dan08da86a2009-08-21 17:18:03 +00005017 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005018 if( pOutFlags ){
5019 *pOutFlags = flags;
5020 }
5021
dane946c392009-08-22 11:39:46 +00005022 if( p->pUnused ){
5023 p->pUnused->fd = fd;
5024 p->pUnused->flags = flags;
5025 }
5026
danielk1977b4b47412007-08-17 15:53:36 +00005027 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005028#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005029 zPath = zName;
5030#else
danielk197717b90b52008-06-06 11:11:25 +00005031 unlink(zName);
chw97185482008-11-17 08:05:31 +00005032#endif
danielk1977b4b47412007-08-17 15:53:36 +00005033 }
drh41022642008-11-21 00:24:42 +00005034#if SQLITE_ENABLE_LOCKING_STYLE
5035 else{
dan08da86a2009-08-21 17:18:03 +00005036 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005037 }
5038#endif
5039
danielk1977fee2d252007-08-18 10:59:19 +00005040 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005041 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005042 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005043 /* It is safe to close fd at this point, because it is guaranteed not
5044 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005045 ** it would not be safe to close as this would release any locks held
5046 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005047 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005048 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005049 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005050 }
5051 }
danielk1977e339d652008-06-28 11:23:00 +00005052
5053#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005054 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005055#endif
5056
drhda0e7682008-07-30 15:27:54 +00005057 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005058
drh7ed97b92010-01-20 13:07:21 +00005059
5060#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5061 struct statfs fsInfo;
5062 if( fstatfs(fd, &fsInfo) == -1 ){
5063 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005064 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5065 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005066 return SQLITE_IOERR_ACCESS;
5067 }
5068 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5069 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5070 }
5071#endif
5072
5073#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005074#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005075 isAutoProxy = 1;
5076#endif
5077 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005078 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5079 int useProxy = 0;
5080
dan08da86a2009-08-21 17:18:03 +00005081 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5082 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005083 if( envforce!=NULL ){
5084 useProxy = atoi(envforce)>0;
5085 }else{
5086 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005087 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005088 /* In theory, the close(fd) call is sub-optimal. If the file opened
5089 ** with fd is a database file, and there are other connections open
5090 ** on that file that are currently holding advisory locks on it,
5091 ** then the call to close() will cancel those locks. In practice,
5092 ** we're assuming that statfs() doesn't fail very often. At least
5093 ** not while other file descriptors opened by the same process on
5094 ** the same file are working. */
5095 p->lastErrno = errno;
5096 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005097 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005098 }
drh0e9365c2011-03-02 02:08:13 +00005099 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005100 rc = SQLITE_IOERR_ACCESS;
5101 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005102 }
5103 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5104 }
5105 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005106 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5107 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005108 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005109 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005110 if( rc!=SQLITE_OK ){
5111 /* Use unixClose to clean up the resources added in fillInUnixFile
5112 ** and clear all the structure's references. Specifically,
5113 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5114 */
5115 unixClose(pFile);
5116 return rc;
5117 }
aswiftaebf4132008-11-21 00:10:35 +00005118 }
dane946c392009-08-22 11:39:46 +00005119 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005120 }
5121 }
5122#endif
5123
drh77197112011-03-15 19:08:48 +00005124 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5125 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005126open_finished:
5127 if( rc!=SQLITE_OK ){
5128 sqlite3_free(p->pUnused);
5129 }
5130 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005131}
5132
dane946c392009-08-22 11:39:46 +00005133
danielk1977b4b47412007-08-17 15:53:36 +00005134/*
danielk1977fee2d252007-08-18 10:59:19 +00005135** Delete the file at zPath. If the dirSync argument is true, fsync()
5136** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005137*/
drh6b9d6dd2008-12-03 19:34:47 +00005138static int unixDelete(
5139 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5140 const char *zPath, /* Name of file to be deleted */
5141 int dirSync /* If true, fsync() directory after deleting file */
5142){
danielk1977fee2d252007-08-18 10:59:19 +00005143 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005144 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005145 SimulateIOError(return SQLITE_IOERR_DELETE);
drh5d4feff2010-07-14 01:45:22 +00005146 if( unlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005147 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005148 }
danielk1977d39fa702008-10-16 13:27:40 +00005149#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005150 if( dirSync ){
5151 int fd;
5152 rc = openDirectory(zPath, &fd);
5153 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005154#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005155 if( fsync(fd)==-1 )
5156#else
5157 if( fsync(fd) )
5158#endif
5159 {
dane18d4952011-02-21 11:46:24 +00005160 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005161 }
drh0e9365c2011-03-02 02:08:13 +00005162 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005163 }
5164 }
danielk1977d138dd82008-10-15 16:02:48 +00005165#endif
danielk1977fee2d252007-08-18 10:59:19 +00005166 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005167}
5168
danielk197790949c22007-08-17 16:50:38 +00005169/*
5170** Test the existance of or access permissions of file zPath. The
5171** test performed depends on the value of flags:
5172**
5173** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5174** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5175** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5176**
5177** Otherwise return 0.
5178*/
danielk1977861f7452008-06-05 11:39:11 +00005179static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005180 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5181 const char *zPath, /* Path of the file to examine */
5182 int flags, /* What do we want to learn about the zPath file? */
5183 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005184){
rse25c0d1a2007-09-20 08:38:14 +00005185 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005186 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005187 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005188 switch( flags ){
5189 case SQLITE_ACCESS_EXISTS:
5190 amode = F_OK;
5191 break;
5192 case SQLITE_ACCESS_READWRITE:
5193 amode = W_OK|R_OK;
5194 break;
drh50d3f902007-08-27 21:10:36 +00005195 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005196 amode = R_OK;
5197 break;
5198
5199 default:
5200 assert(!"Invalid flags argument");
5201 }
drh99ab3b12011-03-02 15:09:07 +00005202 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005203 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5204 struct stat buf;
5205 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
5206 *pResOut = 0;
5207 }
5208 }
danielk1977861f7452008-06-05 11:39:11 +00005209 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005210}
5211
danielk1977b4b47412007-08-17 15:53:36 +00005212
5213/*
5214** Turn a relative pathname into a full pathname. The relative path
5215** is stored as a nul-terminated string in the buffer pointed to by
5216** zPath.
5217**
5218** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5219** (in this case, MAX_PATHNAME bytes). The full-path is written to
5220** this buffer before returning.
5221*/
danielk1977adfb9b02007-09-17 07:02:56 +00005222static int unixFullPathname(
5223 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5224 const char *zPath, /* Possibly relative input path */
5225 int nOut, /* Size of output buffer in bytes */
5226 char *zOut /* Output buffer */
5227){
danielk1977843e65f2007-09-01 16:16:15 +00005228
5229 /* It's odd to simulate an io-error here, but really this is just
5230 ** using the io-error infrastructure to test that SQLite handles this
5231 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005232 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005233 */
5234 SimulateIOError( return SQLITE_ERROR );
5235
drh153c62c2007-08-24 03:51:33 +00005236 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005237 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005238
drh3c7f2dc2007-12-06 13:26:20 +00005239 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005240 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005241 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005242 }else{
5243 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005244 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005245 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005246 }
drhea678832008-12-10 19:26:22 +00005247 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005248 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005249 }
5250 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005251}
5252
drh0ccebe72005-06-07 22:22:50 +00005253
drh761df872006-12-21 01:29:22 +00005254#ifndef SQLITE_OMIT_LOAD_EXTENSION
5255/*
5256** Interfaces for opening a shared library, finding entry points
5257** within the shared library, and closing the shared library.
5258*/
5259#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005260static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5261 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005262 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5263}
danielk197795c8a542007-09-01 06:51:27 +00005264
5265/*
5266** SQLite calls this function immediately after a call to unixDlSym() or
5267** unixDlOpen() fails (returns a null pointer). If a more detailed error
5268** message is available, it is written to zBufOut. If no error message
5269** is available, zBufOut is left unmodified and SQLite uses a default
5270** error message.
5271*/
danielk1977397d65f2008-11-19 11:35:39 +00005272static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005273 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005274 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005275 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005276 zErr = dlerror();
5277 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005278 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005279 }
drh6c7d5c52008-11-21 20:32:33 +00005280 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005281}
drh1875f7a2008-12-08 18:19:17 +00005282static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5283 /*
5284 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5285 ** cast into a pointer to a function. And yet the library dlsym() routine
5286 ** returns a void* which is really a pointer to a function. So how do we
5287 ** use dlsym() with -pedantic-errors?
5288 **
5289 ** Variable x below is defined to be a pointer to a function taking
5290 ** parameters void* and const char* and returning a pointer to a function.
5291 ** We initialize x by assigning it a pointer to the dlsym() function.
5292 ** (That assignment requires a cast.) Then we call the function that
5293 ** x points to.
5294 **
5295 ** This work-around is unlikely to work correctly on any system where
5296 ** you really cannot cast a function pointer into void*. But then, on the
5297 ** other hand, dlsym() will not work on such a system either, so we have
5298 ** not really lost anything.
5299 */
5300 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005301 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005302 x = (void(*(*)(void*,const char*))(void))dlsym;
5303 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005304}
danielk1977397d65f2008-11-19 11:35:39 +00005305static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5306 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005307 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005308}
danielk1977b4b47412007-08-17 15:53:36 +00005309#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5310 #define unixDlOpen 0
5311 #define unixDlError 0
5312 #define unixDlSym 0
5313 #define unixDlClose 0
5314#endif
5315
5316/*
danielk197790949c22007-08-17 16:50:38 +00005317** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005318*/
danielk1977397d65f2008-11-19 11:35:39 +00005319static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5320 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005321 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005322
drhbbd42a62004-05-22 17:41:58 +00005323 /* We have to initialize zBuf to prevent valgrind from reporting
5324 ** errors. The reports issued by valgrind are incorrect - we would
5325 ** prefer that the randomness be increased by making use of the
5326 ** uninitialized space in zBuf - but valgrind errors tend to worry
5327 ** some users. Rather than argue, it seems easier just to initialize
5328 ** the whole array and silence valgrind, even if that means less randomness
5329 ** in the random seed.
5330 **
5331 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005332 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005333 ** tests repeatable.
5334 */
danielk1977b4b47412007-08-17 15:53:36 +00005335 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005336#if !defined(SQLITE_TEST)
5337 {
drh842b8642005-01-21 17:53:17 +00005338 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005339 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005340 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005341 time_t t;
5342 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005343 memcpy(zBuf, &t, sizeof(t));
5344 pid = getpid();
5345 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005346 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005347 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005348 }else{
drhe562be52011-03-02 18:01:10 +00005349 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005350 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005351 }
drhbbd42a62004-05-22 17:41:58 +00005352 }
5353#endif
drh72cbd072008-10-14 17:58:38 +00005354 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005355}
5356
danielk1977b4b47412007-08-17 15:53:36 +00005357
drhbbd42a62004-05-22 17:41:58 +00005358/*
5359** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005360** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005361** The return value is the number of microseconds of sleep actually
5362** requested from the underlying operating system, a number which
5363** might be greater than or equal to the argument, but not less
5364** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005365*/
danielk1977397d65f2008-11-19 11:35:39 +00005366static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005367#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005368 struct timespec sp;
5369
5370 sp.tv_sec = microseconds / 1000000;
5371 sp.tv_nsec = (microseconds % 1000000) * 1000;
5372 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005373 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005374 return microseconds;
5375#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005376 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005377 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005378 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005379#else
danielk1977b4b47412007-08-17 15:53:36 +00005380 int seconds = (microseconds+999999)/1000000;
5381 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005382 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005383 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005384#endif
drh88f474a2006-01-02 20:00:12 +00005385}
5386
5387/*
drh6b9d6dd2008-12-03 19:34:47 +00005388** The following variable, if set to a non-zero value, is interpreted as
5389** the number of seconds since 1970 and is used to set the result of
5390** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005391*/
5392#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005393int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005394#endif
5395
5396/*
drhb7e8ea22010-05-03 14:32:30 +00005397** Find the current time (in Universal Coordinated Time). Write into *piNow
5398** the current time and date as a Julian Day number times 86_400_000. In
5399** other words, write into *piNow the number of milliseconds since the Julian
5400** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5401** proleptic Gregorian calendar.
5402**
5403** On success, return 0. Return 1 if the time and date cannot be found.
5404*/
5405static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5406 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5407#if defined(NO_GETTOD)
5408 time_t t;
5409 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005410 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005411#elif OS_VXWORKS
5412 struct timespec sNow;
5413 clock_gettime(CLOCK_REALTIME, &sNow);
5414 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5415#else
5416 struct timeval sNow;
5417 gettimeofday(&sNow, 0);
5418 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5419#endif
5420
5421#ifdef SQLITE_TEST
5422 if( sqlite3_current_time ){
5423 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5424 }
5425#endif
5426 UNUSED_PARAMETER(NotUsed);
5427 return 0;
5428}
5429
5430/*
drhbbd42a62004-05-22 17:41:58 +00005431** Find the current time (in Universal Coordinated Time). Write the
5432** current time and date as a Julian Day number into *prNow and
5433** return 0. Return 1 if the time and date cannot be found.
5434*/
danielk1977397d65f2008-11-19 11:35:39 +00005435static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005436 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005437 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005438 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005439 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005440 return 0;
5441}
danielk1977b4b47412007-08-17 15:53:36 +00005442
drh6b9d6dd2008-12-03 19:34:47 +00005443/*
5444** We added the xGetLastError() method with the intention of providing
5445** better low-level error messages when operating-system problems come up
5446** during SQLite operation. But so far, none of that has been implemented
5447** in the core. So this routine is never called. For now, it is merely
5448** a place-holder.
5449*/
danielk1977397d65f2008-11-19 11:35:39 +00005450static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5451 UNUSED_PARAMETER(NotUsed);
5452 UNUSED_PARAMETER(NotUsed2);
5453 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005454 return 0;
5455}
5456
drhf2424c52010-04-26 00:04:55 +00005457
5458/*
drh734c9862008-11-28 15:37:20 +00005459************************ End of sqlite3_vfs methods ***************************
5460******************************************************************************/
5461
drh715ff302008-12-03 22:32:44 +00005462/******************************************************************************
5463************************** Begin Proxy Locking ********************************
5464**
5465** Proxy locking is a "uber-locking-method" in this sense: It uses the
5466** other locking methods on secondary lock files. Proxy locking is a
5467** meta-layer over top of the primitive locking implemented above. For
5468** this reason, the division that implements of proxy locking is deferred
5469** until late in the file (here) after all of the other I/O methods have
5470** been defined - so that the primitive locking methods are available
5471** as services to help with the implementation of proxy locking.
5472**
5473****
5474**
5475** The default locking schemes in SQLite use byte-range locks on the
5476** database file to coordinate safe, concurrent access by multiple readers
5477** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5478** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5479** as POSIX read & write locks over fixed set of locations (via fsctl),
5480** on AFP and SMB only exclusive byte-range locks are available via fsctl
5481** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5482** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5483** address in the shared range is taken for a SHARED lock, the entire
5484** shared range is taken for an EXCLUSIVE lock):
5485**
5486** PENDING_BYTE 0x40000000
5487** RESERVED_BYTE 0x40000001
5488** SHARED_RANGE 0x40000002 -> 0x40000200
5489**
5490** This works well on the local file system, but shows a nearly 100x
5491** slowdown in read performance on AFP because the AFP client disables
5492** the read cache when byte-range locks are present. Enabling the read
5493** cache exposes a cache coherency problem that is present on all OS X
5494** supported network file systems. NFS and AFP both observe the
5495** close-to-open semantics for ensuring cache coherency
5496** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5497** address the requirements for concurrent database access by multiple
5498** readers and writers
5499** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5500**
5501** To address the performance and cache coherency issues, proxy file locking
5502** changes the way database access is controlled by limiting access to a
5503** single host at a time and moving file locks off of the database file
5504** and onto a proxy file on the local file system.
5505**
5506**
5507** Using proxy locks
5508** -----------------
5509**
5510** C APIs
5511**
5512** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5513** <proxy_path> | ":auto:");
5514** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5515**
5516**
5517** SQL pragmas
5518**
5519** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5520** PRAGMA [database.]lock_proxy_file
5521**
5522** Specifying ":auto:" means that if there is a conch file with a matching
5523** host ID in it, the proxy path in the conch file will be used, otherwise
5524** a proxy path based on the user's temp dir
5525** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5526** actual proxy file name is generated from the name and path of the
5527** database file. For example:
5528**
5529** For database path "/Users/me/foo.db"
5530** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5531**
5532** Once a lock proxy is configured for a database connection, it can not
5533** be removed, however it may be switched to a different proxy path via
5534** the above APIs (assuming the conch file is not being held by another
5535** connection or process).
5536**
5537**
5538** How proxy locking works
5539** -----------------------
5540**
5541** Proxy file locking relies primarily on two new supporting files:
5542**
5543** * conch file to limit access to the database file to a single host
5544** at a time
5545**
5546** * proxy file to act as a proxy for the advisory locks normally
5547** taken on the database
5548**
5549** The conch file - to use a proxy file, sqlite must first "hold the conch"
5550** by taking an sqlite-style shared lock on the conch file, reading the
5551** contents and comparing the host's unique host ID (see below) and lock
5552** proxy path against the values stored in the conch. The conch file is
5553** stored in the same directory as the database file and the file name
5554** is patterned after the database file name as ".<databasename>-conch".
5555** If the conch file does not exist, or it's contents do not match the
5556** host ID and/or proxy path, then the lock is escalated to an exclusive
5557** lock and the conch file contents is updated with the host ID and proxy
5558** path and the lock is downgraded to a shared lock again. If the conch
5559** is held by another process (with a shared lock), the exclusive lock
5560** will fail and SQLITE_BUSY is returned.
5561**
5562** The proxy file - a single-byte file used for all advisory file locks
5563** normally taken on the database file. This allows for safe sharing
5564** of the database file for multiple readers and writers on the same
5565** host (the conch ensures that they all use the same local lock file).
5566**
drh715ff302008-12-03 22:32:44 +00005567** Requesting the lock proxy does not immediately take the conch, it is
5568** only taken when the first request to lock database file is made.
5569** This matches the semantics of the traditional locking behavior, where
5570** opening a connection to a database file does not take a lock on it.
5571** The shared lock and an open file descriptor are maintained until
5572** the connection to the database is closed.
5573**
5574** The proxy file and the lock file are never deleted so they only need
5575** to be created the first time they are used.
5576**
5577** Configuration options
5578** ---------------------
5579**
5580** SQLITE_PREFER_PROXY_LOCKING
5581**
5582** Database files accessed on non-local file systems are
5583** automatically configured for proxy locking, lock files are
5584** named automatically using the same logic as
5585** PRAGMA lock_proxy_file=":auto:"
5586**
5587** SQLITE_PROXY_DEBUG
5588**
5589** Enables the logging of error messages during host id file
5590** retrieval and creation
5591**
drh715ff302008-12-03 22:32:44 +00005592** LOCKPROXYDIR
5593**
5594** Overrides the default directory used for lock proxy files that
5595** are named automatically via the ":auto:" setting
5596**
5597** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5598**
5599** Permissions to use when creating a directory for storing the
5600** lock proxy files, only used when LOCKPROXYDIR is not set.
5601**
5602**
5603** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5604** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5605** force proxy locking to be used for every database file opened, and 0
5606** will force automatic proxy locking to be disabled for all database
5607** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5608** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5609*/
5610
5611/*
5612** Proxy locking is only available on MacOSX
5613*/
drhd2cb50b2009-01-09 21:41:17 +00005614#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005615
drh715ff302008-12-03 22:32:44 +00005616/*
5617** The proxyLockingContext has the path and file structures for the remote
5618** and local proxy files in it
5619*/
5620typedef struct proxyLockingContext proxyLockingContext;
5621struct proxyLockingContext {
5622 unixFile *conchFile; /* Open conch file */
5623 char *conchFilePath; /* Name of the conch file */
5624 unixFile *lockProxy; /* Open proxy lock file */
5625 char *lockProxyPath; /* Name of the proxy lock file */
5626 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005627 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005628 void *oldLockingContext; /* Original lockingcontext to restore on close */
5629 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5630};
5631
drh7ed97b92010-01-20 13:07:21 +00005632/*
5633** The proxy lock file path for the database at dbPath is written into lPath,
5634** which must point to valid, writable memory large enough for a maxLen length
5635** file path.
drh715ff302008-12-03 22:32:44 +00005636*/
drh715ff302008-12-03 22:32:44 +00005637static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5638 int len;
5639 int dbLen;
5640 int i;
5641
5642#ifdef LOCKPROXYDIR
5643 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5644#else
5645# ifdef _CS_DARWIN_USER_TEMP_DIR
5646 {
drh7ed97b92010-01-20 13:07:21 +00005647 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005648 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5649 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005650 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005651 }
drh7ed97b92010-01-20 13:07:21 +00005652 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005653 }
5654# else
5655 len = strlcpy(lPath, "/tmp/", maxLen);
5656# endif
5657#endif
5658
5659 if( lPath[len-1]!='/' ){
5660 len = strlcat(lPath, "/", maxLen);
5661 }
5662
5663 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005664 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005665 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005666 char c = dbPath[i];
5667 lPath[i+len] = (c=='/')?'_':c;
5668 }
5669 lPath[i+len]='\0';
5670 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005671 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005672 return SQLITE_OK;
5673}
5674
drh7ed97b92010-01-20 13:07:21 +00005675/*
5676 ** Creates the lock file and any missing directories in lockPath
5677 */
5678static int proxyCreateLockPath(const char *lockPath){
5679 int i, len;
5680 char buf[MAXPATHLEN];
5681 int start = 0;
5682
5683 assert(lockPath!=NULL);
5684 /* try to create all the intermediate directories */
5685 len = (int)strlen(lockPath);
5686 buf[0] = lockPath[0];
5687 for( i=1; i<len; i++ ){
5688 if( lockPath[i] == '/' && (i - start > 0) ){
5689 /* only mkdir if leaf dir != "." or "/" or ".." */
5690 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5691 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5692 buf[i]='\0';
5693 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5694 int err=errno;
5695 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005696 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005697 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005698 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005699 return err;
5700 }
5701 }
5702 }
5703 start=i+1;
5704 }
5705 buf[i] = lockPath[i];
5706 }
drh308c2a52010-05-14 11:30:18 +00005707 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005708 return 0;
5709}
5710
drh715ff302008-12-03 22:32:44 +00005711/*
5712** Create a new VFS file descriptor (stored in memory obtained from
5713** sqlite3_malloc) and open the file named "path" in the file descriptor.
5714**
5715** The caller is responsible not only for closing the file descriptor
5716** but also for freeing the memory associated with the file descriptor.
5717*/
drh7ed97b92010-01-20 13:07:21 +00005718static int proxyCreateUnixFile(
5719 const char *path, /* path for the new unixFile */
5720 unixFile **ppFile, /* unixFile created and returned by ref */
5721 int islockfile /* if non zero missing dirs will be created */
5722) {
5723 int fd = -1;
5724 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005725 unixFile *pNew;
5726 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005727 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005728 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005729 int terrno = 0;
5730 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005731
drh7ed97b92010-01-20 13:07:21 +00005732 /* 1. first try to open/create the file
5733 ** 2. if that fails, and this is a lock file (not-conch), try creating
5734 ** the parent directories and then try again.
5735 ** 3. if that fails, try to open the file read-only
5736 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5737 */
5738 pUnused = findReusableFd(path, openFlags);
5739 if( pUnused ){
5740 fd = pUnused->fd;
5741 }else{
5742 pUnused = sqlite3_malloc(sizeof(*pUnused));
5743 if( !pUnused ){
5744 return SQLITE_NOMEM;
5745 }
5746 }
5747 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005748 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005749 terrno = errno;
5750 if( fd<0 && errno==ENOENT && islockfile ){
5751 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005752 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005753 }
5754 }
5755 }
5756 if( fd<0 ){
5757 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005758 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005759 terrno = errno;
5760 }
5761 if( fd<0 ){
5762 if( islockfile ){
5763 return SQLITE_BUSY;
5764 }
5765 switch (terrno) {
5766 case EACCES:
5767 return SQLITE_PERM;
5768 case EIO:
5769 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5770 default:
drh9978c972010-02-23 17:36:32 +00005771 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005772 }
5773 }
5774
5775 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5776 if( pNew==NULL ){
5777 rc = SQLITE_NOMEM;
5778 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005779 }
5780 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005781 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005782 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005783 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005784 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005785 pUnused->fd = fd;
5786 pUnused->flags = openFlags;
5787 pNew->pUnused = pUnused;
5788
drh77197112011-03-15 19:08:48 +00005789 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005790 if( rc==SQLITE_OK ){
5791 *ppFile = pNew;
5792 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005793 }
drh7ed97b92010-01-20 13:07:21 +00005794end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005795 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005796 sqlite3_free(pNew);
5797 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005798 return rc;
5799}
5800
drh7ed97b92010-01-20 13:07:21 +00005801#ifdef SQLITE_TEST
5802/* simulate multiple hosts by creating unique hostid file paths */
5803int sqlite3_hostid_num = 0;
5804#endif
5805
5806#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5807
drh0ab216a2010-07-02 17:10:40 +00005808/* Not always defined in the headers as it ought to be */
5809extern int gethostuuid(uuid_t id, const struct timespec *wait);
5810
drh7ed97b92010-01-20 13:07:21 +00005811/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5812** bytes of writable memory.
5813*/
5814static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005815 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5816 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005817#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5818 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005819 {
5820 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5821 if( gethostuuid(pHostID, &timeout) ){
5822 int err = errno;
5823 if( pError ){
5824 *pError = err;
5825 }
5826 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005827 }
drh7ed97b92010-01-20 13:07:21 +00005828 }
drhe8b0c9b2010-09-25 14:13:17 +00005829#endif
drh7ed97b92010-01-20 13:07:21 +00005830#ifdef SQLITE_TEST
5831 /* simulate multiple hosts by creating unique hostid file paths */
5832 if( sqlite3_hostid_num != 0){
5833 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5834 }
5835#endif
5836
5837 return SQLITE_OK;
5838}
5839
5840/* The conch file contains the header, host id and lock file path
5841 */
5842#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5843#define PROXY_HEADERLEN 1 /* conch file header length */
5844#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5845#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5846
5847/*
5848** Takes an open conch file, copies the contents to a new path and then moves
5849** it back. The newly created file's file descriptor is assigned to the
5850** conch file structure and finally the original conch file descriptor is
5851** closed. Returns zero if successful.
5852*/
5853static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5854 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5855 unixFile *conchFile = pCtx->conchFile;
5856 char tPath[MAXPATHLEN];
5857 char buf[PROXY_MAXCONCHLEN];
5858 char *cPath = pCtx->conchFilePath;
5859 size_t readLen = 0;
5860 size_t pathLen = 0;
5861 char errmsg[64] = "";
5862 int fd = -1;
5863 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005864 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005865
5866 /* create a new path by replace the trailing '-conch' with '-break' */
5867 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5868 if( pathLen>MAXPATHLEN || pathLen<6 ||
5869 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005870 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005871 goto end_breaklock;
5872 }
5873 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005874 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005875 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005876 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005877 goto end_breaklock;
5878 }
5879 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005880 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5881 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005882 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005883 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005884 goto end_breaklock;
5885 }
drhe562be52011-03-02 18:01:10 +00005886 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005887 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005888 goto end_breaklock;
5889 }
5890 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005891 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005892 goto end_breaklock;
5893 }
5894 rc = 0;
5895 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005896 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005897 conchFile->h = fd;
5898 conchFile->openFlags = O_RDWR | O_CREAT;
5899
5900end_breaklock:
5901 if( rc ){
5902 if( fd>=0 ){
5903 unlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005904 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005905 }
5906 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5907 }
5908 return rc;
5909}
5910
5911/* Take the requested lock on the conch file and break a stale lock if the
5912** host id matches.
5913*/
5914static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5915 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5916 unixFile *conchFile = pCtx->conchFile;
5917 int rc = SQLITE_OK;
5918 int nTries = 0;
5919 struct timespec conchModTime;
5920
5921 do {
5922 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5923 nTries ++;
5924 if( rc==SQLITE_BUSY ){
5925 /* If the lock failed (busy):
5926 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5927 * 2nd try: fail if the mod time changed or host id is different, wait
5928 * 10 sec and try again
5929 * 3rd try: break the lock unless the mod time has changed.
5930 */
5931 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005932 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005933 pFile->lastErrno = errno;
5934 return SQLITE_IOERR_LOCK;
5935 }
5936
5937 if( nTries==1 ){
5938 conchModTime = buf.st_mtimespec;
5939 usleep(500000); /* wait 0.5 sec and try the lock again*/
5940 continue;
5941 }
5942
5943 assert( nTries>1 );
5944 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5945 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5946 return SQLITE_BUSY;
5947 }
5948
5949 if( nTries==2 ){
5950 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005951 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005952 if( len<0 ){
5953 pFile->lastErrno = errno;
5954 return SQLITE_IOERR_LOCK;
5955 }
5956 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5957 /* don't break the lock if the host id doesn't match */
5958 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5959 return SQLITE_BUSY;
5960 }
5961 }else{
5962 /* don't break the lock on short read or a version mismatch */
5963 return SQLITE_BUSY;
5964 }
5965 usleep(10000000); /* wait 10 sec and try the lock again */
5966 continue;
5967 }
5968
5969 assert( nTries==3 );
5970 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5971 rc = SQLITE_OK;
5972 if( lockType==EXCLUSIVE_LOCK ){
5973 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5974 }
5975 if( !rc ){
5976 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5977 }
5978 }
5979 }
5980 } while( rc==SQLITE_BUSY && nTries<3 );
5981
5982 return rc;
5983}
5984
5985/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00005986** lockPath is non-NULL, the host ID and lock file path must match. A NULL
5987** lockPath means that the lockPath in the conch file will be used if the
5988** host IDs match, or a new lock path will be generated automatically
5989** and written to the conch file.
5990*/
5991static int proxyTakeConch(unixFile *pFile){
5992 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5993
drh7ed97b92010-01-20 13:07:21 +00005994 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00005995 return SQLITE_OK;
5996 }else{
5997 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00005998 uuid_t myHostID;
5999 int pError = 0;
6000 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006001 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006002 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006003 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006004 int createConch = 0;
6005 int hostIdMatch = 0;
6006 int readLen = 0;
6007 int tryOldLockPath = 0;
6008 int forceNewLockPath = 0;
6009
drh308c2a52010-05-14 11:30:18 +00006010 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6011 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006012
drh7ed97b92010-01-20 13:07:21 +00006013 rc = proxyGetHostID(myHostID, &pError);
6014 if( (rc&0xff)==SQLITE_IOERR ){
6015 pFile->lastErrno = pError;
6016 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006017 }
drh7ed97b92010-01-20 13:07:21 +00006018 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006019 if( rc!=SQLITE_OK ){
6020 goto end_takeconch;
6021 }
drh7ed97b92010-01-20 13:07:21 +00006022 /* read the existing conch file */
6023 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6024 if( readLen<0 ){
6025 /* I/O error: lastErrno set by seekAndRead */
6026 pFile->lastErrno = conchFile->lastErrno;
6027 rc = SQLITE_IOERR_READ;
6028 goto end_takeconch;
6029 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6030 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6031 /* a short read or version format mismatch means we need to create a new
6032 ** conch file.
6033 */
6034 createConch = 1;
6035 }
6036 /* if the host id matches and the lock path already exists in the conch
6037 ** we'll try to use the path there, if we can't open that path, we'll
6038 ** retry with a new auto-generated path
6039 */
6040 do { /* in case we need to try again for an :auto: named lock file */
6041
6042 if( !createConch && !forceNewLockPath ){
6043 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6044 PROXY_HOSTIDLEN);
6045 /* if the conch has data compare the contents */
6046 if( !pCtx->lockProxyPath ){
6047 /* for auto-named local lock file, just check the host ID and we'll
6048 ** use the local lock file path that's already in there
6049 */
6050 if( hostIdMatch ){
6051 size_t pathLen = (readLen - PROXY_PATHINDEX);
6052
6053 if( pathLen>=MAXPATHLEN ){
6054 pathLen=MAXPATHLEN-1;
6055 }
6056 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6057 lockPath[pathLen] = 0;
6058 tempLockPath = lockPath;
6059 tryOldLockPath = 1;
6060 /* create a copy of the lock path if the conch is taken */
6061 goto end_takeconch;
6062 }
6063 }else if( hostIdMatch
6064 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6065 readLen-PROXY_PATHINDEX)
6066 ){
6067 /* conch host and lock path match */
6068 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006069 }
drh7ed97b92010-01-20 13:07:21 +00006070 }
6071
6072 /* if the conch isn't writable and doesn't match, we can't take it */
6073 if( (conchFile->openFlags&O_RDWR) == 0 ){
6074 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006075 goto end_takeconch;
6076 }
drh7ed97b92010-01-20 13:07:21 +00006077
6078 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006079 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006080 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6081 tempLockPath = lockPath;
6082 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006083 }
drh7ed97b92010-01-20 13:07:21 +00006084
6085 /* update conch with host and path (this will fail if other process
6086 ** has a shared lock already), if the host id matches, use the big
6087 ** stick.
drh715ff302008-12-03 22:32:44 +00006088 */
drh7ed97b92010-01-20 13:07:21 +00006089 futimes(conchFile->h, NULL);
6090 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006091 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006092 /* We are trying for an exclusive lock but another thread in this
6093 ** same process is still holding a shared lock. */
6094 rc = SQLITE_BUSY;
6095 } else {
6096 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006097 }
drh715ff302008-12-03 22:32:44 +00006098 }else{
drh7ed97b92010-01-20 13:07:21 +00006099 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006100 }
drh7ed97b92010-01-20 13:07:21 +00006101 if( rc==SQLITE_OK ){
6102 char writeBuffer[PROXY_MAXCONCHLEN];
6103 int writeSize = 0;
6104
6105 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6106 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6107 if( pCtx->lockProxyPath!=NULL ){
6108 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6109 }else{
6110 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6111 }
6112 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006113 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006114 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6115 fsync(conchFile->h);
6116 /* If we created a new conch file (not just updated the contents of a
6117 ** valid conch file), try to match the permissions of the database
6118 */
6119 if( rc==SQLITE_OK && createConch ){
6120 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006121 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006122 if( err==0 ){
6123 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6124 S_IROTH|S_IWOTH);
6125 /* try to match the database file R/W permissions, ignore failure */
6126#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006127 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006128#else
drhff812312011-02-23 13:33:46 +00006129 do{
drhe562be52011-03-02 18:01:10 +00006130 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006131 }while( rc==(-1) && errno==EINTR );
6132 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006133 int code = errno;
6134 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6135 cmode, code, strerror(code));
6136 } else {
6137 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6138 }
6139 }else{
6140 int code = errno;
6141 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6142 err, code, strerror(code));
6143#endif
6144 }
drh715ff302008-12-03 22:32:44 +00006145 }
6146 }
drh7ed97b92010-01-20 13:07:21 +00006147 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6148
6149 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006150 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006151 if( rc==SQLITE_OK && pFile->openFlags ){
6152 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006153 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006154 }
6155 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006156 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006157 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006158 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006159 if( fd>=0 ){
6160 pFile->h = fd;
6161 }else{
drh9978c972010-02-23 17:36:32 +00006162 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006163 during locking */
6164 }
6165 }
6166 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6167 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6168 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6169 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6170 /* we couldn't create the proxy lock file with the old lock file path
6171 ** so try again via auto-naming
6172 */
6173 forceNewLockPath = 1;
6174 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006175 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006176 }
6177 }
6178 if( rc==SQLITE_OK ){
6179 /* Need to make a copy of path if we extracted the value
6180 ** from the conch file or the path was allocated on the stack
6181 */
6182 if( tempLockPath ){
6183 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6184 if( !pCtx->lockProxyPath ){
6185 rc = SQLITE_NOMEM;
6186 }
6187 }
6188 }
6189 if( rc==SQLITE_OK ){
6190 pCtx->conchHeld = 1;
6191
6192 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6193 afpLockingContext *afpCtx;
6194 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6195 afpCtx->dbPath = pCtx->lockProxyPath;
6196 }
6197 } else {
6198 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6199 }
drh308c2a52010-05-14 11:30:18 +00006200 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6201 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006202 return rc;
drh308c2a52010-05-14 11:30:18 +00006203 } while (1); /* in case we need to retry the :auto: lock file -
6204 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006205 }
6206}
6207
6208/*
6209** If pFile holds a lock on a conch file, then release that lock.
6210*/
6211static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006212 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006213 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6214 unixFile *conchFile; /* Name of the conch file */
6215
6216 pCtx = (proxyLockingContext *)pFile->lockingContext;
6217 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006218 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006219 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006220 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006221 if( pCtx->conchHeld>0 ){
6222 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6223 }
drh715ff302008-12-03 22:32:44 +00006224 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006225 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6226 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006227 return rc;
6228}
6229
6230/*
6231** Given the name of a database file, compute the name of its conch file.
6232** Store the conch filename in memory obtained from sqlite3_malloc().
6233** Make *pConchPath point to the new name. Return SQLITE_OK on success
6234** or SQLITE_NOMEM if unable to obtain memory.
6235**
6236** The caller is responsible for ensuring that the allocated memory
6237** space is eventually freed.
6238**
6239** *pConchPath is set to NULL if a memory allocation error occurs.
6240*/
6241static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6242 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006243 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006244 char *conchPath; /* buffer in which to construct conch name */
6245
6246 /* Allocate space for the conch filename and initialize the name to
6247 ** the name of the original database file. */
6248 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6249 if( conchPath==0 ){
6250 return SQLITE_NOMEM;
6251 }
6252 memcpy(conchPath, dbPath, len+1);
6253
6254 /* now insert a "." before the last / character */
6255 for( i=(len-1); i>=0; i-- ){
6256 if( conchPath[i]=='/' ){
6257 i++;
6258 break;
6259 }
6260 }
6261 conchPath[i]='.';
6262 while ( i<len ){
6263 conchPath[i+1]=dbPath[i];
6264 i++;
6265 }
6266
6267 /* append the "-conch" suffix to the file */
6268 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006269 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006270
6271 return SQLITE_OK;
6272}
6273
6274
6275/* Takes a fully configured proxy locking-style unix file and switches
6276** the local lock file path
6277*/
6278static int switchLockProxyPath(unixFile *pFile, const char *path) {
6279 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6280 char *oldPath = pCtx->lockProxyPath;
6281 int rc = SQLITE_OK;
6282
drh308c2a52010-05-14 11:30:18 +00006283 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006284 return SQLITE_BUSY;
6285 }
6286
6287 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6288 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6289 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6290 return SQLITE_OK;
6291 }else{
6292 unixFile *lockProxy = pCtx->lockProxy;
6293 pCtx->lockProxy=NULL;
6294 pCtx->conchHeld = 0;
6295 if( lockProxy!=NULL ){
6296 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6297 if( rc ) return rc;
6298 sqlite3_free(lockProxy);
6299 }
6300 sqlite3_free(oldPath);
6301 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6302 }
6303
6304 return rc;
6305}
6306
6307/*
6308** pFile is a file that has been opened by a prior xOpen call. dbPath
6309** is a string buffer at least MAXPATHLEN+1 characters in size.
6310**
6311** This routine find the filename associated with pFile and writes it
6312** int dbPath.
6313*/
6314static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006315#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006316 if( pFile->pMethod == &afpIoMethods ){
6317 /* afp style keeps a reference to the db path in the filePath field
6318 ** of the struct */
drhea678832008-12-10 19:26:22 +00006319 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006320 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6321 } else
drh715ff302008-12-03 22:32:44 +00006322#endif
6323 if( pFile->pMethod == &dotlockIoMethods ){
6324 /* dot lock style uses the locking context to store the dot lock
6325 ** file path */
6326 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6327 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6328 }else{
6329 /* all other styles use the locking context to store the db file path */
6330 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006331 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006332 }
6333 return SQLITE_OK;
6334}
6335
6336/*
6337** Takes an already filled in unix file and alters it so all file locking
6338** will be performed on the local proxy lock file. The following fields
6339** are preserved in the locking context so that they can be restored and
6340** the unix structure properly cleaned up at close time:
6341** ->lockingContext
6342** ->pMethod
6343*/
6344static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6345 proxyLockingContext *pCtx;
6346 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6347 char *lockPath=NULL;
6348 int rc = SQLITE_OK;
6349
drh308c2a52010-05-14 11:30:18 +00006350 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006351 return SQLITE_BUSY;
6352 }
6353 proxyGetDbPathForUnixFile(pFile, dbPath);
6354 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6355 lockPath=NULL;
6356 }else{
6357 lockPath=(char *)path;
6358 }
6359
drh308c2a52010-05-14 11:30:18 +00006360 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6361 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006362
6363 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6364 if( pCtx==0 ){
6365 return SQLITE_NOMEM;
6366 }
6367 memset(pCtx, 0, sizeof(*pCtx));
6368
6369 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6370 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006371 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6372 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6373 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6374 ** (c) the file system is read-only, then enable no-locking access.
6375 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6376 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6377 */
6378 struct statfs fsInfo;
6379 struct stat conchInfo;
6380 int goLockless = 0;
6381
drh99ab3b12011-03-02 15:09:07 +00006382 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006383 int err = errno;
6384 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6385 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6386 }
6387 }
6388 if( goLockless ){
6389 pCtx->conchHeld = -1; /* read only FS/ lockless */
6390 rc = SQLITE_OK;
6391 }
6392 }
drh715ff302008-12-03 22:32:44 +00006393 }
6394 if( rc==SQLITE_OK && lockPath ){
6395 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6396 }
6397
6398 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006399 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6400 if( pCtx->dbPath==NULL ){
6401 rc = SQLITE_NOMEM;
6402 }
6403 }
6404 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006405 /* all memory is allocated, proxys are created and assigned,
6406 ** switch the locking context and pMethod then return.
6407 */
drh715ff302008-12-03 22:32:44 +00006408 pCtx->oldLockingContext = pFile->lockingContext;
6409 pFile->lockingContext = pCtx;
6410 pCtx->pOldMethod = pFile->pMethod;
6411 pFile->pMethod = &proxyIoMethods;
6412 }else{
6413 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006414 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006415 sqlite3_free(pCtx->conchFile);
6416 }
drhd56b1212010-08-11 06:14:15 +00006417 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006418 sqlite3_free(pCtx->conchFilePath);
6419 sqlite3_free(pCtx);
6420 }
drh308c2a52010-05-14 11:30:18 +00006421 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6422 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006423 return rc;
6424}
6425
6426
6427/*
6428** This routine handles sqlite3_file_control() calls that are specific
6429** to proxy locking.
6430*/
6431static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6432 switch( op ){
6433 case SQLITE_GET_LOCKPROXYFILE: {
6434 unixFile *pFile = (unixFile*)id;
6435 if( pFile->pMethod == &proxyIoMethods ){
6436 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6437 proxyTakeConch(pFile);
6438 if( pCtx->lockProxyPath ){
6439 *(const char **)pArg = pCtx->lockProxyPath;
6440 }else{
6441 *(const char **)pArg = ":auto: (not held)";
6442 }
6443 } else {
6444 *(const char **)pArg = NULL;
6445 }
6446 return SQLITE_OK;
6447 }
6448 case SQLITE_SET_LOCKPROXYFILE: {
6449 unixFile *pFile = (unixFile*)id;
6450 int rc = SQLITE_OK;
6451 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6452 if( pArg==NULL || (const char *)pArg==0 ){
6453 if( isProxyStyle ){
6454 /* turn off proxy locking - not supported */
6455 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6456 }else{
6457 /* turn off proxy locking - already off - NOOP */
6458 rc = SQLITE_OK;
6459 }
6460 }else{
6461 const char *proxyPath = (const char *)pArg;
6462 if( isProxyStyle ){
6463 proxyLockingContext *pCtx =
6464 (proxyLockingContext*)pFile->lockingContext;
6465 if( !strcmp(pArg, ":auto:")
6466 || (pCtx->lockProxyPath &&
6467 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6468 ){
6469 rc = SQLITE_OK;
6470 }else{
6471 rc = switchLockProxyPath(pFile, proxyPath);
6472 }
6473 }else{
6474 /* turn on proxy file locking */
6475 rc = proxyTransformUnixFile(pFile, proxyPath);
6476 }
6477 }
6478 return rc;
6479 }
6480 default: {
6481 assert( 0 ); /* The call assures that only valid opcodes are sent */
6482 }
6483 }
6484 /*NOTREACHED*/
6485 return SQLITE_ERROR;
6486}
6487
6488/*
6489** Within this division (the proxying locking implementation) the procedures
6490** above this point are all utilities. The lock-related methods of the
6491** proxy-locking sqlite3_io_method object follow.
6492*/
6493
6494
6495/*
6496** This routine checks if there is a RESERVED lock held on the specified
6497** file by this or any other process. If such a lock is held, set *pResOut
6498** to a non-zero value otherwise *pResOut is set to zero. The return value
6499** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6500*/
6501static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6502 unixFile *pFile = (unixFile*)id;
6503 int rc = proxyTakeConch(pFile);
6504 if( rc==SQLITE_OK ){
6505 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006506 if( pCtx->conchHeld>0 ){
6507 unixFile *proxy = pCtx->lockProxy;
6508 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6509 }else{ /* conchHeld < 0 is lockless */
6510 pResOut=0;
6511 }
drh715ff302008-12-03 22:32:44 +00006512 }
6513 return rc;
6514}
6515
6516/*
drh308c2a52010-05-14 11:30:18 +00006517** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006518** of the following:
6519**
6520** (1) SHARED_LOCK
6521** (2) RESERVED_LOCK
6522** (3) PENDING_LOCK
6523** (4) EXCLUSIVE_LOCK
6524**
6525** Sometimes when requesting one lock state, additional lock states
6526** are inserted in between. The locking might fail on one of the later
6527** transitions leaving the lock state different from what it started but
6528** still short of its goal. The following chart shows the allowed
6529** transitions and the inserted intermediate states:
6530**
6531** UNLOCKED -> SHARED
6532** SHARED -> RESERVED
6533** SHARED -> (PENDING) -> EXCLUSIVE
6534** RESERVED -> (PENDING) -> EXCLUSIVE
6535** PENDING -> EXCLUSIVE
6536**
6537** This routine will only increase a lock. Use the sqlite3OsUnlock()
6538** routine to lower a locking level.
6539*/
drh308c2a52010-05-14 11:30:18 +00006540static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006541 unixFile *pFile = (unixFile*)id;
6542 int rc = proxyTakeConch(pFile);
6543 if( rc==SQLITE_OK ){
6544 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006545 if( pCtx->conchHeld>0 ){
6546 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006547 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6548 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006549 }else{
6550 /* conchHeld < 0 is lockless */
6551 }
drh715ff302008-12-03 22:32:44 +00006552 }
6553 return rc;
6554}
6555
6556
6557/*
drh308c2a52010-05-14 11:30:18 +00006558** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006559** must be either NO_LOCK or SHARED_LOCK.
6560**
6561** If the locking level of the file descriptor is already at or below
6562** the requested locking level, this routine is a no-op.
6563*/
drh308c2a52010-05-14 11:30:18 +00006564static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006565 unixFile *pFile = (unixFile*)id;
6566 int rc = proxyTakeConch(pFile);
6567 if( rc==SQLITE_OK ){
6568 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006569 if( pCtx->conchHeld>0 ){
6570 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006571 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6572 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006573 }else{
6574 /* conchHeld < 0 is lockless */
6575 }
drh715ff302008-12-03 22:32:44 +00006576 }
6577 return rc;
6578}
6579
6580/*
6581** Close a file that uses proxy locks.
6582*/
6583static int proxyClose(sqlite3_file *id) {
6584 if( id ){
6585 unixFile *pFile = (unixFile*)id;
6586 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6587 unixFile *lockProxy = pCtx->lockProxy;
6588 unixFile *conchFile = pCtx->conchFile;
6589 int rc = SQLITE_OK;
6590
6591 if( lockProxy ){
6592 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6593 if( rc ) return rc;
6594 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6595 if( rc ) return rc;
6596 sqlite3_free(lockProxy);
6597 pCtx->lockProxy = 0;
6598 }
6599 if( conchFile ){
6600 if( pCtx->conchHeld ){
6601 rc = proxyReleaseConch(pFile);
6602 if( rc ) return rc;
6603 }
6604 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6605 if( rc ) return rc;
6606 sqlite3_free(conchFile);
6607 }
drhd56b1212010-08-11 06:14:15 +00006608 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006609 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006610 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006611 /* restore the original locking context and pMethod then close it */
6612 pFile->lockingContext = pCtx->oldLockingContext;
6613 pFile->pMethod = pCtx->pOldMethod;
6614 sqlite3_free(pCtx);
6615 return pFile->pMethod->xClose(id);
6616 }
6617 return SQLITE_OK;
6618}
6619
6620
6621
drhd2cb50b2009-01-09 21:41:17 +00006622#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006623/*
6624** The proxy locking style is intended for use with AFP filesystems.
6625** And since AFP is only supported on MacOSX, the proxy locking is also
6626** restricted to MacOSX.
6627**
6628**
6629******************* End of the proxy lock implementation **********************
6630******************************************************************************/
6631
drh734c9862008-11-28 15:37:20 +00006632/*
danielk1977e339d652008-06-28 11:23:00 +00006633** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006634**
6635** This routine registers all VFS implementations for unix-like operating
6636** systems. This routine, and the sqlite3_os_end() routine that follows,
6637** should be the only routines in this file that are visible from other
6638** files.
drh6b9d6dd2008-12-03 19:34:47 +00006639**
6640** This routine is called once during SQLite initialization and by a
6641** single thread. The memory allocation and mutex subsystems have not
6642** necessarily been initialized when this routine is called, and so they
6643** should not be used.
drh153c62c2007-08-24 03:51:33 +00006644*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006645int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006646 /*
6647 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006648 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6649 ** to the "finder" function. (pAppData is a pointer to a pointer because
6650 ** silly C90 rules prohibit a void* from being cast to a function pointer
6651 ** and so we have to go through the intermediate pointer to avoid problems
6652 ** when compiling with -pedantic-errors on GCC.)
6653 **
6654 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006655 ** finder-function. The finder-function returns a pointer to the
6656 ** sqlite_io_methods object that implements the desired locking
6657 ** behaviors. See the division above that contains the IOMETHODS
6658 ** macro for addition information on finder-functions.
6659 **
6660 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6661 ** object. But the "autolockIoFinder" available on MacOSX does a little
6662 ** more than that; it looks at the filesystem type that hosts the
6663 ** database file and tries to choose an locking method appropriate for
6664 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006665 */
drh7708e972008-11-29 00:56:52 +00006666 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006667 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006668 sizeof(unixFile), /* szOsFile */ \
6669 MAX_PATHNAME, /* mxPathname */ \
6670 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006671 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006672 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006673 unixOpen, /* xOpen */ \
6674 unixDelete, /* xDelete */ \
6675 unixAccess, /* xAccess */ \
6676 unixFullPathname, /* xFullPathname */ \
6677 unixDlOpen, /* xDlOpen */ \
6678 unixDlError, /* xDlError */ \
6679 unixDlSym, /* xDlSym */ \
6680 unixDlClose, /* xDlClose */ \
6681 unixRandomness, /* xRandomness */ \
6682 unixSleep, /* xSleep */ \
6683 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006684 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006685 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006686 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006687 unixGetSystemCall, /* xGetSystemCall */ \
6688 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006689 }
6690
drh6b9d6dd2008-12-03 19:34:47 +00006691 /*
6692 ** All default VFSes for unix are contained in the following array.
6693 **
6694 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6695 ** by the SQLite core when the VFS is registered. So the following
6696 ** array cannot be const.
6697 */
danielk1977e339d652008-06-28 11:23:00 +00006698 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006699#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006700 UNIXVFS("unix", autolockIoFinder ),
6701#else
6702 UNIXVFS("unix", posixIoFinder ),
6703#endif
6704 UNIXVFS("unix-none", nolockIoFinder ),
6705 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006706 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006707#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006708 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006709#endif
6710#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006711 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006712#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006713 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006714#endif
chw78a13182009-04-07 05:35:03 +00006715#endif
drhd2cb50b2009-01-09 21:41:17 +00006716#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006717 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006718 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006719 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006720#endif
drh153c62c2007-08-24 03:51:33 +00006721 };
drh6b9d6dd2008-12-03 19:34:47 +00006722 unsigned int i; /* Loop counter */
6723
drh2aa5a002011-04-13 13:42:25 +00006724 /* Double-check that the aSyscall[] array has been constructed
6725 ** correctly. See ticket [bb3a86e890c8e96ab] */
6726 assert( ArraySize(aSyscall)==16 );
6727
drh6b9d6dd2008-12-03 19:34:47 +00006728 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006729 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006730 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006731 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006732 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006733}
danielk1977e339d652008-06-28 11:23:00 +00006734
6735/*
drh6b9d6dd2008-12-03 19:34:47 +00006736** Shutdown the operating system interface.
6737**
6738** Some operating systems might need to do some cleanup in this routine,
6739** to release dynamically allocated objects. But not on unix.
6740** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006741*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006742int sqlite3_os_end(void){
6743 return SQLITE_OK;
6744}
drhdce8bdb2007-08-16 13:01:44 +00006745
danielk197729bafea2008-06-26 10:41:19 +00006746#endif /* SQLITE_OS_UNIX */