blob: 0f003fc4999c5bf82e96441786f80b52b9cebe96 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drhdbe4b882011-06-20 18:00:17 +0000141#ifdef HAVE_UTIME
142# include <utime.h>
143#endif
144
drh9cbe6352005-11-29 03:13:21 +0000145/*
drh7ed97b92010-01-20 13:07:21 +0000146** Allowed values of unixFile.fsFlags
147*/
148#define SQLITE_FSFLAGS_IS_MSDOS 0x1
149
150/*
drhf1a221e2006-01-15 17:27:17 +0000151** If we are to be thread-safe, include the pthreads header and define
152** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000153*/
drhd677b3d2007-08-20 22:48:41 +0000154#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000155# include <pthread.h>
156# define SQLITE_UNIX_THREADS 1
157#endif
158
159/*
160** Default permissions when creating a new file
161*/
162#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
163# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
164#endif
165
danielk1977b4b47412007-08-17 15:53:36 +0000166/*
aswiftaebf4132008-11-21 00:10:35 +0000167 ** Default permissions when creating auto proxy dir
168 */
169#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
170# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
171#endif
172
173/*
danielk1977b4b47412007-08-17 15:53:36 +0000174** Maximum supported path-length.
175*/
176#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000177
drh734c9862008-11-28 15:37:20 +0000178/*
drh734c9862008-11-28 15:37:20 +0000179** Only set the lastErrno if the error code is a real error and not
180** a normal expected return code of SQLITE_BUSY or SQLITE_OK
181*/
182#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
183
drhd91c68f2010-05-14 14:52:25 +0000184/* Forward references */
185typedef struct unixShm unixShm; /* Connection shared memory */
186typedef struct unixShmNode unixShmNode; /* Shared memory instance */
187typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
188typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000189
190/*
dane946c392009-08-22 11:39:46 +0000191** Sometimes, after a file handle is closed by SQLite, the file descriptor
192** cannot be closed immediately. In these cases, instances of the following
193** structure are used to store the file descriptor while waiting for an
194** opportunity to either close or reuse it.
195*/
dane946c392009-08-22 11:39:46 +0000196struct UnixUnusedFd {
197 int fd; /* File descriptor to close */
198 int flags; /* Flags this file descriptor was opened with */
199 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
200};
201
202/*
drh9b35ea62008-11-29 02:20:26 +0000203** The unixFile structure is subclass of sqlite3_file specific to the unix
204** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000205*/
drh054889e2005-11-30 03:20:31 +0000206typedef struct unixFile unixFile;
207struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000208 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000209 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000210 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000211 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000212 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000213 int lastErrno; /* The unix errno from last I/O error */
214 void *lockingContext; /* Locking style specific state */
215 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000216 const char *zPath; /* Name of the file */
217 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000218 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000219#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000220 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000221#endif
drh7ed97b92010-01-20 13:07:21 +0000222#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000223 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000224#endif
225#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000226 int isDelete; /* Delete on close if true */
227 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000228#endif
drh8f941bc2009-01-14 23:03:40 +0000229#ifndef NDEBUG
230 /* The next group of variables are used to track whether or not the
231 ** transaction counter in bytes 24-27 of database files are updated
232 ** whenever any part of the database changes. An assertion fault will
233 ** occur if a file is updated without also updating the transaction
234 ** counter. This test is made to avoid new problems similar to the
235 ** one described by ticket #3584.
236 */
237 unsigned char transCntrChng; /* True if the transaction counter changed */
238 unsigned char dbUpdate; /* True if any part of database file changed */
239 unsigned char inNormalWrite; /* True if in a normal write operation */
240#endif
danielk1977967a4a12007-08-20 14:23:44 +0000241#ifdef SQLITE_TEST
242 /* In test mode, increase the size of this structure a bit so that
243 ** it is larger than the struct CrashFile defined in test6.c.
244 */
245 char aPadding[32];
246#endif
drh9cbe6352005-11-29 03:13:21 +0000247};
248
drh0ccebe72005-06-07 22:22:50 +0000249/*
drha7e61d82011-03-12 17:02:57 +0000250** Allowed values for the unixFile.ctrlFlags bitmask:
251*/
drhf0b190d2011-07-26 16:03:07 +0000252#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
253#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
254#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000255#ifndef SQLITE_DISABLE_DIRSYNC
256# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
257#else
258# define UNIXFILE_DIRSYNC 0x00
259#endif
drha7e61d82011-03-12 17:02:57 +0000260
261/*
drh198bf392006-01-06 21:52:49 +0000262** Include code that is common to all os_*.c files
263*/
264#include "os_common.h"
265
266/*
drh0ccebe72005-06-07 22:22:50 +0000267** Define various macros that are missing from some systems.
268*/
drhbbd42a62004-05-22 17:41:58 +0000269#ifndef O_LARGEFILE
270# define O_LARGEFILE 0
271#endif
272#ifdef SQLITE_DISABLE_LFS
273# undef O_LARGEFILE
274# define O_LARGEFILE 0
275#endif
276#ifndef O_NOFOLLOW
277# define O_NOFOLLOW 0
278#endif
279#ifndef O_BINARY
280# define O_BINARY 0
281#endif
282
283/*
drh2b4b5962005-06-15 17:47:55 +0000284** The threadid macro resolves to the thread-id or to 0. Used for
285** testing and debugging only.
286*/
drhd677b3d2007-08-20 22:48:41 +0000287#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000288#define threadid pthread_self()
289#else
290#define threadid 0
291#endif
292
drh99ab3b12011-03-02 15:09:07 +0000293/*
drh9a3baf12011-04-25 18:01:27 +0000294** Different Unix systems declare open() in different ways. Same use
295** open(const char*,int,mode_t). Others use open(const char*,int,...).
296** The difference is important when using a pointer to the function.
297**
298** The safest way to deal with the problem is to always use this wrapper
299** which always has the same well-defined interface.
300*/
301static int posixOpen(const char *zFile, int flags, int mode){
302 return open(zFile, flags, mode);
303}
304
drh90315a22011-08-10 01:52:12 +0000305/* Forward reference */
306static int openDirectory(const char*, int*);
307
drh9a3baf12011-04-25 18:01:27 +0000308/*
drh99ab3b12011-03-02 15:09:07 +0000309** Many system calls are accessed through pointer-to-functions so that
310** they may be overridden at runtime to facilitate fault injection during
311** testing and sandboxing. The following array holds the names and pointers
312** to all overrideable system calls.
313*/
314static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000315 const char *zName; /* Name of the sytem call */
316 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
317 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000318} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000319 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
320#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000321
drh58ad5802011-03-23 22:02:23 +0000322 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000323#define osClose ((int(*)(int))aSyscall[1].pCurrent)
324
drh58ad5802011-03-23 22:02:23 +0000325 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000326#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
327
drh58ad5802011-03-23 22:02:23 +0000328 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000329#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
330
drh58ad5802011-03-23 22:02:23 +0000331 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000332#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
333
334/*
335** The DJGPP compiler environment looks mostly like Unix, but it
336** lacks the fcntl() system call. So redefine fcntl() to be something
337** that always succeeds. This means that locking does not occur under
338** DJGPP. But it is DOS - what did you expect?
339*/
340#ifdef __DJGPP__
341 { "fstat", 0, 0 },
342#define osFstat(a,b,c) 0
343#else
drh58ad5802011-03-23 22:02:23 +0000344 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
346#endif
347
drh58ad5802011-03-23 22:02:23 +0000348 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000349#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
350
drh58ad5802011-03-23 22:02:23 +0000351 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000352#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000353
drh58ad5802011-03-23 22:02:23 +0000354 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000355#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
356
drhd4a80312011-04-15 14:33:20 +0000357#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000358 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000359#else
drh58ad5802011-03-23 22:02:23 +0000360 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000361#endif
362#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
363
364#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000365 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000366#else
drh58ad5802011-03-23 22:02:23 +0000367 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000368#endif
369#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
370
drh58ad5802011-03-23 22:02:23 +0000371 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000372#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
373
drhd4a80312011-04-15 14:33:20 +0000374#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000375 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000376#else
drh58ad5802011-03-23 22:02:23 +0000377 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000378#endif
379#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
380 aSyscall[12].pCurrent)
381
382#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000383 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000384#else
drh58ad5802011-03-23 22:02:23 +0000385 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000386#endif
387#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
388 aSyscall[13].pCurrent)
389
drha6c47492011-04-11 18:35:09 +0000390#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000391 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000392#else
393 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000394#endif
drh2aa5a002011-04-13 13:42:25 +0000395#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000396
397#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000398 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000399#else
drh58ad5802011-03-23 22:02:23 +0000400 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000401#endif
dan0fd7d862011-03-29 10:04:23 +0000402#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000403
drh036ac7f2011-08-08 23:18:05 +0000404 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
405#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
406
drh90315a22011-08-10 01:52:12 +0000407 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
408#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
409
drh9ef6bc42011-11-04 02:24:02 +0000410 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
411#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
412
413 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
414#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
415
drhe562be52011-03-02 18:01:10 +0000416}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000417
418/*
419** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000420** "unix" VFSes. Return SQLITE_OK opon successfully updating the
421** system call pointer, or SQLITE_NOTFOUND if there is no configurable
422** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000423*/
424static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000425 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
426 const char *zName, /* Name of system call to override */
427 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000428){
drh58ad5802011-03-23 22:02:23 +0000429 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000430 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000431
432 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000433 if( zName==0 ){
434 /* If no zName is given, restore all system calls to their default
435 ** settings and return NULL
436 */
dan51438a72011-04-02 17:00:47 +0000437 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000438 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
439 if( aSyscall[i].pDefault ){
440 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000441 }
442 }
443 }else{
444 /* If zName is specified, operate on only the one system call
445 ** specified.
446 */
447 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
448 if( strcmp(zName, aSyscall[i].zName)==0 ){
449 if( aSyscall[i].pDefault==0 ){
450 aSyscall[i].pDefault = aSyscall[i].pCurrent;
451 }
drh1df30962011-03-02 19:06:42 +0000452 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000453 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
454 aSyscall[i].pCurrent = pNewFunc;
455 break;
456 }
457 }
458 }
459 return rc;
460}
461
drh1df30962011-03-02 19:06:42 +0000462/*
463** Return the value of a system call. Return NULL if zName is not a
464** recognized system call name. NULL is also returned if the system call
465** is currently undefined.
466*/
drh58ad5802011-03-23 22:02:23 +0000467static sqlite3_syscall_ptr unixGetSystemCall(
468 sqlite3_vfs *pNotUsed,
469 const char *zName
470){
471 unsigned int i;
472
473 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000474 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
475 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
476 }
477 return 0;
478}
479
480/*
481** Return the name of the first system call after zName. If zName==NULL
482** then return the name of the first system call. Return NULL if zName
483** is the last system call or if zName is not the name of a valid
484** system call.
485*/
486static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000487 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000488
489 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000490 if( zName ){
491 for(i=0; i<ArraySize(aSyscall)-1; i++){
492 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000493 }
494 }
dan0fd7d862011-03-29 10:04:23 +0000495 for(i++; i<ArraySize(aSyscall); i++){
496 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000497 }
498 return 0;
499}
500
drhad4f1e52011-03-04 15:43:57 +0000501/*
502** Retry open() calls that fail due to EINTR
503*/
504static int robust_open(const char *z, int f, int m){
505 int rc;
506 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
507 return rc;
508}
danielk197713adf8a2004-06-03 16:08:41 +0000509
drh107886a2008-11-21 22:21:50 +0000510/*
dan9359c7b2009-08-21 08:29:10 +0000511** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000512** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000513** vxworksFileId objects used by this file, all of which may be
514** shared by multiple threads.
515**
516** Function unixMutexHeld() is used to assert() that the global mutex
517** is held when required. This function is only used as part of assert()
518** statements. e.g.
519**
520** unixEnterMutex()
521** assert( unixMutexHeld() );
522** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000523*/
524static void unixEnterMutex(void){
525 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
526}
527static void unixLeaveMutex(void){
528 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
529}
dan9359c7b2009-08-21 08:29:10 +0000530#ifdef SQLITE_DEBUG
531static int unixMutexHeld(void) {
532 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
533}
534#endif
drh107886a2008-11-21 22:21:50 +0000535
drh734c9862008-11-28 15:37:20 +0000536
drh30ddce62011-10-15 00:16:30 +0000537#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000538/*
539** Helper function for printing out trace information from debugging
540** binaries. This returns the string represetation of the supplied
541** integer lock-type.
542*/
drh308c2a52010-05-14 11:30:18 +0000543static const char *azFileLock(int eFileLock){
544 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000545 case NO_LOCK: return "NONE";
546 case SHARED_LOCK: return "SHARED";
547 case RESERVED_LOCK: return "RESERVED";
548 case PENDING_LOCK: return "PENDING";
549 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000550 }
551 return "ERROR";
552}
553#endif
554
555#ifdef SQLITE_LOCK_TRACE
556/*
557** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000558**
drh734c9862008-11-28 15:37:20 +0000559** This routine is used for troubleshooting locks on multithreaded
560** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
561** command-line option on the compiler. This code is normally
562** turned off.
563*/
564static int lockTrace(int fd, int op, struct flock *p){
565 char *zOpName, *zType;
566 int s;
567 int savedErrno;
568 if( op==F_GETLK ){
569 zOpName = "GETLK";
570 }else if( op==F_SETLK ){
571 zOpName = "SETLK";
572 }else{
drh99ab3b12011-03-02 15:09:07 +0000573 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000574 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
575 return s;
576 }
577 if( p->l_type==F_RDLCK ){
578 zType = "RDLCK";
579 }else if( p->l_type==F_WRLCK ){
580 zType = "WRLCK";
581 }else if( p->l_type==F_UNLCK ){
582 zType = "UNLCK";
583 }else{
584 assert( 0 );
585 }
586 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000587 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000588 savedErrno = errno;
589 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
590 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
591 (int)p->l_pid, s);
592 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
593 struct flock l2;
594 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000595 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000596 if( l2.l_type==F_RDLCK ){
597 zType = "RDLCK";
598 }else if( l2.l_type==F_WRLCK ){
599 zType = "WRLCK";
600 }else if( l2.l_type==F_UNLCK ){
601 zType = "UNLCK";
602 }else{
603 assert( 0 );
604 }
605 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
606 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
607 }
608 errno = savedErrno;
609 return s;
610}
drh99ab3b12011-03-02 15:09:07 +0000611#undef osFcntl
612#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000613#endif /* SQLITE_LOCK_TRACE */
614
drhff812312011-02-23 13:33:46 +0000615/*
616** Retry ftruncate() calls that fail due to EINTR
617*/
drhff812312011-02-23 13:33:46 +0000618static int robust_ftruncate(int h, sqlite3_int64 sz){
619 int rc;
drh99ab3b12011-03-02 15:09:07 +0000620 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000621 return rc;
622}
drh734c9862008-11-28 15:37:20 +0000623
624/*
625** This routine translates a standard POSIX errno code into something
626** useful to the clients of the sqlite3 functions. Specifically, it is
627** intended to translate a variety of "try again" errors into SQLITE_BUSY
628** and a variety of "please close the file descriptor NOW" errors into
629** SQLITE_IOERR
630**
631** Errors during initialization of locks, or file system support for locks,
632** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
633*/
634static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
635 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000636#if 0
637 /* At one point this code was not commented out. In theory, this branch
638 ** should never be hit, as this function should only be called after
639 ** a locking-related function (i.e. fcntl()) has returned non-zero with
640 ** the value of errno as the first argument. Since a system call has failed,
641 ** errno should be non-zero.
642 **
643 ** Despite this, if errno really is zero, we still don't want to return
644 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
645 ** propagated back to the caller. Commenting this branch out means errno==0
646 ** will be handled by the "default:" case below.
647 */
drh734c9862008-11-28 15:37:20 +0000648 case 0:
649 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000650#endif
651
drh734c9862008-11-28 15:37:20 +0000652 case EAGAIN:
653 case ETIMEDOUT:
654 case EBUSY:
655 case EINTR:
656 case ENOLCK:
657 /* random NFS retry error, unless during file system support
658 * introspection, in which it actually means what it says */
659 return SQLITE_BUSY;
660
661 case EACCES:
662 /* EACCES is like EAGAIN during locking operations, but not any other time*/
663 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
664 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
665 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
666 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
667 return SQLITE_BUSY;
668 }
669 /* else fall through */
670 case EPERM:
671 return SQLITE_PERM;
672
danea83bc62011-04-01 11:56:32 +0000673 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
674 ** this module never makes such a call. And the code in SQLite itself
675 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
676 ** this case is also commented out. If the system does set errno to EDEADLK,
677 ** the default SQLITE_IOERR_XXX code will be returned. */
678#if 0
drh734c9862008-11-28 15:37:20 +0000679 case EDEADLK:
680 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000681#endif
drh734c9862008-11-28 15:37:20 +0000682
683#if EOPNOTSUPP!=ENOTSUP
684 case EOPNOTSUPP:
685 /* something went terribly awry, unless during file system support
686 * introspection, in which it actually means what it says */
687#endif
688#ifdef ENOTSUP
689 case ENOTSUP:
690 /* invalid fd, unless during file system support introspection, in which
691 * it actually means what it says */
692#endif
693 case EIO:
694 case EBADF:
695 case EINVAL:
696 case ENOTCONN:
697 case ENODEV:
698 case ENXIO:
699 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000700#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000701 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000702#endif
drh734c9862008-11-28 15:37:20 +0000703 case ENOSYS:
704 /* these should force the client to close the file and reconnect */
705
706 default:
707 return sqliteIOErr;
708 }
709}
710
711
712
713/******************************************************************************
714****************** Begin Unique File ID Utility Used By VxWorks ***************
715**
716** On most versions of unix, we can get a unique ID for a file by concatenating
717** the device number and the inode number. But this does not work on VxWorks.
718** On VxWorks, a unique file id must be based on the canonical filename.
719**
720** A pointer to an instance of the following structure can be used as a
721** unique file ID in VxWorks. Each instance of this structure contains
722** a copy of the canonical filename. There is also a reference count.
723** The structure is reclaimed when the number of pointers to it drops to
724** zero.
725**
726** There are never very many files open at one time and lookups are not
727** a performance-critical path, so it is sufficient to put these
728** structures on a linked list.
729*/
730struct vxworksFileId {
731 struct vxworksFileId *pNext; /* Next in a list of them all */
732 int nRef; /* Number of references to this one */
733 int nName; /* Length of the zCanonicalName[] string */
734 char *zCanonicalName; /* Canonical filename */
735};
736
737#if OS_VXWORKS
738/*
drh9b35ea62008-11-29 02:20:26 +0000739** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000740** variable:
741*/
742static struct vxworksFileId *vxworksFileList = 0;
743
744/*
745** Simplify a filename into its canonical form
746** by making the following changes:
747**
748** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000749** * convert /./ into just /
750** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000751**
752** Changes are made in-place. Return the new name length.
753**
754** The original filename is in z[0..n-1]. Return the number of
755** characters in the simplified name.
756*/
757static int vxworksSimplifyName(char *z, int n){
758 int i, j;
759 while( n>1 && z[n-1]=='/' ){ n--; }
760 for(i=j=0; i<n; i++){
761 if( z[i]=='/' ){
762 if( z[i+1]=='/' ) continue;
763 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
764 i += 1;
765 continue;
766 }
767 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
768 while( j>0 && z[j-1]!='/' ){ j--; }
769 if( j>0 ){ j--; }
770 i += 2;
771 continue;
772 }
773 }
774 z[j++] = z[i];
775 }
776 z[j] = 0;
777 return j;
778}
779
780/*
781** Find a unique file ID for the given absolute pathname. Return
782** a pointer to the vxworksFileId object. This pointer is the unique
783** file ID.
784**
785** The nRef field of the vxworksFileId object is incremented before
786** the object is returned. A new vxworksFileId object is created
787** and added to the global list if necessary.
788**
789** If a memory allocation error occurs, return NULL.
790*/
791static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
792 struct vxworksFileId *pNew; /* search key and new file ID */
793 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
794 int n; /* Length of zAbsoluteName string */
795
796 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000797 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000798 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
799 if( pNew==0 ) return 0;
800 pNew->zCanonicalName = (char*)&pNew[1];
801 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
802 n = vxworksSimplifyName(pNew->zCanonicalName, n);
803
804 /* Search for an existing entry that matching the canonical name.
805 ** If found, increment the reference count and return a pointer to
806 ** the existing file ID.
807 */
808 unixEnterMutex();
809 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
810 if( pCandidate->nName==n
811 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
812 ){
813 sqlite3_free(pNew);
814 pCandidate->nRef++;
815 unixLeaveMutex();
816 return pCandidate;
817 }
818 }
819
820 /* No match was found. We will make a new file ID */
821 pNew->nRef = 1;
822 pNew->nName = n;
823 pNew->pNext = vxworksFileList;
824 vxworksFileList = pNew;
825 unixLeaveMutex();
826 return pNew;
827}
828
829/*
830** Decrement the reference count on a vxworksFileId object. Free
831** the object when the reference count reaches zero.
832*/
833static void vxworksReleaseFileId(struct vxworksFileId *pId){
834 unixEnterMutex();
835 assert( pId->nRef>0 );
836 pId->nRef--;
837 if( pId->nRef==0 ){
838 struct vxworksFileId **pp;
839 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
840 assert( *pp==pId );
841 *pp = pId->pNext;
842 sqlite3_free(pId);
843 }
844 unixLeaveMutex();
845}
846#endif /* OS_VXWORKS */
847/*************** End of Unique File ID Utility Used By VxWorks ****************
848******************************************************************************/
849
850
851/******************************************************************************
852*************************** Posix Advisory Locking ****************************
853**
drh9b35ea62008-11-29 02:20:26 +0000854** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000855** section 6.5.2.2 lines 483 through 490 specify that when a process
856** sets or clears a lock, that operation overrides any prior locks set
857** by the same process. It does not explicitly say so, but this implies
858** that it overrides locks set by the same process using a different
859** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000860**
861** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000862** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
863**
864** Suppose ./file1 and ./file2 are really the same file (because
865** one is a hard or symbolic link to the other) then if you set
866** an exclusive lock on fd1, then try to get an exclusive lock
867** on fd2, it works. I would have expected the second lock to
868** fail since there was already a lock on the file due to fd1.
869** But not so. Since both locks came from the same process, the
870** second overrides the first, even though they were on different
871** file descriptors opened on different file names.
872**
drh734c9862008-11-28 15:37:20 +0000873** This means that we cannot use POSIX locks to synchronize file access
874** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000875** to synchronize access for threads in separate processes, but not
876** threads within the same process.
877**
878** To work around the problem, SQLite has to manage file locks internally
879** on its own. Whenever a new database is opened, we have to find the
880** specific inode of the database file (the inode is determined by the
881** st_dev and st_ino fields of the stat structure that fstat() fills in)
882** and check for locks already existing on that inode. When locks are
883** created or removed, we have to look at our own internal record of the
884** locks to see if another thread has previously set a lock on that same
885** inode.
886**
drh9b35ea62008-11-29 02:20:26 +0000887** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
888** For VxWorks, we have to use the alternative unique ID system based on
889** canonical filename and implemented in the previous division.)
890**
danielk1977ad94b582007-08-20 06:44:22 +0000891** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000892** descriptor. It is now a structure that holds the integer file
893** descriptor and a pointer to a structure that describes the internal
894** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000895** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000896** point to the same locking structure. The locking structure keeps
897** a reference count (so we will know when to delete it) and a "cnt"
898** field that tells us its internal lock status. cnt==0 means the
899** file is unlocked. cnt==-1 means the file has an exclusive lock.
900** cnt>0 means there are cnt shared locks on the file.
901**
902** Any attempt to lock or unlock a file first checks the locking
903** structure. The fcntl() system call is only invoked to set a
904** POSIX lock if the internal lock structure transitions between
905** a locked and an unlocked state.
906**
drh734c9862008-11-28 15:37:20 +0000907** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000908**
909** If you close a file descriptor that points to a file that has locks,
910** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000911** released. To work around this problem, each unixInodeInfo object
912** maintains a count of the number of pending locks on tha inode.
913** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000914** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000915** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000916** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000917** be closed and that list is walked (and cleared) when the last lock
918** clears.
919**
drh9b35ea62008-11-29 02:20:26 +0000920** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000921**
drh9b35ea62008-11-29 02:20:26 +0000922** Many older versions of linux use the LinuxThreads library which is
923** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000924** A cannot be modified or overridden by a different thread B.
925** Only thread A can modify the lock. Locking behavior is correct
926** if the appliation uses the newer Native Posix Thread Library (NPTL)
927** on linux - with NPTL a lock created by thread A can override locks
928** in thread B. But there is no way to know at compile-time which
929** threading library is being used. So there is no way to know at
930** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000931** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000932** current process.
drh5fdae772004-06-29 03:29:00 +0000933**
drh8af6c222010-05-14 12:43:01 +0000934** SQLite used to support LinuxThreads. But support for LinuxThreads
935** was dropped beginning with version 3.7.0. SQLite will still work with
936** LinuxThreads provided that (1) there is no more than one connection
937** per database file in the same process and (2) database connections
938** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000939*/
940
941/*
942** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000943** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000944*/
945struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000946 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000947#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000948 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000949#else
drh107886a2008-11-21 22:21:50 +0000950 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000951#endif
952};
953
954/*
drhbbd42a62004-05-22 17:41:58 +0000955** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000956** inode. Or, on LinuxThreads, there is one of these structures for
957** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000958**
danielk1977ad94b582007-08-20 06:44:22 +0000959** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000960** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000961** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000962*/
drh8af6c222010-05-14 12:43:01 +0000963struct unixInodeInfo {
964 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000965 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000966 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
967 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000968 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000969 unixShmNode *pShmNode; /* Shared memory associated with this inode */
970 int nLock; /* Number of outstanding file locks */
971 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
972 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
973 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000974#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000975 unsigned long long sharedByte; /* for AFP simulated shared lock */
976#endif
drh6c7d5c52008-11-21 20:32:33 +0000977#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000978 sem_t *pSem; /* Named POSIX semaphore */
979 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000980#endif
drhbbd42a62004-05-22 17:41:58 +0000981};
982
drhda0e7682008-07-30 15:27:54 +0000983/*
drh8af6c222010-05-14 12:43:01 +0000984** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000985*/
drhd91c68f2010-05-14 14:52:25 +0000986static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000987
drh5fdae772004-06-29 03:29:00 +0000988/*
dane18d4952011-02-21 11:46:24 +0000989**
990** This function - unixLogError_x(), is only ever called via the macro
991** unixLogError().
992**
993** It is invoked after an error occurs in an OS function and errno has been
994** set. It logs a message using sqlite3_log() containing the current value of
995** errno and, if possible, the human-readable equivalent from strerror() or
996** strerror_r().
997**
998** The first argument passed to the macro should be the error code that
999** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1000** The two subsequent arguments should be the name of the OS function that
1001** failed (e.g. "unlink", "open") and the the associated file-system path,
1002** if any.
1003*/
drh0e9365c2011-03-02 02:08:13 +00001004#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1005static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001006 int errcode, /* SQLite error code */
1007 const char *zFunc, /* Name of OS function that failed */
1008 const char *zPath, /* File path associated with error */
1009 int iLine /* Source line number where error occurred */
1010){
1011 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001012 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001013
1014 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1015 ** the strerror() function to obtain the human-readable error message
1016 ** equivalent to errno. Otherwise, use strerror_r().
1017 */
1018#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1019 char aErr[80];
1020 memset(aErr, 0, sizeof(aErr));
1021 zErr = aErr;
1022
1023 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1024 ** assume that the system provides the the GNU version of strerror_r() that
1025 ** returns a pointer to a buffer containing the error message. That pointer
1026 ** may point to aErr[], or it may point to some static storage somewhere.
1027 ** Otherwise, assume that the system provides the POSIX version of
1028 ** strerror_r(), which always writes an error message into aErr[].
1029 **
1030 ** If the code incorrectly assumes that it is the POSIX version that is
1031 ** available, the error message will often be an empty string. Not a
1032 ** huge problem. Incorrectly concluding that the GNU version is available
1033 ** could lead to a segfault though.
1034 */
1035#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1036 zErr =
1037# endif
drh0e9365c2011-03-02 02:08:13 +00001038 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001039
1040#elif SQLITE_THREADSAFE
1041 /* This is a threadsafe build, but strerror_r() is not available. */
1042 zErr = "";
1043#else
1044 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001045 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001046#endif
1047
1048 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001049 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001050 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001051 "os_unix.c:%d: (%d) %s(%s) - %s",
1052 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001053 );
1054
1055 return errcode;
1056}
1057
drh0e9365c2011-03-02 02:08:13 +00001058/*
1059** Close a file descriptor.
1060**
1061** We assume that close() almost always works, since it is only in a
1062** very sick application or on a very sick platform that it might fail.
1063** If it does fail, simply leak the file descriptor, but do log the
1064** error.
1065**
1066** Note that it is not safe to retry close() after EINTR since the
1067** file descriptor might have already been reused by another thread.
1068** So we don't even try to recover from an EINTR. Just log the error
1069** and move on.
1070*/
1071static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001072 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001073 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1074 pFile ? pFile->zPath : 0, lineno);
1075 }
1076}
dane18d4952011-02-21 11:46:24 +00001077
1078/*
danb0ac3e32010-06-16 10:55:42 +00001079** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001080*/
drh0e9365c2011-03-02 02:08:13 +00001081static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001082 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001083 UnixUnusedFd *p;
1084 UnixUnusedFd *pNext;
1085 for(p=pInode->pUnused; p; p=pNext){
1086 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001087 robust_close(pFile, p->fd, __LINE__);
1088 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001089 }
drh0e9365c2011-03-02 02:08:13 +00001090 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001091}
1092
1093/*
drh8af6c222010-05-14 12:43:01 +00001094** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001095**
1096** The mutex entered using the unixEnterMutex() function must be held
1097** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001098*/
danb0ac3e32010-06-16 10:55:42 +00001099static void releaseInodeInfo(unixFile *pFile){
1100 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001101 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001102 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001103 pInode->nRef--;
1104 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001105 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001106 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001107 if( pInode->pPrev ){
1108 assert( pInode->pPrev->pNext==pInode );
1109 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001110 }else{
drh8af6c222010-05-14 12:43:01 +00001111 assert( inodeList==pInode );
1112 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001113 }
drh8af6c222010-05-14 12:43:01 +00001114 if( pInode->pNext ){
1115 assert( pInode->pNext->pPrev==pInode );
1116 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001117 }
drh8af6c222010-05-14 12:43:01 +00001118 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001119 }
drhbbd42a62004-05-22 17:41:58 +00001120 }
1121}
1122
1123/*
drh8af6c222010-05-14 12:43:01 +00001124** Given a file descriptor, locate the unixInodeInfo object that
1125** describes that file descriptor. Create a new one if necessary. The
1126** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001127**
dan9359c7b2009-08-21 08:29:10 +00001128** The mutex entered using the unixEnterMutex() function must be held
1129** when this function is called.
1130**
drh6c7d5c52008-11-21 20:32:33 +00001131** Return an appropriate error code.
1132*/
drh8af6c222010-05-14 12:43:01 +00001133static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001134 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001135 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001136){
1137 int rc; /* System call return code */
1138 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001139 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1140 struct stat statbuf; /* Low-level file information */
1141 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001142
dan9359c7b2009-08-21 08:29:10 +00001143 assert( unixMutexHeld() );
1144
drh6c7d5c52008-11-21 20:32:33 +00001145 /* Get low-level information about the file that we can used to
1146 ** create a unique name for the file.
1147 */
1148 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001149 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001150 if( rc!=0 ){
1151 pFile->lastErrno = errno;
1152#ifdef EOVERFLOW
1153 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1154#endif
1155 return SQLITE_IOERR;
1156 }
1157
drheb0d74f2009-02-03 15:27:02 +00001158#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001159 /* On OS X on an msdos filesystem, the inode number is reported
1160 ** incorrectly for zero-size files. See ticket #3260. To work
1161 ** around this problem (we consider it a bug in OS X, not SQLite)
1162 ** we always increase the file size to 1 by writing a single byte
1163 ** prior to accessing the inode number. The one byte written is
1164 ** an ASCII 'S' character which also happens to be the first byte
1165 ** in the header of every SQLite database. In this way, if there
1166 ** is a race condition such that another thread has already populated
1167 ** the first page of the database, no damage is done.
1168 */
drh7ed97b92010-01-20 13:07:21 +00001169 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001170 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001171 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001172 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001173 return SQLITE_IOERR;
1174 }
drh99ab3b12011-03-02 15:09:07 +00001175 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001176 if( rc!=0 ){
1177 pFile->lastErrno = errno;
1178 return SQLITE_IOERR;
1179 }
1180 }
drheb0d74f2009-02-03 15:27:02 +00001181#endif
drh6c7d5c52008-11-21 20:32:33 +00001182
drh8af6c222010-05-14 12:43:01 +00001183 memset(&fileId, 0, sizeof(fileId));
1184 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001185#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001186 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001187#else
drh8af6c222010-05-14 12:43:01 +00001188 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001189#endif
drh8af6c222010-05-14 12:43:01 +00001190 pInode = inodeList;
1191 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1192 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001193 }
drh8af6c222010-05-14 12:43:01 +00001194 if( pInode==0 ){
1195 pInode = sqlite3_malloc( sizeof(*pInode) );
1196 if( pInode==0 ){
1197 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001198 }
drh8af6c222010-05-14 12:43:01 +00001199 memset(pInode, 0, sizeof(*pInode));
1200 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1201 pInode->nRef = 1;
1202 pInode->pNext = inodeList;
1203 pInode->pPrev = 0;
1204 if( inodeList ) inodeList->pPrev = pInode;
1205 inodeList = pInode;
1206 }else{
1207 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001208 }
drh8af6c222010-05-14 12:43:01 +00001209 *ppInode = pInode;
1210 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001211}
drh6c7d5c52008-11-21 20:32:33 +00001212
aswift5b1a2562008-08-22 00:22:35 +00001213
1214/*
danielk197713adf8a2004-06-03 16:08:41 +00001215** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001216** file by this or any other process. If such a lock is held, set *pResOut
1217** to a non-zero value otherwise *pResOut is set to zero. The return value
1218** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001219*/
danielk1977861f7452008-06-05 11:39:11 +00001220static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001221 int rc = SQLITE_OK;
1222 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001223 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001224
danielk1977861f7452008-06-05 11:39:11 +00001225 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1226
drh054889e2005-11-30 03:20:31 +00001227 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001228 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001229
1230 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001231 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001232 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001233 }
1234
drh2ac3ee92004-06-07 16:27:46 +00001235 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001236 */
danielk197709480a92009-02-09 05:32:32 +00001237#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001238 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001239 struct flock lock;
1240 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001241 lock.l_start = RESERVED_BYTE;
1242 lock.l_len = 1;
1243 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001244 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1245 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1246 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001247 } else if( lock.l_type!=F_UNLCK ){
1248 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001249 }
1250 }
danielk197709480a92009-02-09 05:32:32 +00001251#endif
danielk197713adf8a2004-06-03 16:08:41 +00001252
drh6c7d5c52008-11-21 20:32:33 +00001253 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001254 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001255
aswift5b1a2562008-08-22 00:22:35 +00001256 *pResOut = reserved;
1257 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001258}
1259
1260/*
drha7e61d82011-03-12 17:02:57 +00001261** Attempt to set a system-lock on the file pFile. The lock is
1262** described by pLock.
1263**
drh77197112011-03-15 19:08:48 +00001264** If the pFile was opened read/write from unix-excl, then the only lock
1265** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001266** the first time any lock is attempted. All subsequent system locking
1267** operations become no-ops. Locking operations still happen internally,
1268** in order to coordinate access between separate database connections
1269** within this process, but all of that is handled in memory and the
1270** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001271**
1272** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1273** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1274** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001275**
1276** Zero is returned if the call completes successfully, or -1 if a call
1277** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001278*/
1279static int unixFileLock(unixFile *pFile, struct flock *pLock){
1280 int rc;
drh3cb93392011-03-12 18:10:44 +00001281 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001282 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001283 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001284 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1285 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1286 ){
drh3cb93392011-03-12 18:10:44 +00001287 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001288 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001289 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001290 lock.l_whence = SEEK_SET;
1291 lock.l_start = SHARED_FIRST;
1292 lock.l_len = SHARED_SIZE;
1293 lock.l_type = F_WRLCK;
1294 rc = osFcntl(pFile->h, F_SETLK, &lock);
1295 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001296 pInode->bProcessLock = 1;
1297 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001298 }else{
1299 rc = 0;
1300 }
1301 }else{
1302 rc = osFcntl(pFile->h, F_SETLK, pLock);
1303 }
1304 return rc;
1305}
1306
1307/*
drh308c2a52010-05-14 11:30:18 +00001308** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001309** of the following:
1310**
drh2ac3ee92004-06-07 16:27:46 +00001311** (1) SHARED_LOCK
1312** (2) RESERVED_LOCK
1313** (3) PENDING_LOCK
1314** (4) EXCLUSIVE_LOCK
1315**
drhb3e04342004-06-08 00:47:47 +00001316** Sometimes when requesting one lock state, additional lock states
1317** are inserted in between. The locking might fail on one of the later
1318** transitions leaving the lock state different from what it started but
1319** still short of its goal. The following chart shows the allowed
1320** transitions and the inserted intermediate states:
1321**
1322** UNLOCKED -> SHARED
1323** SHARED -> RESERVED
1324** SHARED -> (PENDING) -> EXCLUSIVE
1325** RESERVED -> (PENDING) -> EXCLUSIVE
1326** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001327**
drha6abd042004-06-09 17:37:22 +00001328** This routine will only increase a lock. Use the sqlite3OsUnlock()
1329** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001330*/
drh308c2a52010-05-14 11:30:18 +00001331static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001332 /* The following describes the implementation of the various locks and
1333 ** lock transitions in terms of the POSIX advisory shared and exclusive
1334 ** lock primitives (called read-locks and write-locks below, to avoid
1335 ** confusion with SQLite lock names). The algorithms are complicated
1336 ** slightly in order to be compatible with windows systems simultaneously
1337 ** accessing the same database file, in case that is ever required.
1338 **
1339 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1340 ** byte', each single bytes at well known offsets, and the 'shared byte
1341 ** range', a range of 510 bytes at a well known offset.
1342 **
1343 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1344 ** byte'. If this is successful, a random byte from the 'shared byte
1345 ** range' is read-locked and the lock on the 'pending byte' released.
1346 **
danielk197790ba3bd2004-06-25 08:32:25 +00001347 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1348 ** A RESERVED lock is implemented by grabbing a write-lock on the
1349 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001350 **
1351 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001352 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1353 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1354 ** obtained, but existing SHARED locks are allowed to persist. A process
1355 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1356 ** This property is used by the algorithm for rolling back a journal file
1357 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001358 **
danielk197790ba3bd2004-06-25 08:32:25 +00001359 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1360 ** implemented by obtaining a write-lock on the entire 'shared byte
1361 ** range'. Since all other locks require a read-lock on one of the bytes
1362 ** within this range, this ensures that no other locks are held on the
1363 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001364 **
1365 ** The reason a single byte cannot be used instead of the 'shared byte
1366 ** range' is that some versions of windows do not support read-locks. By
1367 ** locking a random byte from a range, concurrent SHARED locks may exist
1368 ** even if the locking primitive used is always a write-lock.
1369 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001370 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001371 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001372 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001373 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001374 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001375
drh054889e2005-11-30 03:20:31 +00001376 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001377 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1378 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001379 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001380
1381 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001382 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001383 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001384 */
drh308c2a52010-05-14 11:30:18 +00001385 if( pFile->eFileLock>=eFileLock ){
1386 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1387 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001388 return SQLITE_OK;
1389 }
1390
drh0c2694b2009-09-03 16:23:44 +00001391 /* Make sure the locking sequence is correct.
1392 ** (1) We never move from unlocked to anything higher than shared lock.
1393 ** (2) SQLite never explicitly requests a pendig lock.
1394 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001395 */
drh308c2a52010-05-14 11:30:18 +00001396 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1397 assert( eFileLock!=PENDING_LOCK );
1398 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001399
drh8af6c222010-05-14 12:43:01 +00001400 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001401 */
drh6c7d5c52008-11-21 20:32:33 +00001402 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001403 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001404
danielk1977ad94b582007-08-20 06:44:22 +00001405 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001406 ** handle that precludes the requested lock, return BUSY.
1407 */
drh8af6c222010-05-14 12:43:01 +00001408 if( (pFile->eFileLock!=pInode->eFileLock &&
1409 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001410 ){
1411 rc = SQLITE_BUSY;
1412 goto end_lock;
1413 }
1414
1415 /* If a SHARED lock is requested, and some thread using this PID already
1416 ** has a SHARED or RESERVED lock, then increment reference counts and
1417 ** return SQLITE_OK.
1418 */
drh308c2a52010-05-14 11:30:18 +00001419 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001420 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001421 assert( eFileLock==SHARED_LOCK );
1422 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001423 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001424 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001425 pInode->nShared++;
1426 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001427 goto end_lock;
1428 }
1429
danielk19779a1d0ab2004-06-01 14:09:28 +00001430
drh3cde3bb2004-06-12 02:17:14 +00001431 /* A PENDING lock is needed before acquiring a SHARED lock and before
1432 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1433 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001434 */
drh0c2694b2009-09-03 16:23:44 +00001435 lock.l_len = 1L;
1436 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001437 if( eFileLock==SHARED_LOCK
1438 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001439 ){
drh308c2a52010-05-14 11:30:18 +00001440 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001441 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001442 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001443 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001444 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001445 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001446 pFile->lastErrno = tErrno;
1447 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001448 goto end_lock;
1449 }
drh3cde3bb2004-06-12 02:17:14 +00001450 }
1451
1452
1453 /* If control gets to this point, then actually go ahead and make
1454 ** operating system calls for the specified lock.
1455 */
drh308c2a52010-05-14 11:30:18 +00001456 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001457 assert( pInode->nShared==0 );
1458 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001459 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001460
drh2ac3ee92004-06-07 16:27:46 +00001461 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001462 lock.l_start = SHARED_FIRST;
1463 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001464 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001465 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001466 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001467 }
dan661d71a2011-03-30 19:08:03 +00001468
drh2ac3ee92004-06-07 16:27:46 +00001469 /* Drop the temporary PENDING lock */
1470 lock.l_start = PENDING_BYTE;
1471 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001472 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001473 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1474 /* This could happen with a network mount */
1475 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001476 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001477 }
dan661d71a2011-03-30 19:08:03 +00001478
1479 if( rc ){
1480 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001481 pFile->lastErrno = tErrno;
1482 }
dan661d71a2011-03-30 19:08:03 +00001483 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001484 }else{
drh308c2a52010-05-14 11:30:18 +00001485 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001486 pInode->nLock++;
1487 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001488 }
drh8af6c222010-05-14 12:43:01 +00001489 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001490 /* We are trying for an exclusive lock but another thread in this
1491 ** same process is still holding a shared lock. */
1492 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001493 }else{
drh3cde3bb2004-06-12 02:17:14 +00001494 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001495 ** assumed that there is a SHARED or greater lock on the file
1496 ** already.
1497 */
drh308c2a52010-05-14 11:30:18 +00001498 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001499 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001500
1501 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1502 if( eFileLock==RESERVED_LOCK ){
1503 lock.l_start = RESERVED_BYTE;
1504 lock.l_len = 1L;
1505 }else{
1506 lock.l_start = SHARED_FIRST;
1507 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001508 }
dan661d71a2011-03-30 19:08:03 +00001509
1510 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001511 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001512 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001513 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001514 pFile->lastErrno = tErrno;
1515 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001516 }
drhbbd42a62004-05-22 17:41:58 +00001517 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001518
drh8f941bc2009-01-14 23:03:40 +00001519
1520#ifndef NDEBUG
1521 /* Set up the transaction-counter change checking flags when
1522 ** transitioning from a SHARED to a RESERVED lock. The change
1523 ** from SHARED to RESERVED marks the beginning of a normal
1524 ** write operation (not a hot journal rollback).
1525 */
1526 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001527 && pFile->eFileLock<=SHARED_LOCK
1528 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001529 ){
1530 pFile->transCntrChng = 0;
1531 pFile->dbUpdate = 0;
1532 pFile->inNormalWrite = 1;
1533 }
1534#endif
1535
1536
danielk1977ecb2a962004-06-02 06:30:16 +00001537 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001538 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001539 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001540 }else if( eFileLock==EXCLUSIVE_LOCK ){
1541 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001542 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001543 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001544
1545end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001546 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001547 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1548 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001549 return rc;
1550}
1551
1552/*
dan08da86a2009-08-21 17:18:03 +00001553** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001554** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001555*/
1556static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001557 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001558 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001559 p->pNext = pInode->pUnused;
1560 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001561 pFile->h = -1;
1562 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001563}
1564
1565/*
drh308c2a52010-05-14 11:30:18 +00001566** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001567** must be either NO_LOCK or SHARED_LOCK.
1568**
1569** If the locking level of the file descriptor is already at or below
1570** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001571**
1572** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1573** the byte range is divided into 2 parts and the first part is unlocked then
1574** set to a read lock, then the other part is simply unlocked. This works
1575** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1576** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001577*/
drha7e61d82011-03-12 17:02:57 +00001578static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001579 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001580 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001581 struct flock lock;
1582 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001583
drh054889e2005-11-30 03:20:31 +00001584 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001585 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001586 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001587 getpid()));
drha6abd042004-06-09 17:37:22 +00001588
drh308c2a52010-05-14 11:30:18 +00001589 assert( eFileLock<=SHARED_LOCK );
1590 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001591 return SQLITE_OK;
1592 }
drh6c7d5c52008-11-21 20:32:33 +00001593 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001594 pInode = pFile->pInode;
1595 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001596 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001597 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001598
1599#ifndef NDEBUG
1600 /* When reducing a lock such that other processes can start
1601 ** reading the database file again, make sure that the
1602 ** transaction counter was updated if any part of the database
1603 ** file changed. If the transaction counter is not updated,
1604 ** other connections to the same file might not realize that
1605 ** the file has changed and hence might not know to flush their
1606 ** cache. The use of a stale cache can lead to database corruption.
1607 */
drh8f941bc2009-01-14 23:03:40 +00001608 pFile->inNormalWrite = 0;
1609#endif
1610
drh7ed97b92010-01-20 13:07:21 +00001611 /* downgrading to a shared lock on NFS involves clearing the write lock
1612 ** before establishing the readlock - to avoid a race condition we downgrade
1613 ** the lock in 2 blocks, so that part of the range will be covered by a
1614 ** write lock until the rest is covered by a read lock:
1615 ** 1: [WWWWW]
1616 ** 2: [....W]
1617 ** 3: [RRRRW]
1618 ** 4: [RRRR.]
1619 */
drh308c2a52010-05-14 11:30:18 +00001620 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001621
1622#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001623 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001624 assert( handleNFSUnlock==0 );
1625#endif
1626#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001627 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001628 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001629 off_t divSize = SHARED_SIZE - 1;
1630
1631 lock.l_type = F_UNLCK;
1632 lock.l_whence = SEEK_SET;
1633 lock.l_start = SHARED_FIRST;
1634 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001635 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001636 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001637 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001638 if( IS_LOCK_ERROR(rc) ){
1639 pFile->lastErrno = tErrno;
1640 }
1641 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001642 }
drh7ed97b92010-01-20 13:07:21 +00001643 lock.l_type = F_RDLCK;
1644 lock.l_whence = SEEK_SET;
1645 lock.l_start = SHARED_FIRST;
1646 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001647 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001648 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001649 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1650 if( IS_LOCK_ERROR(rc) ){
1651 pFile->lastErrno = tErrno;
1652 }
1653 goto end_unlock;
1654 }
1655 lock.l_type = F_UNLCK;
1656 lock.l_whence = SEEK_SET;
1657 lock.l_start = SHARED_FIRST+divSize;
1658 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001659 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001660 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001661 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001662 if( IS_LOCK_ERROR(rc) ){
1663 pFile->lastErrno = tErrno;
1664 }
1665 goto end_unlock;
1666 }
drh30f776f2011-02-25 03:25:07 +00001667 }else
1668#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1669 {
drh7ed97b92010-01-20 13:07:21 +00001670 lock.l_type = F_RDLCK;
1671 lock.l_whence = SEEK_SET;
1672 lock.l_start = SHARED_FIRST;
1673 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001674 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001675 /* In theory, the call to unixFileLock() cannot fail because another
1676 ** process is holding an incompatible lock. If it does, this
1677 ** indicates that the other process is not following the locking
1678 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1679 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1680 ** an assert to fail). */
1681 rc = SQLITE_IOERR_RDLOCK;
1682 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001683 goto end_unlock;
1684 }
drh9c105bb2004-10-02 20:38:28 +00001685 }
1686 }
drhbbd42a62004-05-22 17:41:58 +00001687 lock.l_type = F_UNLCK;
1688 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001689 lock.l_start = PENDING_BYTE;
1690 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001691 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001692 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001693 }else{
danea83bc62011-04-01 11:56:32 +00001694 rc = SQLITE_IOERR_UNLOCK;
1695 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001696 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001697 }
drhbbd42a62004-05-22 17:41:58 +00001698 }
drh308c2a52010-05-14 11:30:18 +00001699 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001700 /* Decrement the shared lock counter. Release the lock using an
1701 ** OS call only when all threads in this same process have released
1702 ** the lock.
1703 */
drh8af6c222010-05-14 12:43:01 +00001704 pInode->nShared--;
1705 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001706 lock.l_type = F_UNLCK;
1707 lock.l_whence = SEEK_SET;
1708 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001709 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001710 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001711 }else{
danea83bc62011-04-01 11:56:32 +00001712 rc = SQLITE_IOERR_UNLOCK;
1713 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001714 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001715 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001716 }
drha6abd042004-06-09 17:37:22 +00001717 }
1718
drhbbd42a62004-05-22 17:41:58 +00001719 /* Decrement the count of locks against this same file. When the
1720 ** count reaches zero, close any other file descriptors whose close
1721 ** was deferred because of outstanding locks.
1722 */
drh8af6c222010-05-14 12:43:01 +00001723 pInode->nLock--;
1724 assert( pInode->nLock>=0 );
1725 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001726 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001727 }
1728 }
aswift5b1a2562008-08-22 00:22:35 +00001729
1730end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001731 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001732 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001733 return rc;
drhbbd42a62004-05-22 17:41:58 +00001734}
1735
1736/*
drh308c2a52010-05-14 11:30:18 +00001737** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001738** must be either NO_LOCK or SHARED_LOCK.
1739**
1740** If the locking level of the file descriptor is already at or below
1741** the requested locking level, this routine is a no-op.
1742*/
drh308c2a52010-05-14 11:30:18 +00001743static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001744 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001745}
1746
1747/*
danielk1977e339d652008-06-28 11:23:00 +00001748** This function performs the parts of the "close file" operation
1749** common to all locking schemes. It closes the directory and file
1750** handles, if they are valid, and sets all fields of the unixFile
1751** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001752**
1753** It is *not* necessary to hold the mutex when this routine is called,
1754** even on VxWorks. A mutex will be acquired on VxWorks by the
1755** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001756*/
1757static int closeUnixFile(sqlite3_file *id){
1758 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001759 if( pFile->h>=0 ){
1760 robust_close(pFile, pFile->h, __LINE__);
1761 pFile->h = -1;
1762 }
1763#if OS_VXWORKS
1764 if( pFile->pId ){
1765 if( pFile->isDelete ){
drh036ac7f2011-08-08 23:18:05 +00001766 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001767 }
1768 vxworksReleaseFileId(pFile->pId);
1769 pFile->pId = 0;
1770 }
1771#endif
1772 OSTRACE(("CLOSE %-3d\n", pFile->h));
1773 OpenCounter(-1);
1774 sqlite3_free(pFile->pUnused);
1775 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001776 return SQLITE_OK;
1777}
1778
1779/*
danielk1977e3026632004-06-22 11:29:02 +00001780** Close a file.
1781*/
danielk197762079062007-08-15 17:08:46 +00001782static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001783 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001784 unixFile *pFile = (unixFile *)id;
1785 unixUnlock(id, NO_LOCK);
1786 unixEnterMutex();
1787
1788 /* unixFile.pInode is always valid here. Otherwise, a different close
1789 ** routine (e.g. nolockClose()) would be called instead.
1790 */
1791 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1792 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1793 /* If there are outstanding locks, do not actually close the file just
1794 ** yet because that would clear those locks. Instead, add the file
1795 ** descriptor to pInode->pUnused list. It will be automatically closed
1796 ** when the last lock is cleared.
1797 */
1798 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001799 }
dan661d71a2011-03-30 19:08:03 +00001800 releaseInodeInfo(pFile);
1801 rc = closeUnixFile(id);
1802 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001803 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001804}
1805
drh734c9862008-11-28 15:37:20 +00001806/************** End of the posix advisory lock implementation *****************
1807******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001808
drh734c9862008-11-28 15:37:20 +00001809/******************************************************************************
1810****************************** No-op Locking **********************************
1811**
1812** Of the various locking implementations available, this is by far the
1813** simplest: locking is ignored. No attempt is made to lock the database
1814** file for reading or writing.
1815**
1816** This locking mode is appropriate for use on read-only databases
1817** (ex: databases that are burned into CD-ROM, for example.) It can
1818** also be used if the application employs some external mechanism to
1819** prevent simultaneous access of the same database by two or more
1820** database connections. But there is a serious risk of database
1821** corruption if this locking mode is used in situations where multiple
1822** database connections are accessing the same database file at the same
1823** time and one or more of those connections are writing.
1824*/
drhbfe66312006-10-03 17:40:40 +00001825
drh734c9862008-11-28 15:37:20 +00001826static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1827 UNUSED_PARAMETER(NotUsed);
1828 *pResOut = 0;
1829 return SQLITE_OK;
1830}
drh734c9862008-11-28 15:37:20 +00001831static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1832 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1833 return SQLITE_OK;
1834}
drh734c9862008-11-28 15:37:20 +00001835static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1836 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1837 return SQLITE_OK;
1838}
1839
1840/*
drh9b35ea62008-11-29 02:20:26 +00001841** Close the file.
drh734c9862008-11-28 15:37:20 +00001842*/
1843static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001844 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001845}
1846
1847/******************* End of the no-op lock implementation *********************
1848******************************************************************************/
1849
1850/******************************************************************************
1851************************* Begin dot-file Locking ******************************
1852**
drh0c2694b2009-09-03 16:23:44 +00001853** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001854** files (really a directory) to control access to the database. This works
1855** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001856**
1857** (1) There is zero concurrency. A single reader blocks all other
1858** connections from reading or writing the database.
1859**
1860** (2) An application crash or power loss can leave stale lock files
1861** sitting around that need to be cleared manually.
1862**
1863** Nevertheless, a dotlock is an appropriate locking mode for use if no
1864** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001865**
drh9ef6bc42011-11-04 02:24:02 +00001866** Dotfile locking works by creating a subdirectory in the same directory as
1867** the database and with the same name but with a ".lock" extension added.
1868** The existance of a lock directory implies an EXCLUSIVE lock. All other
1869** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001870*/
1871
1872/*
1873** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001874** lock directory.
drh734c9862008-11-28 15:37:20 +00001875*/
1876#define DOTLOCK_SUFFIX ".lock"
1877
drh7708e972008-11-29 00:56:52 +00001878/*
1879** This routine checks if there is a RESERVED lock held on the specified
1880** file by this or any other process. If such a lock is held, set *pResOut
1881** to a non-zero value otherwise *pResOut is set to zero. The return value
1882** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1883**
1884** In dotfile locking, either a lock exists or it does not. So in this
1885** variation of CheckReservedLock(), *pResOut is set to true if any lock
1886** is held on the file and false if the file is unlocked.
1887*/
drh734c9862008-11-28 15:37:20 +00001888static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1889 int rc = SQLITE_OK;
1890 int reserved = 0;
1891 unixFile *pFile = (unixFile*)id;
1892
1893 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1894
1895 assert( pFile );
1896
1897 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001898 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001899 /* Either this connection or some other connection in the same process
1900 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001901 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001902 }else{
1903 /* The lock is held if and only if the lockfile exists */
1904 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001905 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001906 }
drh308c2a52010-05-14 11:30:18 +00001907 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001908 *pResOut = reserved;
1909 return rc;
1910}
1911
drh7708e972008-11-29 00:56:52 +00001912/*
drh308c2a52010-05-14 11:30:18 +00001913** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001914** of the following:
1915**
1916** (1) SHARED_LOCK
1917** (2) RESERVED_LOCK
1918** (3) PENDING_LOCK
1919** (4) EXCLUSIVE_LOCK
1920**
1921** Sometimes when requesting one lock state, additional lock states
1922** are inserted in between. The locking might fail on one of the later
1923** transitions leaving the lock state different from what it started but
1924** still short of its goal. The following chart shows the allowed
1925** transitions and the inserted intermediate states:
1926**
1927** UNLOCKED -> SHARED
1928** SHARED -> RESERVED
1929** SHARED -> (PENDING) -> EXCLUSIVE
1930** RESERVED -> (PENDING) -> EXCLUSIVE
1931** PENDING -> EXCLUSIVE
1932**
1933** This routine will only increase a lock. Use the sqlite3OsUnlock()
1934** routine to lower a locking level.
1935**
1936** With dotfile locking, we really only support state (4): EXCLUSIVE.
1937** But we track the other locking levels internally.
1938*/
drh308c2a52010-05-14 11:30:18 +00001939static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001940 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001941 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001942 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001943
drh7708e972008-11-29 00:56:52 +00001944
1945 /* If we have any lock, then the lock file already exists. All we have
1946 ** to do is adjust our internal record of the lock level.
1947 */
drh308c2a52010-05-14 11:30:18 +00001948 if( pFile->eFileLock > NO_LOCK ){
1949 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001950 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001951#ifdef HAVE_UTIME
1952 utime(zLockFile, NULL);
1953#else
drh734c9862008-11-28 15:37:20 +00001954 utimes(zLockFile, NULL);
1955#endif
drh7708e972008-11-29 00:56:52 +00001956 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001957 }
1958
1959 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00001960 rc = osMkdir(zLockFile, 0777);
1961 if( rc<0 ){
1962 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00001963 int tErrno = errno;
1964 if( EEXIST == tErrno ){
1965 rc = SQLITE_BUSY;
1966 } else {
1967 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1968 if( IS_LOCK_ERROR(rc) ){
1969 pFile->lastErrno = tErrno;
1970 }
1971 }
drh7708e972008-11-29 00:56:52 +00001972 return rc;
drh734c9862008-11-28 15:37:20 +00001973 }
drh734c9862008-11-28 15:37:20 +00001974
1975 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001976 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001977 return rc;
1978}
1979
drh7708e972008-11-29 00:56:52 +00001980/*
drh308c2a52010-05-14 11:30:18 +00001981** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001982** must be either NO_LOCK or SHARED_LOCK.
1983**
1984** If the locking level of the file descriptor is already at or below
1985** the requested locking level, this routine is a no-op.
1986**
1987** When the locking level reaches NO_LOCK, delete the lock file.
1988*/
drh308c2a52010-05-14 11:30:18 +00001989static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001990 unixFile *pFile = (unixFile*)id;
1991 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00001992 int rc;
drh734c9862008-11-28 15:37:20 +00001993
1994 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001995 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1996 pFile->eFileLock, getpid()));
1997 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00001998
1999 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002000 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002001 return SQLITE_OK;
2002 }
drh7708e972008-11-29 00:56:52 +00002003
2004 /* To downgrade to shared, simply update our internal notion of the
2005 ** lock state. No need to mess with the file on disk.
2006 */
drh308c2a52010-05-14 11:30:18 +00002007 if( eFileLock==SHARED_LOCK ){
2008 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002009 return SQLITE_OK;
2010 }
2011
drh7708e972008-11-29 00:56:52 +00002012 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002013 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002014 rc = osRmdir(zLockFile);
2015 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2016 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002017 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002018 rc = 0;
drh734c9862008-11-28 15:37:20 +00002019 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002020 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002021 }
2022 if( IS_LOCK_ERROR(rc) ){
2023 pFile->lastErrno = tErrno;
2024 }
2025 return rc;
2026 }
drh308c2a52010-05-14 11:30:18 +00002027 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002028 return SQLITE_OK;
2029}
2030
2031/*
drh9b35ea62008-11-29 02:20:26 +00002032** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002033*/
2034static int dotlockClose(sqlite3_file *id) {
2035 int rc;
2036 if( id ){
2037 unixFile *pFile = (unixFile*)id;
2038 dotlockUnlock(id, NO_LOCK);
2039 sqlite3_free(pFile->lockingContext);
2040 }
drh734c9862008-11-28 15:37:20 +00002041 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002042 return rc;
2043}
2044/****************** End of the dot-file lock implementation *******************
2045******************************************************************************/
2046
2047/******************************************************************************
2048************************** Begin flock Locking ********************************
2049**
2050** Use the flock() system call to do file locking.
2051**
drh6b9d6dd2008-12-03 19:34:47 +00002052** flock() locking is like dot-file locking in that the various
2053** fine-grain locking levels supported by SQLite are collapsed into
2054** a single exclusive lock. In other words, SHARED, RESERVED, and
2055** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2056** still works when you do this, but concurrency is reduced since
2057** only a single process can be reading the database at a time.
2058**
drh734c9862008-11-28 15:37:20 +00002059** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2060** compiling for VXWORKS.
2061*/
2062#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002063
drh6b9d6dd2008-12-03 19:34:47 +00002064/*
drhff812312011-02-23 13:33:46 +00002065** Retry flock() calls that fail with EINTR
2066*/
2067#ifdef EINTR
2068static int robust_flock(int fd, int op){
2069 int rc;
2070 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2071 return rc;
2072}
2073#else
drh5c819272011-02-23 14:00:12 +00002074# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002075#endif
2076
2077
2078/*
drh6b9d6dd2008-12-03 19:34:47 +00002079** This routine checks if there is a RESERVED lock held on the specified
2080** file by this or any other process. If such a lock is held, set *pResOut
2081** to a non-zero value otherwise *pResOut is set to zero. The return value
2082** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2083*/
drh734c9862008-11-28 15:37:20 +00002084static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2085 int rc = SQLITE_OK;
2086 int reserved = 0;
2087 unixFile *pFile = (unixFile*)id;
2088
2089 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2090
2091 assert( pFile );
2092
2093 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002094 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002095 reserved = 1;
2096 }
2097
2098 /* Otherwise see if some other process holds it. */
2099 if( !reserved ){
2100 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002101 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002102 if( !lrc ){
2103 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002104 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002105 if ( lrc ) {
2106 int tErrno = errno;
2107 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002108 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002109 if( IS_LOCK_ERROR(lrc) ){
2110 pFile->lastErrno = tErrno;
2111 rc = lrc;
2112 }
2113 }
2114 } else {
2115 int tErrno = errno;
2116 reserved = 1;
2117 /* someone else might have it reserved */
2118 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2119 if( IS_LOCK_ERROR(lrc) ){
2120 pFile->lastErrno = tErrno;
2121 rc = lrc;
2122 }
2123 }
2124 }
drh308c2a52010-05-14 11:30:18 +00002125 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002126
2127#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2128 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2129 rc = SQLITE_OK;
2130 reserved=1;
2131 }
2132#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2133 *pResOut = reserved;
2134 return rc;
2135}
2136
drh6b9d6dd2008-12-03 19:34:47 +00002137/*
drh308c2a52010-05-14 11:30:18 +00002138** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002139** of the following:
2140**
2141** (1) SHARED_LOCK
2142** (2) RESERVED_LOCK
2143** (3) PENDING_LOCK
2144** (4) EXCLUSIVE_LOCK
2145**
2146** Sometimes when requesting one lock state, additional lock states
2147** are inserted in between. The locking might fail on one of the later
2148** transitions leaving the lock state different from what it started but
2149** still short of its goal. The following chart shows the allowed
2150** transitions and the inserted intermediate states:
2151**
2152** UNLOCKED -> SHARED
2153** SHARED -> RESERVED
2154** SHARED -> (PENDING) -> EXCLUSIVE
2155** RESERVED -> (PENDING) -> EXCLUSIVE
2156** PENDING -> EXCLUSIVE
2157**
2158** flock() only really support EXCLUSIVE locks. We track intermediate
2159** lock states in the sqlite3_file structure, but all locks SHARED or
2160** above are really EXCLUSIVE locks and exclude all other processes from
2161** access the file.
2162**
2163** This routine will only increase a lock. Use the sqlite3OsUnlock()
2164** routine to lower a locking level.
2165*/
drh308c2a52010-05-14 11:30:18 +00002166static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002167 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002168 unixFile *pFile = (unixFile*)id;
2169
2170 assert( pFile );
2171
2172 /* if we already have a lock, it is exclusive.
2173 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002174 if (pFile->eFileLock > NO_LOCK) {
2175 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002176 return SQLITE_OK;
2177 }
2178
2179 /* grab an exclusive lock */
2180
drhff812312011-02-23 13:33:46 +00002181 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002182 int tErrno = errno;
2183 /* didn't get, must be busy */
2184 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2185 if( IS_LOCK_ERROR(rc) ){
2186 pFile->lastErrno = tErrno;
2187 }
2188 } else {
2189 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002190 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002191 }
drh308c2a52010-05-14 11:30:18 +00002192 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2193 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002194#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2195 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2196 rc = SQLITE_BUSY;
2197 }
2198#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2199 return rc;
2200}
2201
drh6b9d6dd2008-12-03 19:34:47 +00002202
2203/*
drh308c2a52010-05-14 11:30:18 +00002204** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002205** must be either NO_LOCK or SHARED_LOCK.
2206**
2207** If the locking level of the file descriptor is already at or below
2208** the requested locking level, this routine is a no-op.
2209*/
drh308c2a52010-05-14 11:30:18 +00002210static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002211 unixFile *pFile = (unixFile*)id;
2212
2213 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002214 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2215 pFile->eFileLock, getpid()));
2216 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002217
2218 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002219 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002220 return SQLITE_OK;
2221 }
2222
2223 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002224 if (eFileLock==SHARED_LOCK) {
2225 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002226 return SQLITE_OK;
2227 }
2228
2229 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002230 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002231#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002232 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002233#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002234 return SQLITE_IOERR_UNLOCK;
2235 }else{
drh308c2a52010-05-14 11:30:18 +00002236 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002237 return SQLITE_OK;
2238 }
2239}
2240
2241/*
2242** Close a file.
2243*/
2244static int flockClose(sqlite3_file *id) {
2245 if( id ){
2246 flockUnlock(id, NO_LOCK);
2247 }
2248 return closeUnixFile(id);
2249}
2250
2251#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2252
2253/******************* End of the flock lock implementation *********************
2254******************************************************************************/
2255
2256/******************************************************************************
2257************************ Begin Named Semaphore Locking ************************
2258**
2259** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002260**
2261** Semaphore locking is like dot-lock and flock in that it really only
2262** supports EXCLUSIVE locking. Only a single process can read or write
2263** the database file at a time. This reduces potential concurrency, but
2264** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002265*/
2266#if OS_VXWORKS
2267
drh6b9d6dd2008-12-03 19:34:47 +00002268/*
2269** This routine checks if there is a RESERVED lock held on the specified
2270** file by this or any other process. If such a lock is held, set *pResOut
2271** to a non-zero value otherwise *pResOut is set to zero. The return value
2272** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2273*/
drh734c9862008-11-28 15:37:20 +00002274static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2275 int rc = SQLITE_OK;
2276 int reserved = 0;
2277 unixFile *pFile = (unixFile*)id;
2278
2279 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2280
2281 assert( pFile );
2282
2283 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002284 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002285 reserved = 1;
2286 }
2287
2288 /* Otherwise see if some other process holds it. */
2289 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002290 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002291 struct stat statBuf;
2292
2293 if( sem_trywait(pSem)==-1 ){
2294 int tErrno = errno;
2295 if( EAGAIN != tErrno ){
2296 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2297 pFile->lastErrno = tErrno;
2298 } else {
2299 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002300 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002301 }
2302 }else{
2303 /* we could have it if we want it */
2304 sem_post(pSem);
2305 }
2306 }
drh308c2a52010-05-14 11:30:18 +00002307 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002308
2309 *pResOut = reserved;
2310 return rc;
2311}
2312
drh6b9d6dd2008-12-03 19:34:47 +00002313/*
drh308c2a52010-05-14 11:30:18 +00002314** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002315** of the following:
2316**
2317** (1) SHARED_LOCK
2318** (2) RESERVED_LOCK
2319** (3) PENDING_LOCK
2320** (4) EXCLUSIVE_LOCK
2321**
2322** Sometimes when requesting one lock state, additional lock states
2323** are inserted in between. The locking might fail on one of the later
2324** transitions leaving the lock state different from what it started but
2325** still short of its goal. The following chart shows the allowed
2326** transitions and the inserted intermediate states:
2327**
2328** UNLOCKED -> SHARED
2329** SHARED -> RESERVED
2330** SHARED -> (PENDING) -> EXCLUSIVE
2331** RESERVED -> (PENDING) -> EXCLUSIVE
2332** PENDING -> EXCLUSIVE
2333**
2334** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2335** lock states in the sqlite3_file structure, but all locks SHARED or
2336** above are really EXCLUSIVE locks and exclude all other processes from
2337** access the file.
2338**
2339** This routine will only increase a lock. Use the sqlite3OsUnlock()
2340** routine to lower a locking level.
2341*/
drh308c2a52010-05-14 11:30:18 +00002342static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002343 unixFile *pFile = (unixFile*)id;
2344 int fd;
drh8af6c222010-05-14 12:43:01 +00002345 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002346 int rc = SQLITE_OK;
2347
2348 /* if we already have a lock, it is exclusive.
2349 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002350 if (pFile->eFileLock > NO_LOCK) {
2351 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002352 rc = SQLITE_OK;
2353 goto sem_end_lock;
2354 }
2355
2356 /* lock semaphore now but bail out when already locked. */
2357 if( sem_trywait(pSem)==-1 ){
2358 rc = SQLITE_BUSY;
2359 goto sem_end_lock;
2360 }
2361
2362 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002363 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002364
2365 sem_end_lock:
2366 return rc;
2367}
2368
drh6b9d6dd2008-12-03 19:34:47 +00002369/*
drh308c2a52010-05-14 11:30:18 +00002370** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002371** must be either NO_LOCK or SHARED_LOCK.
2372**
2373** If the locking level of the file descriptor is already at or below
2374** the requested locking level, this routine is a no-op.
2375*/
drh308c2a52010-05-14 11:30:18 +00002376static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002377 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002378 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002379
2380 assert( pFile );
2381 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002382 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2383 pFile->eFileLock, getpid()));
2384 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002385
2386 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002387 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002388 return SQLITE_OK;
2389 }
2390
2391 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002392 if (eFileLock==SHARED_LOCK) {
2393 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002394 return SQLITE_OK;
2395 }
2396
2397 /* no, really unlock. */
2398 if ( sem_post(pSem)==-1 ) {
2399 int rc, tErrno = errno;
2400 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2401 if( IS_LOCK_ERROR(rc) ){
2402 pFile->lastErrno = tErrno;
2403 }
2404 return rc;
2405 }
drh308c2a52010-05-14 11:30:18 +00002406 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002407 return SQLITE_OK;
2408}
2409
2410/*
2411 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002412 */
drh734c9862008-11-28 15:37:20 +00002413static int semClose(sqlite3_file *id) {
2414 if( id ){
2415 unixFile *pFile = (unixFile*)id;
2416 semUnlock(id, NO_LOCK);
2417 assert( pFile );
2418 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002419 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002420 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002421 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002422 }
2423 return SQLITE_OK;
2424}
2425
2426#endif /* OS_VXWORKS */
2427/*
2428** Named semaphore locking is only available on VxWorks.
2429**
2430*************** End of the named semaphore lock implementation ****************
2431******************************************************************************/
2432
2433
2434/******************************************************************************
2435*************************** Begin AFP Locking *********************************
2436**
2437** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2438** on Apple Macintosh computers - both OS9 and OSX.
2439**
2440** Third-party implementations of AFP are available. But this code here
2441** only works on OSX.
2442*/
2443
drhd2cb50b2009-01-09 21:41:17 +00002444#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002445/*
2446** The afpLockingContext structure contains all afp lock specific state
2447*/
drhbfe66312006-10-03 17:40:40 +00002448typedef struct afpLockingContext afpLockingContext;
2449struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002450 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002451 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002452};
2453
2454struct ByteRangeLockPB2
2455{
2456 unsigned long long offset; /* offset to first byte to lock */
2457 unsigned long long length; /* nbr of bytes to lock */
2458 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2459 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2460 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2461 int fd; /* file desc to assoc this lock with */
2462};
2463
drhfd131da2007-08-07 17:13:03 +00002464#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002465
drh6b9d6dd2008-12-03 19:34:47 +00002466/*
2467** This is a utility for setting or clearing a bit-range lock on an
2468** AFP filesystem.
2469**
2470** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2471*/
2472static int afpSetLock(
2473 const char *path, /* Name of the file to be locked or unlocked */
2474 unixFile *pFile, /* Open file descriptor on path */
2475 unsigned long long offset, /* First byte to be locked */
2476 unsigned long long length, /* Number of bytes to lock */
2477 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002478){
drh6b9d6dd2008-12-03 19:34:47 +00002479 struct ByteRangeLockPB2 pb;
2480 int err;
drhbfe66312006-10-03 17:40:40 +00002481
2482 pb.unLockFlag = setLockFlag ? 0 : 1;
2483 pb.startEndFlag = 0;
2484 pb.offset = offset;
2485 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002486 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002487
drh308c2a52010-05-14 11:30:18 +00002488 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002489 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002490 offset, length));
drhbfe66312006-10-03 17:40:40 +00002491 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2492 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002493 int rc;
2494 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002495 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2496 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002497#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2498 rc = SQLITE_BUSY;
2499#else
drh734c9862008-11-28 15:37:20 +00002500 rc = sqliteErrorFromPosixError(tErrno,
2501 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002502#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002503 if( IS_LOCK_ERROR(rc) ){
2504 pFile->lastErrno = tErrno;
2505 }
2506 return rc;
drhbfe66312006-10-03 17:40:40 +00002507 } else {
aswift5b1a2562008-08-22 00:22:35 +00002508 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002509 }
2510}
2511
drh6b9d6dd2008-12-03 19:34:47 +00002512/*
2513** This routine checks if there is a RESERVED lock held on the specified
2514** file by this or any other process. If such a lock is held, set *pResOut
2515** to a non-zero value otherwise *pResOut is set to zero. The return value
2516** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2517*/
danielk1977e339d652008-06-28 11:23:00 +00002518static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002519 int rc = SQLITE_OK;
2520 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002521 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002522 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002523
aswift5b1a2562008-08-22 00:22:35 +00002524 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2525
2526 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002527 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002528 if( context->reserved ){
2529 *pResOut = 1;
2530 return SQLITE_OK;
2531 }
drh8af6c222010-05-14 12:43:01 +00002532 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002533
2534 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002535 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002536 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002537 }
2538
2539 /* Otherwise see if some other process holds it.
2540 */
aswift5b1a2562008-08-22 00:22:35 +00002541 if( !reserved ){
2542 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002543 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002544 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002545 /* if we succeeded in taking the reserved lock, unlock it to restore
2546 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002547 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002548 } else {
2549 /* if we failed to get the lock then someone else must have it */
2550 reserved = 1;
2551 }
2552 if( IS_LOCK_ERROR(lrc) ){
2553 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002554 }
2555 }
drhbfe66312006-10-03 17:40:40 +00002556
drh7ed97b92010-01-20 13:07:21 +00002557 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002558 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002559
2560 *pResOut = reserved;
2561 return rc;
drhbfe66312006-10-03 17:40:40 +00002562}
2563
drh6b9d6dd2008-12-03 19:34:47 +00002564/*
drh308c2a52010-05-14 11:30:18 +00002565** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002566** of the following:
2567**
2568** (1) SHARED_LOCK
2569** (2) RESERVED_LOCK
2570** (3) PENDING_LOCK
2571** (4) EXCLUSIVE_LOCK
2572**
2573** Sometimes when requesting one lock state, additional lock states
2574** are inserted in between. The locking might fail on one of the later
2575** transitions leaving the lock state different from what it started but
2576** still short of its goal. The following chart shows the allowed
2577** transitions and the inserted intermediate states:
2578**
2579** UNLOCKED -> SHARED
2580** SHARED -> RESERVED
2581** SHARED -> (PENDING) -> EXCLUSIVE
2582** RESERVED -> (PENDING) -> EXCLUSIVE
2583** PENDING -> EXCLUSIVE
2584**
2585** This routine will only increase a lock. Use the sqlite3OsUnlock()
2586** routine to lower a locking level.
2587*/
drh308c2a52010-05-14 11:30:18 +00002588static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002589 int rc = SQLITE_OK;
2590 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002591 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002592 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002593
2594 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002595 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2596 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002597 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002598
drhbfe66312006-10-03 17:40:40 +00002599 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002600 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002601 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002602 */
drh308c2a52010-05-14 11:30:18 +00002603 if( pFile->eFileLock>=eFileLock ){
2604 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2605 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002606 return SQLITE_OK;
2607 }
2608
2609 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002610 ** (1) We never move from unlocked to anything higher than shared lock.
2611 ** (2) SQLite never explicitly requests a pendig lock.
2612 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002613 */
drh308c2a52010-05-14 11:30:18 +00002614 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2615 assert( eFileLock!=PENDING_LOCK );
2616 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002617
drh8af6c222010-05-14 12:43:01 +00002618 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002619 */
drh6c7d5c52008-11-21 20:32:33 +00002620 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002621 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002622
2623 /* If some thread using this PID has a lock via a different unixFile*
2624 ** handle that precludes the requested lock, return BUSY.
2625 */
drh8af6c222010-05-14 12:43:01 +00002626 if( (pFile->eFileLock!=pInode->eFileLock &&
2627 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002628 ){
2629 rc = SQLITE_BUSY;
2630 goto afp_end_lock;
2631 }
2632
2633 /* If a SHARED lock is requested, and some thread using this PID already
2634 ** has a SHARED or RESERVED lock, then increment reference counts and
2635 ** return SQLITE_OK.
2636 */
drh308c2a52010-05-14 11:30:18 +00002637 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002638 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002639 assert( eFileLock==SHARED_LOCK );
2640 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002641 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002642 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002643 pInode->nShared++;
2644 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002645 goto afp_end_lock;
2646 }
drhbfe66312006-10-03 17:40:40 +00002647
2648 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002649 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2650 ** be released.
2651 */
drh308c2a52010-05-14 11:30:18 +00002652 if( eFileLock==SHARED_LOCK
2653 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002654 ){
2655 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002656 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002657 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002658 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002659 goto afp_end_lock;
2660 }
2661 }
2662
2663 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002664 ** operating system calls for the specified lock.
2665 */
drh308c2a52010-05-14 11:30:18 +00002666 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002667 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002668 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002669
drh8af6c222010-05-14 12:43:01 +00002670 assert( pInode->nShared==0 );
2671 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002672
2673 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002674 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002675 /* note that the quality of the randomness doesn't matter that much */
2676 lk = random();
drh8af6c222010-05-14 12:43:01 +00002677 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002678 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002679 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002680 if( IS_LOCK_ERROR(lrc1) ){
2681 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002682 }
aswift5b1a2562008-08-22 00:22:35 +00002683 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002684 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002685
aswift5b1a2562008-08-22 00:22:35 +00002686 if( IS_LOCK_ERROR(lrc1) ) {
2687 pFile->lastErrno = lrc1Errno;
2688 rc = lrc1;
2689 goto afp_end_lock;
2690 } else if( IS_LOCK_ERROR(lrc2) ){
2691 rc = lrc2;
2692 goto afp_end_lock;
2693 } else if( lrc1 != SQLITE_OK ) {
2694 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002695 } else {
drh308c2a52010-05-14 11:30:18 +00002696 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002697 pInode->nLock++;
2698 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002699 }
drh8af6c222010-05-14 12:43:01 +00002700 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002701 /* We are trying for an exclusive lock but another thread in this
2702 ** same process is still holding a shared lock. */
2703 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002704 }else{
2705 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2706 ** assumed that there is a SHARED or greater lock on the file
2707 ** already.
2708 */
2709 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002710 assert( 0!=pFile->eFileLock );
2711 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002712 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002713 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002714 if( !failed ){
2715 context->reserved = 1;
2716 }
drhbfe66312006-10-03 17:40:40 +00002717 }
drh308c2a52010-05-14 11:30:18 +00002718 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002719 /* Acquire an EXCLUSIVE lock */
2720
2721 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002722 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002723 */
drh6b9d6dd2008-12-03 19:34:47 +00002724 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002725 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002726 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002727 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002728 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002729 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002730 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002731 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002732 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2733 ** a critical I/O error
2734 */
2735 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2736 SQLITE_IOERR_LOCK;
2737 goto afp_end_lock;
2738 }
2739 }else{
aswift5b1a2562008-08-22 00:22:35 +00002740 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002741 }
2742 }
aswift5b1a2562008-08-22 00:22:35 +00002743 if( failed ){
2744 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002745 }
2746 }
2747
2748 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002749 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002750 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002751 }else if( eFileLock==EXCLUSIVE_LOCK ){
2752 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002753 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002754 }
2755
2756afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002757 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002758 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2759 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002760 return rc;
2761}
2762
2763/*
drh308c2a52010-05-14 11:30:18 +00002764** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002765** must be either NO_LOCK or SHARED_LOCK.
2766**
2767** If the locking level of the file descriptor is already at or below
2768** the requested locking level, this routine is a no-op.
2769*/
drh308c2a52010-05-14 11:30:18 +00002770static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002771 int rc = SQLITE_OK;
2772 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002773 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002774 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2775 int skipShared = 0;
2776#ifdef SQLITE_TEST
2777 int h = pFile->h;
2778#endif
drhbfe66312006-10-03 17:40:40 +00002779
2780 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002781 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002782 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002783 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002784
drh308c2a52010-05-14 11:30:18 +00002785 assert( eFileLock<=SHARED_LOCK );
2786 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002787 return SQLITE_OK;
2788 }
drh6c7d5c52008-11-21 20:32:33 +00002789 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002790 pInode = pFile->pInode;
2791 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002792 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002793 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002794 SimulateIOErrorBenign(1);
2795 SimulateIOError( h=(-1) )
2796 SimulateIOErrorBenign(0);
2797
2798#ifndef NDEBUG
2799 /* When reducing a lock such that other processes can start
2800 ** reading the database file again, make sure that the
2801 ** transaction counter was updated if any part of the database
2802 ** file changed. If the transaction counter is not updated,
2803 ** other connections to the same file might not realize that
2804 ** the file has changed and hence might not know to flush their
2805 ** cache. The use of a stale cache can lead to database corruption.
2806 */
2807 assert( pFile->inNormalWrite==0
2808 || pFile->dbUpdate==0
2809 || pFile->transCntrChng==1 );
2810 pFile->inNormalWrite = 0;
2811#endif
aswiftaebf4132008-11-21 00:10:35 +00002812
drh308c2a52010-05-14 11:30:18 +00002813 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002814 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002815 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002816 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002817 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002818 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2819 } else {
2820 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002821 }
2822 }
drh308c2a52010-05-14 11:30:18 +00002823 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002824 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002825 }
drh308c2a52010-05-14 11:30:18 +00002826 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002827 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2828 if( !rc ){
2829 context->reserved = 0;
2830 }
aswiftaebf4132008-11-21 00:10:35 +00002831 }
drh8af6c222010-05-14 12:43:01 +00002832 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2833 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002834 }
aswiftaebf4132008-11-21 00:10:35 +00002835 }
drh308c2a52010-05-14 11:30:18 +00002836 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002837
drh7ed97b92010-01-20 13:07:21 +00002838 /* Decrement the shared lock counter. Release the lock using an
2839 ** OS call only when all threads in this same process have released
2840 ** the lock.
2841 */
drh8af6c222010-05-14 12:43:01 +00002842 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2843 pInode->nShared--;
2844 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002845 SimulateIOErrorBenign(1);
2846 SimulateIOError( h=(-1) )
2847 SimulateIOErrorBenign(0);
2848 if( !skipShared ){
2849 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2850 }
2851 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002852 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002853 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002854 }
2855 }
2856 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002857 pInode->nLock--;
2858 assert( pInode->nLock>=0 );
2859 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002860 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002861 }
2862 }
drhbfe66312006-10-03 17:40:40 +00002863 }
drh7ed97b92010-01-20 13:07:21 +00002864
drh6c7d5c52008-11-21 20:32:33 +00002865 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002866 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002867 return rc;
2868}
2869
2870/*
drh339eb0b2008-03-07 15:34:11 +00002871** Close a file & cleanup AFP specific locking context
2872*/
danielk1977e339d652008-06-28 11:23:00 +00002873static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002874 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002875 if( id ){
2876 unixFile *pFile = (unixFile*)id;
2877 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002878 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002879 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002880 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002881 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002882 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002883 ** the last lock is cleared.
2884 */
dan08da86a2009-08-21 17:18:03 +00002885 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002886 }
danb0ac3e32010-06-16 10:55:42 +00002887 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002888 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002889 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002890 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002891 }
drh7ed97b92010-01-20 13:07:21 +00002892 return rc;
drhbfe66312006-10-03 17:40:40 +00002893}
2894
drhd2cb50b2009-01-09 21:41:17 +00002895#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002896/*
2897** The code above is the AFP lock implementation. The code is specific
2898** to MacOSX and does not work on other unix platforms. No alternative
2899** is available. If you don't compile for a mac, then the "unix-afp"
2900** VFS is not available.
2901**
2902********************* End of the AFP lock implementation **********************
2903******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002904
drh7ed97b92010-01-20 13:07:21 +00002905/******************************************************************************
2906*************************** Begin NFS Locking ********************************/
2907
2908#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2909/*
drh308c2a52010-05-14 11:30:18 +00002910 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002911 ** must be either NO_LOCK or SHARED_LOCK.
2912 **
2913 ** If the locking level of the file descriptor is already at or below
2914 ** the requested locking level, this routine is a no-op.
2915 */
drh308c2a52010-05-14 11:30:18 +00002916static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002917 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002918}
2919
2920#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2921/*
2922** The code above is the NFS lock implementation. The code is specific
2923** to MacOSX and does not work on other unix platforms. No alternative
2924** is available.
2925**
2926********************* End of the NFS lock implementation **********************
2927******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002928
2929/******************************************************************************
2930**************** Non-locking sqlite3_file methods *****************************
2931**
2932** The next division contains implementations for all methods of the
2933** sqlite3_file object other than the locking methods. The locking
2934** methods were defined in divisions above (one locking method per
2935** division). Those methods that are common to all locking modes
2936** are gather together into this division.
2937*/
drhbfe66312006-10-03 17:40:40 +00002938
2939/*
drh734c9862008-11-28 15:37:20 +00002940** Seek to the offset passed as the second argument, then read cnt
2941** bytes into pBuf. Return the number of bytes actually read.
2942**
2943** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2944** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2945** one system to another. Since SQLite does not define USE_PREAD
2946** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2947** See tickets #2741 and #2681.
2948**
2949** To avoid stomping the errno value on a failed read the lastErrno value
2950** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002951*/
drh734c9862008-11-28 15:37:20 +00002952static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2953 int got;
drh58024642011-11-07 18:16:00 +00002954 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00002955#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002956 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002957#endif
drh734c9862008-11-28 15:37:20 +00002958 TIMER_START;
drh58024642011-11-07 18:16:00 +00002959 do{
drh734c9862008-11-28 15:37:20 +00002960#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00002961 got = osPread(id->h, pBuf, cnt, offset);
2962 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002963#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00002964 got = osPread64(id->h, pBuf, cnt, offset);
2965 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002966#else
drh58024642011-11-07 18:16:00 +00002967 newOffset = lseek(id->h, offset, SEEK_SET);
2968 SimulateIOError( newOffset-- );
2969 if( newOffset!=offset ){
2970 if( newOffset == -1 ){
2971 ((unixFile*)id)->lastErrno = errno;
2972 }else{
2973 ((unixFile*)id)->lastErrno = 0;
2974 }
2975 return -1;
drh734c9862008-11-28 15:37:20 +00002976 }
drh58024642011-11-07 18:16:00 +00002977 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00002978#endif
drh58024642011-11-07 18:16:00 +00002979 if( got==cnt ) break;
2980 if( got<0 ){
2981 if( errno==EINTR ){ got = 1; continue; }
2982 prior = 0;
2983 ((unixFile*)id)->lastErrno = errno;
2984 break;
2985 }else if( got>0 ){
2986 cnt -= got;
2987 offset += got;
2988 prior += got;
2989 pBuf = (void*)(got + (char*)pBuf);
2990 }
2991 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00002992 TIMER_END;
drh58024642011-11-07 18:16:00 +00002993 OSTRACE(("READ %-3d %5d %7lld %llu\n",
2994 id->h, got+prior, offset-prior, TIMER_ELAPSED));
2995 return got+prior;
drhbfe66312006-10-03 17:40:40 +00002996}
2997
2998/*
drh734c9862008-11-28 15:37:20 +00002999** Read data from a file into a buffer. Return SQLITE_OK if all
3000** bytes were read successfully and SQLITE_IOERR if anything goes
3001** wrong.
drh339eb0b2008-03-07 15:34:11 +00003002*/
drh734c9862008-11-28 15:37:20 +00003003static int unixRead(
3004 sqlite3_file *id,
3005 void *pBuf,
3006 int amt,
3007 sqlite3_int64 offset
3008){
dan08da86a2009-08-21 17:18:03 +00003009 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003010 int got;
3011 assert( id );
drh08c6d442009-02-09 17:34:07 +00003012
dan08da86a2009-08-21 17:18:03 +00003013 /* If this is a database file (not a journal, master-journal or temp
3014 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003015#if 0
dane946c392009-08-22 11:39:46 +00003016 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003017 || offset>=PENDING_BYTE+512
3018 || offset+amt<=PENDING_BYTE
3019 );
dan7c246102010-04-12 19:00:29 +00003020#endif
drh08c6d442009-02-09 17:34:07 +00003021
dan08da86a2009-08-21 17:18:03 +00003022 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003023 if( got==amt ){
3024 return SQLITE_OK;
3025 }else if( got<0 ){
3026 /* lastErrno set by seekAndRead */
3027 return SQLITE_IOERR_READ;
3028 }else{
dan08da86a2009-08-21 17:18:03 +00003029 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003030 /* Unread parts of the buffer must be zero-filled */
3031 memset(&((char*)pBuf)[got], 0, amt-got);
3032 return SQLITE_IOERR_SHORT_READ;
3033 }
3034}
3035
3036/*
3037** Seek to the offset in id->offset then read cnt bytes into pBuf.
3038** Return the number of bytes actually read. Update the offset.
3039**
3040** To avoid stomping the errno value on a failed write the lastErrno value
3041** is set before returning.
3042*/
3043static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3044 int got;
drh7ed97b92010-01-20 13:07:21 +00003045#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003046 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003047#endif
drh734c9862008-11-28 15:37:20 +00003048 TIMER_START;
3049#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003050 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003051#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003052 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003053#else
drhbd1e50c2011-08-19 14:54:12 +00003054 do{
3055 newOffset = lseek(id->h, offset, SEEK_SET);
3056 SimulateIOError( newOffset-- );
3057 if( newOffset!=offset ){
3058 if( newOffset == -1 ){
3059 ((unixFile*)id)->lastErrno = errno;
3060 }else{
3061 ((unixFile*)id)->lastErrno = 0;
3062 }
3063 return -1;
drh734c9862008-11-28 15:37:20 +00003064 }
drhbd1e50c2011-08-19 14:54:12 +00003065 got = osWrite(id->h, pBuf, cnt);
3066 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003067#endif
3068 TIMER_END;
3069 if( got<0 ){
3070 ((unixFile*)id)->lastErrno = errno;
3071 }
3072
drh308c2a52010-05-14 11:30:18 +00003073 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003074 return got;
3075}
3076
3077
3078/*
3079** Write data from a buffer into a file. Return SQLITE_OK on success
3080** or some other error code on failure.
3081*/
3082static int unixWrite(
3083 sqlite3_file *id,
3084 const void *pBuf,
3085 int amt,
3086 sqlite3_int64 offset
3087){
dan08da86a2009-08-21 17:18:03 +00003088 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003089 int wrote = 0;
3090 assert( id );
3091 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003092
dan08da86a2009-08-21 17:18:03 +00003093 /* If this is a database file (not a journal, master-journal or temp
3094 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003095#if 0
dane946c392009-08-22 11:39:46 +00003096 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003097 || offset>=PENDING_BYTE+512
3098 || offset+amt<=PENDING_BYTE
3099 );
dan7c246102010-04-12 19:00:29 +00003100#endif
drh08c6d442009-02-09 17:34:07 +00003101
drh8f941bc2009-01-14 23:03:40 +00003102#ifndef NDEBUG
3103 /* If we are doing a normal write to a database file (as opposed to
3104 ** doing a hot-journal rollback or a write to some file other than a
3105 ** normal database file) then record the fact that the database
3106 ** has changed. If the transaction counter is modified, record that
3107 ** fact too.
3108 */
dan08da86a2009-08-21 17:18:03 +00003109 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003110 pFile->dbUpdate = 1; /* The database has been modified */
3111 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003112 int rc;
drh8f941bc2009-01-14 23:03:40 +00003113 char oldCntr[4];
3114 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003115 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003116 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003117 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003118 pFile->transCntrChng = 1; /* The transaction counter has changed */
3119 }
3120 }
3121 }
3122#endif
3123
dan08da86a2009-08-21 17:18:03 +00003124 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003125 amt -= wrote;
3126 offset += wrote;
3127 pBuf = &((char*)pBuf)[wrote];
3128 }
3129 SimulateIOError(( wrote=(-1), amt=1 ));
3130 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003131
drh734c9862008-11-28 15:37:20 +00003132 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003133 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003134 /* lastErrno set by seekAndWrite */
3135 return SQLITE_IOERR_WRITE;
3136 }else{
dan08da86a2009-08-21 17:18:03 +00003137 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003138 return SQLITE_FULL;
3139 }
3140 }
dan6e09d692010-07-27 18:34:15 +00003141
drh734c9862008-11-28 15:37:20 +00003142 return SQLITE_OK;
3143}
3144
3145#ifdef SQLITE_TEST
3146/*
3147** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003148** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003149*/
3150int sqlite3_sync_count = 0;
3151int sqlite3_fullsync_count = 0;
3152#endif
3153
3154/*
drh89240432009-03-25 01:06:01 +00003155** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003156** Others do no. To be safe, we will stick with the (slightly slower)
3157** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003158** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003159*/
drh20f8e132011-08-31 21:01:55 +00003160#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003161# define fdatasync fsync
3162#endif
3163
3164/*
3165** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3166** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3167** only available on Mac OS X. But that could change.
3168*/
3169#ifdef F_FULLFSYNC
3170# define HAVE_FULLFSYNC 1
3171#else
3172# define HAVE_FULLFSYNC 0
3173#endif
3174
3175
3176/*
3177** The fsync() system call does not work as advertised on many
3178** unix systems. The following procedure is an attempt to make
3179** it work better.
3180**
3181** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3182** for testing when we want to run through the test suite quickly.
3183** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3184** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3185** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003186**
3187** SQLite sets the dataOnly flag if the size of the file is unchanged.
3188** The idea behind dataOnly is that it should only write the file content
3189** to disk, not the inode. We only set dataOnly if the file size is
3190** unchanged since the file size is part of the inode. However,
3191** Ted Ts'o tells us that fdatasync() will also write the inode if the
3192** file size has changed. The only real difference between fdatasync()
3193** and fsync(), Ted tells us, is that fdatasync() will not flush the
3194** inode if the mtime or owner or other inode attributes have changed.
3195** We only care about the file size, not the other file attributes, so
3196** as far as SQLite is concerned, an fdatasync() is always adequate.
3197** So, we always use fdatasync() if it is available, regardless of
3198** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003199*/
3200static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003201 int rc;
drh734c9862008-11-28 15:37:20 +00003202
3203 /* The following "ifdef/elif/else/" block has the same structure as
3204 ** the one below. It is replicated here solely to avoid cluttering
3205 ** up the real code with the UNUSED_PARAMETER() macros.
3206 */
3207#ifdef SQLITE_NO_SYNC
3208 UNUSED_PARAMETER(fd);
3209 UNUSED_PARAMETER(fullSync);
3210 UNUSED_PARAMETER(dataOnly);
3211#elif HAVE_FULLFSYNC
3212 UNUSED_PARAMETER(dataOnly);
3213#else
3214 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003215 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003216#endif
3217
3218 /* Record the number of times that we do a normal fsync() and
3219 ** FULLSYNC. This is used during testing to verify that this procedure
3220 ** gets called with the correct arguments.
3221 */
3222#ifdef SQLITE_TEST
3223 if( fullSync ) sqlite3_fullsync_count++;
3224 sqlite3_sync_count++;
3225#endif
3226
3227 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3228 ** no-op
3229 */
3230#ifdef SQLITE_NO_SYNC
3231 rc = SQLITE_OK;
3232#elif HAVE_FULLFSYNC
3233 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003234 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003235 }else{
3236 rc = 1;
3237 }
3238 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003239 ** It shouldn't be possible for fullfsync to fail on the local
3240 ** file system (on OSX), so failure indicates that FULLFSYNC
3241 ** isn't supported for this file system. So, attempt an fsync
3242 ** and (for now) ignore the overhead of a superfluous fcntl call.
3243 ** It'd be better to detect fullfsync support once and avoid
3244 ** the fcntl call every time sync is called.
3245 */
drh734c9862008-11-28 15:37:20 +00003246 if( rc ) rc = fsync(fd);
3247
drh7ed97b92010-01-20 13:07:21 +00003248#elif defined(__APPLE__)
3249 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3250 ** so currently we default to the macro that redefines fdatasync to fsync
3251 */
3252 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003253#else
drh0b647ff2009-03-21 14:41:04 +00003254 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003255#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003256 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003257 rc = fsync(fd);
3258 }
drh0b647ff2009-03-21 14:41:04 +00003259#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003260#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3261
3262 if( OS_VXWORKS && rc!= -1 ){
3263 rc = 0;
3264 }
chw97185482008-11-17 08:05:31 +00003265 return rc;
drhbfe66312006-10-03 17:40:40 +00003266}
3267
drh734c9862008-11-28 15:37:20 +00003268/*
drh0059eae2011-08-08 23:48:40 +00003269** Open a file descriptor to the directory containing file zFilename.
3270** If successful, *pFd is set to the opened file descriptor and
3271** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3272** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3273** value.
3274**
drh90315a22011-08-10 01:52:12 +00003275** The directory file descriptor is used for only one thing - to
3276** fsync() a directory to make sure file creation and deletion events
3277** are flushed to disk. Such fsyncs are not needed on newer
3278** journaling filesystems, but are required on older filesystems.
3279**
3280** This routine can be overridden using the xSetSysCall interface.
3281** The ability to override this routine was added in support of the
3282** chromium sandbox. Opening a directory is a security risk (we are
3283** told) so making it overrideable allows the chromium sandbox to
3284** replace this routine with a harmless no-op. To make this routine
3285** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3286** *pFd set to a negative number.
3287**
drh0059eae2011-08-08 23:48:40 +00003288** If SQLITE_OK is returned, the caller is responsible for closing
3289** the file descriptor *pFd using close().
3290*/
3291static int openDirectory(const char *zFilename, int *pFd){
3292 int ii;
3293 int fd = -1;
3294 char zDirname[MAX_PATHNAME+1];
3295
3296 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3297 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3298 if( ii>0 ){
3299 zDirname[ii] = '\0';
3300 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3301 if( fd>=0 ){
3302#ifdef FD_CLOEXEC
3303 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3304#endif
3305 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3306 }
3307 }
3308 *pFd = fd;
3309 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3310}
3311
3312/*
drh734c9862008-11-28 15:37:20 +00003313** Make sure all writes to a particular file are committed to disk.
3314**
3315** If dataOnly==0 then both the file itself and its metadata (file
3316** size, access time, etc) are synced. If dataOnly!=0 then only the
3317** file data is synced.
3318**
3319** Under Unix, also make sure that the directory entry for the file
3320** has been created by fsync-ing the directory that contains the file.
3321** If we do not do this and we encounter a power failure, the directory
3322** entry for the journal might not exist after we reboot. The next
3323** SQLite to access the file will not know that the journal exists (because
3324** the directory entry for the journal was never created) and the transaction
3325** will not roll back - possibly leading to database corruption.
3326*/
3327static int unixSync(sqlite3_file *id, int flags){
3328 int rc;
3329 unixFile *pFile = (unixFile*)id;
3330
3331 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3332 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3333
3334 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3335 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3336 || (flags&0x0F)==SQLITE_SYNC_FULL
3337 );
3338
3339 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3340 ** line is to test that doing so does not cause any problems.
3341 */
3342 SimulateDiskfullError( return SQLITE_FULL );
3343
3344 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003345 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003346 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3347 SimulateIOError( rc=1 );
3348 if( rc ){
3349 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003350 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003351 }
drh0059eae2011-08-08 23:48:40 +00003352
3353 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003354 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3355 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003356 */
3357 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3358 int dirfd;
3359 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003360 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003361 rc = osOpenDirectory(pFile->zPath, &dirfd);
3362 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003363 full_fsync(dirfd, 0, 0);
3364 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003365 }else if( rc==SQLITE_CANTOPEN ){
3366 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003367 }
drh0059eae2011-08-08 23:48:40 +00003368 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003369 }
3370 return rc;
3371}
3372
3373/*
3374** Truncate an open file to a specified size
3375*/
3376static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003377 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003378 int rc;
dan6e09d692010-07-27 18:34:15 +00003379 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003380 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003381
3382 /* If the user has configured a chunk-size for this file, truncate the
3383 ** file so that it consists of an integer number of chunks (i.e. the
3384 ** actual file size after the operation may be larger than the requested
3385 ** size).
3386 */
3387 if( pFile->szChunk ){
3388 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3389 }
3390
drhff812312011-02-23 13:33:46 +00003391 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003392 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003393 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003394 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003395 }else{
drh3313b142009-11-06 04:13:18 +00003396#ifndef NDEBUG
3397 /* If we are doing a normal write to a database file (as opposed to
3398 ** doing a hot-journal rollback or a write to some file other than a
3399 ** normal database file) and we truncate the file to zero length,
3400 ** that effectively updates the change counter. This might happen
3401 ** when restoring a database using the backup API from a zero-length
3402 ** source.
3403 */
dan6e09d692010-07-27 18:34:15 +00003404 if( pFile->inNormalWrite && nByte==0 ){
3405 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003406 }
3407#endif
3408
drh734c9862008-11-28 15:37:20 +00003409 return SQLITE_OK;
3410 }
3411}
3412
3413/*
3414** Determine the current size of a file in bytes
3415*/
3416static int unixFileSize(sqlite3_file *id, i64 *pSize){
3417 int rc;
3418 struct stat buf;
3419 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003420 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003421 SimulateIOError( rc=1 );
3422 if( rc!=0 ){
3423 ((unixFile*)id)->lastErrno = errno;
3424 return SQLITE_IOERR_FSTAT;
3425 }
3426 *pSize = buf.st_size;
3427
drh8af6c222010-05-14 12:43:01 +00003428 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003429 ** writes a single byte into that file in order to work around a bug
3430 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3431 ** layers, we need to report this file size as zero even though it is
3432 ** really 1. Ticket #3260.
3433 */
3434 if( *pSize==1 ) *pSize = 0;
3435
3436
3437 return SQLITE_OK;
3438}
3439
drhd2cb50b2009-01-09 21:41:17 +00003440#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003441/*
3442** Handler for proxy-locking file-control verbs. Defined below in the
3443** proxying locking division.
3444*/
3445static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003446#endif
drh715ff302008-12-03 22:32:44 +00003447
dan502019c2010-07-28 14:26:17 +00003448/*
3449** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003450** file-control operation. Enlarge the database to nBytes in size
3451** (rounded up to the next chunk-size). If the database is already
3452** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003453*/
3454static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003455 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003456 i64 nSize; /* Required file size */
3457 struct stat buf; /* Used to hold return values of fstat() */
3458
drh99ab3b12011-03-02 15:09:07 +00003459 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003460
3461 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3462 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003463
dan502019c2010-07-28 14:26:17 +00003464#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003465 /* The code below is handling the return value of osFallocate()
3466 ** correctly. posix_fallocate() is defined to "returns zero on success,
3467 ** or an error number on failure". See the manpage for details. */
3468 int err;
drhff812312011-02-23 13:33:46 +00003469 do{
dan661d71a2011-03-30 19:08:03 +00003470 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3471 }while( err==EINTR );
3472 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003473#else
3474 /* If the OS does not have posix_fallocate(), fake it. First use
3475 ** ftruncate() to set the file size, then write a single byte to
3476 ** the last byte in each block within the extended region. This
3477 ** is the same technique used by glibc to implement posix_fallocate()
3478 ** on systems that do not have a real fallocate() system call.
3479 */
3480 int nBlk = buf.st_blksize; /* File-system block size */
3481 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003482
drhff812312011-02-23 13:33:46 +00003483 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003484 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003485 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003486 }
3487 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003488 while( iWrite<nSize ){
3489 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3490 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003491 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003492 }
dan502019c2010-07-28 14:26:17 +00003493#endif
3494 }
3495 }
3496
3497 return SQLITE_OK;
3498}
danielk1977ad94b582007-08-20 06:44:22 +00003499
danielk1977e3026632004-06-22 11:29:02 +00003500/*
drh9e33c2c2007-08-31 18:34:59 +00003501** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003502*/
drhcc6bb3e2007-08-31 16:11:35 +00003503static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003504 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003505 switch( op ){
3506 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003507 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003508 return SQLITE_OK;
3509 }
drh7708e972008-11-29 00:56:52 +00003510 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003511 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003512 return SQLITE_OK;
3513 }
dan6e09d692010-07-27 18:34:15 +00003514 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003515 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003516 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003517 }
drh9ff27ec2010-05-19 19:26:05 +00003518 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003519 int rc;
3520 SimulateIOErrorBenign(1);
3521 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3522 SimulateIOErrorBenign(0);
3523 return rc;
drhf0b190d2011-07-26 16:03:07 +00003524 }
3525 case SQLITE_FCNTL_PERSIST_WAL: {
3526 int bPersist = *(int*)pArg;
3527 if( bPersist<0 ){
drh253cea52011-07-26 16:23:25 +00003528 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
drhf0b190d2011-07-26 16:03:07 +00003529 }else if( bPersist==0 ){
3530 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
3531 }else{
3532 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
3533 }
3534 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003535 }
drh8f941bc2009-01-14 23:03:40 +00003536#ifndef NDEBUG
3537 /* The pager calls this method to signal that it has done
3538 ** a rollback and that the database is therefore unchanged and
3539 ** it hence it is OK for the transaction change counter to be
3540 ** unchanged.
3541 */
3542 case SQLITE_FCNTL_DB_UNCHANGED: {
3543 ((unixFile*)id)->dbUpdate = 0;
3544 return SQLITE_OK;
3545 }
3546#endif
drhd2cb50b2009-01-09 21:41:17 +00003547#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003548 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003549 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003550 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003551 }
drhd2cb50b2009-01-09 21:41:17 +00003552#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003553 case SQLITE_FCNTL_SYNC_OMITTED: {
3554 return SQLITE_OK; /* A no-op */
3555 }
drh9e33c2c2007-08-31 18:34:59 +00003556 }
drh0b52b7d2011-01-26 19:46:22 +00003557 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003558}
3559
3560/*
danielk1977a3d4c882007-03-23 10:08:38 +00003561** Return the sector size in bytes of the underlying block device for
3562** the specified file. This is almost always 512 bytes, but may be
3563** larger for some devices.
3564**
3565** SQLite code assumes this function cannot fail. It also assumes that
3566** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003567** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003568** same for both.
3569*/
danielk1977397d65f2008-11-19 11:35:39 +00003570static int unixSectorSize(sqlite3_file *NotUsed){
3571 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003572 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003573}
3574
danielk197790949c22007-08-17 16:50:38 +00003575/*
danielk1977397d65f2008-11-19 11:35:39 +00003576** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003577*/
danielk1977397d65f2008-11-19 11:35:39 +00003578static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3579 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003580 return 0;
3581}
3582
drhd9e5c4f2010-05-12 18:01:39 +00003583#ifndef SQLITE_OMIT_WAL
3584
3585
3586/*
drhd91c68f2010-05-14 14:52:25 +00003587** Object used to represent an shared memory buffer.
3588**
3589** When multiple threads all reference the same wal-index, each thread
3590** has its own unixShm object, but they all point to a single instance
3591** of this unixShmNode object. In other words, each wal-index is opened
3592** only once per process.
3593**
3594** Each unixShmNode object is connected to a single unixInodeInfo object.
3595** We could coalesce this object into unixInodeInfo, but that would mean
3596** every open file that does not use shared memory (in other words, most
3597** open files) would have to carry around this extra information. So
3598** the unixInodeInfo object contains a pointer to this unixShmNode object
3599** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003600**
3601** unixMutexHeld() must be true when creating or destroying
3602** this object or while reading or writing the following fields:
3603**
3604** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003605**
3606** The following fields are read-only after the object is created:
3607**
3608** fid
3609** zFilename
3610**
drhd91c68f2010-05-14 14:52:25 +00003611** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003612** unixMutexHeld() is true when reading or writing any other field
3613** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003614*/
drhd91c68f2010-05-14 14:52:25 +00003615struct unixShmNode {
3616 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003617 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003618 char *zFilename; /* Name of the mmapped file */
3619 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003620 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003621 u16 nRegion; /* Size of array apRegion */
3622 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003623 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003624 int nRef; /* Number of unixShm objects pointing to this */
3625 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003626#ifdef SQLITE_DEBUG
3627 u8 exclMask; /* Mask of exclusive locks held */
3628 u8 sharedMask; /* Mask of shared locks held */
3629 u8 nextShmId; /* Next available unixShm.id value */
3630#endif
3631};
3632
3633/*
drhd9e5c4f2010-05-12 18:01:39 +00003634** Structure used internally by this VFS to record the state of an
3635** open shared memory connection.
3636**
drhd91c68f2010-05-14 14:52:25 +00003637** The following fields are initialized when this object is created and
3638** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003639**
drhd91c68f2010-05-14 14:52:25 +00003640** unixShm.pFile
3641** unixShm.id
3642**
3643** All other fields are read/write. The unixShm.pFile->mutex must be held
3644** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003645*/
3646struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003647 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3648 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003649 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003650 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003651 u16 sharedMask; /* Mask of shared locks held */
3652 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003653};
3654
3655/*
drhd9e5c4f2010-05-12 18:01:39 +00003656** Constants used for locking
3657*/
drhbd9676c2010-06-23 17:58:38 +00003658#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003659#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003660
drhd9e5c4f2010-05-12 18:01:39 +00003661/*
drh73b64e42010-05-30 19:55:15 +00003662** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003663**
3664** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3665** otherwise.
3666*/
3667static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003668 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3669 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003670 int ofst, /* First byte of the locking range */
3671 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003672){
3673 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003674 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003675
drhd91c68f2010-05-14 14:52:25 +00003676 /* Access to the unixShmNode object is serialized by the caller */
3677 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003678
drh73b64e42010-05-30 19:55:15 +00003679 /* Shared locks never span more than one byte */
3680 assert( n==1 || lockType!=F_RDLCK );
3681
3682 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003683 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003684
drh3cb93392011-03-12 18:10:44 +00003685 if( pShmNode->h>=0 ){
3686 /* Initialize the locking parameters */
3687 memset(&f, 0, sizeof(f));
3688 f.l_type = lockType;
3689 f.l_whence = SEEK_SET;
3690 f.l_start = ofst;
3691 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003692
drh3cb93392011-03-12 18:10:44 +00003693 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3694 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3695 }
drhd9e5c4f2010-05-12 18:01:39 +00003696
3697 /* Update the global lock state and do debug tracing */
3698#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003699 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003700 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003701 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003702 if( rc==SQLITE_OK ){
3703 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003704 OSTRACE(("unlock %d ok", ofst));
3705 pShmNode->exclMask &= ~mask;
3706 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003707 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003708 OSTRACE(("read-lock %d ok", ofst));
3709 pShmNode->exclMask &= ~mask;
3710 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003711 }else{
3712 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003713 OSTRACE(("write-lock %d ok", ofst));
3714 pShmNode->exclMask |= mask;
3715 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003716 }
3717 }else{
3718 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003719 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003720 }else if( lockType==F_RDLCK ){
3721 OSTRACE(("read-lock failed"));
3722 }else{
3723 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003724 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003725 }
3726 }
drh20e1f082010-05-31 16:10:12 +00003727 OSTRACE((" - afterwards %03x,%03x\n",
3728 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003729 }
drhd9e5c4f2010-05-12 18:01:39 +00003730#endif
3731
3732 return rc;
3733}
3734
drhd9e5c4f2010-05-12 18:01:39 +00003735
3736/*
drhd91c68f2010-05-14 14:52:25 +00003737** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003738**
3739** This is not a VFS shared-memory method; it is a utility function called
3740** by VFS shared-memory methods.
3741*/
drhd91c68f2010-05-14 14:52:25 +00003742static void unixShmPurge(unixFile *pFd){
3743 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003744 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003745 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003746 int i;
drhd91c68f2010-05-14 14:52:25 +00003747 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003748 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003749 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003750 if( p->h>=0 ){
3751 munmap(p->apRegion[i], p->szRegion);
3752 }else{
3753 sqlite3_free(p->apRegion[i]);
3754 }
dan13a3cb82010-06-11 19:04:21 +00003755 }
dan18801912010-06-14 14:07:50 +00003756 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003757 if( p->h>=0 ){
3758 robust_close(pFd, p->h, __LINE__);
3759 p->h = -1;
3760 }
drhd91c68f2010-05-14 14:52:25 +00003761 p->pInode->pShmNode = 0;
3762 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003763 }
3764}
3765
3766/*
danda9fe0c2010-07-13 18:44:03 +00003767** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003768** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003769**
drh7234c6d2010-06-19 15:10:09 +00003770** The file used to implement shared-memory is in the same directory
3771** as the open database file and has the same name as the open database
3772** file with the "-shm" suffix added. For example, if the database file
3773** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003774** for shared memory will be called "/home/user1/config.db-shm".
3775**
3776** Another approach to is to use files in /dev/shm or /dev/tmp or an
3777** some other tmpfs mount. But if a file in a different directory
3778** from the database file is used, then differing access permissions
3779** or a chroot() might cause two different processes on the same
3780** database to end up using different files for shared memory -
3781** meaning that their memory would not really be shared - resulting
3782** in database corruption. Nevertheless, this tmpfs file usage
3783** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3784** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3785** option results in an incompatible build of SQLite; builds of SQLite
3786** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3787** same database file at the same time, database corruption will likely
3788** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3789** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003790**
3791** When opening a new shared-memory file, if no other instances of that
3792** file are currently open, in this process or in other processes, then
3793** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003794**
3795** If the original database file (pDbFd) is using the "unix-excl" VFS
3796** that means that an exclusive lock is held on the database file and
3797** that no other processes are able to read or write the database. In
3798** that case, we do not really need shared memory. No shared memory
3799** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003800*/
danda9fe0c2010-07-13 18:44:03 +00003801static int unixOpenSharedMemory(unixFile *pDbFd){
3802 struct unixShm *p = 0; /* The connection to be opened */
3803 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3804 int rc; /* Result code */
3805 unixInodeInfo *pInode; /* The inode of fd */
3806 char *zShmFilename; /* Name of the file used for SHM */
3807 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003808
danda9fe0c2010-07-13 18:44:03 +00003809 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003810 p = sqlite3_malloc( sizeof(*p) );
3811 if( p==0 ) return SQLITE_NOMEM;
3812 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003813 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003814
danda9fe0c2010-07-13 18:44:03 +00003815 /* Check to see if a unixShmNode object already exists. Reuse an existing
3816 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003817 */
3818 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003819 pInode = pDbFd->pInode;
3820 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003821 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003822 struct stat sStat; /* fstat() info for database file */
3823
3824 /* Call fstat() to figure out the permissions on the database file. If
3825 ** a new *-shm file is created, an attempt will be made to create it
3826 ** with the same permissions. The actual permissions the file is created
3827 ** with are subject to the current umask setting.
3828 */
drh3cb93392011-03-12 18:10:44 +00003829 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003830 rc = SQLITE_IOERR_FSTAT;
3831 goto shm_open_err;
3832 }
3833
drha4ced192010-07-15 18:32:40 +00003834#ifdef SQLITE_SHM_DIRECTORY
3835 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3836#else
drh7234c6d2010-06-19 15:10:09 +00003837 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003838#endif
drh7234c6d2010-06-19 15:10:09 +00003839 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003840 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003841 rc = SQLITE_NOMEM;
3842 goto shm_open_err;
3843 }
drhd91c68f2010-05-14 14:52:25 +00003844 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003845 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003846#ifdef SQLITE_SHM_DIRECTORY
3847 sqlite3_snprintf(nShmFilename, zShmFilename,
3848 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3849 (u32)sStat.st_ino, (u32)sStat.st_dev);
3850#else
drh7234c6d2010-06-19 15:10:09 +00003851 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003852 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003853#endif
drhd91c68f2010-05-14 14:52:25 +00003854 pShmNode->h = -1;
3855 pDbFd->pInode->pShmNode = pShmNode;
3856 pShmNode->pInode = pDbFd->pInode;
3857 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3858 if( pShmNode->mutex==0 ){
3859 rc = SQLITE_NOMEM;
3860 goto shm_open_err;
3861 }
drhd9e5c4f2010-05-12 18:01:39 +00003862
drh3cb93392011-03-12 18:10:44 +00003863 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003864 const char *zRO;
3865 int openFlags = O_RDWR | O_CREAT;
3866 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
3867 if( zRO && sqlite3GetBoolean(zRO) ){
3868 openFlags = O_RDONLY;
3869 pShmNode->isReadonly = 1;
3870 }
3871 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003872 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003873 if( pShmNode->h<0 ){
3874 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3875 goto shm_open_err;
3876 }
drhd9e5c4f2010-05-12 18:01:39 +00003877 }
drh3cb93392011-03-12 18:10:44 +00003878
3879 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003880 ** If not, truncate the file to zero length.
3881 */
3882 rc = SQLITE_OK;
3883 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3884 if( robust_ftruncate(pShmNode->h, 0) ){
3885 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003886 }
3887 }
drh66dfec8b2011-06-01 20:01:49 +00003888 if( rc==SQLITE_OK ){
3889 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3890 }
3891 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003892 }
drhd9e5c4f2010-05-12 18:01:39 +00003893 }
3894
drhd91c68f2010-05-14 14:52:25 +00003895 /* Make the new connection a child of the unixShmNode */
3896 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003897#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003898 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003899#endif
drhd91c68f2010-05-14 14:52:25 +00003900 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003901 pDbFd->pShm = p;
3902 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003903
3904 /* The reference count on pShmNode has already been incremented under
3905 ** the cover of the unixEnterMutex() mutex and the pointer from the
3906 ** new (struct unixShm) object to the pShmNode has been set. All that is
3907 ** left to do is to link the new object into the linked list starting
3908 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3909 ** mutex.
3910 */
3911 sqlite3_mutex_enter(pShmNode->mutex);
3912 p->pNext = pShmNode->pFirst;
3913 pShmNode->pFirst = p;
3914 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003915 return SQLITE_OK;
3916
3917 /* Jump here on any error */
3918shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003919 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003920 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003921 unixLeaveMutex();
3922 return rc;
3923}
3924
3925/*
danda9fe0c2010-07-13 18:44:03 +00003926** This function is called to obtain a pointer to region iRegion of the
3927** shared-memory associated with the database file fd. Shared-memory regions
3928** are numbered starting from zero. Each shared-memory region is szRegion
3929** bytes in size.
3930**
3931** If an error occurs, an error code is returned and *pp is set to NULL.
3932**
3933** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3934** region has not been allocated (by any client, including one running in a
3935** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3936** bExtend is non-zero and the requested shared-memory region has not yet
3937** been allocated, it is allocated by this function.
3938**
3939** If the shared-memory region has already been allocated or is allocated by
3940** this call as described above, then it is mapped into this processes
3941** address space (if it is not already), *pp is set to point to the mapped
3942** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003943*/
danda9fe0c2010-07-13 18:44:03 +00003944static int unixShmMap(
3945 sqlite3_file *fd, /* Handle open on database file */
3946 int iRegion, /* Region to retrieve */
3947 int szRegion, /* Size of regions */
3948 int bExtend, /* True to extend file if necessary */
3949 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003950){
danda9fe0c2010-07-13 18:44:03 +00003951 unixFile *pDbFd = (unixFile*)fd;
3952 unixShm *p;
3953 unixShmNode *pShmNode;
3954 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003955
danda9fe0c2010-07-13 18:44:03 +00003956 /* If the shared-memory file has not yet been opened, open it now. */
3957 if( pDbFd->pShm==0 ){
3958 rc = unixOpenSharedMemory(pDbFd);
3959 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003960 }
drhd9e5c4f2010-05-12 18:01:39 +00003961
danda9fe0c2010-07-13 18:44:03 +00003962 p = pDbFd->pShm;
3963 pShmNode = p->pShmNode;
3964 sqlite3_mutex_enter(pShmNode->mutex);
3965 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003966 assert( pShmNode->pInode==pDbFd->pInode );
3967 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3968 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003969
3970 if( pShmNode->nRegion<=iRegion ){
3971 char **apNew; /* New apRegion[] array */
3972 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3973 struct stat sStat; /* Used by fstat() */
3974
3975 pShmNode->szRegion = szRegion;
3976
drh3cb93392011-03-12 18:10:44 +00003977 if( pShmNode->h>=0 ){
3978 /* The requested region is not mapped into this processes address space.
3979 ** Check to see if it has been allocated (i.e. if the wal-index file is
3980 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003981 */
drh3cb93392011-03-12 18:10:44 +00003982 if( osFstat(pShmNode->h, &sStat) ){
3983 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003984 goto shmpage_out;
3985 }
drh3cb93392011-03-12 18:10:44 +00003986
3987 if( sStat.st_size<nByte ){
3988 /* The requested memory region does not exist. If bExtend is set to
3989 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3990 **
3991 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3992 ** the requested memory region.
3993 */
3994 if( !bExtend ) goto shmpage_out;
3995 if( robust_ftruncate(pShmNode->h, nByte) ){
3996 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3997 pShmNode->zFilename);
3998 goto shmpage_out;
3999 }
4000 }
danda9fe0c2010-07-13 18:44:03 +00004001 }
4002
4003 /* Map the requested memory region into this processes address space. */
4004 apNew = (char **)sqlite3_realloc(
4005 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4006 );
4007 if( !apNew ){
4008 rc = SQLITE_IOERR_NOMEM;
4009 goto shmpage_out;
4010 }
4011 pShmNode->apRegion = apNew;
4012 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004013 void *pMem;
4014 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004015 pMem = mmap(0, szRegion,
4016 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004017 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4018 );
4019 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004020 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004021 goto shmpage_out;
4022 }
4023 }else{
4024 pMem = sqlite3_malloc(szRegion);
4025 if( pMem==0 ){
4026 rc = SQLITE_NOMEM;
4027 goto shmpage_out;
4028 }
4029 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004030 }
4031 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4032 pShmNode->nRegion++;
4033 }
4034 }
4035
4036shmpage_out:
4037 if( pShmNode->nRegion>iRegion ){
4038 *pp = pShmNode->apRegion[iRegion];
4039 }else{
4040 *pp = 0;
4041 }
drh66dfec8b2011-06-01 20:01:49 +00004042 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004043 sqlite3_mutex_leave(pShmNode->mutex);
4044 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004045}
4046
4047/*
drhd9e5c4f2010-05-12 18:01:39 +00004048** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004049**
4050** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4051** different here than in posix. In xShmLock(), one can go from unlocked
4052** to shared and back or from unlocked to exclusive and back. But one may
4053** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004054*/
4055static int unixShmLock(
4056 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004057 int ofst, /* First lock to acquire or release */
4058 int n, /* Number of locks to acquire or release */
4059 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004060){
drh73b64e42010-05-30 19:55:15 +00004061 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4062 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4063 unixShm *pX; /* For looping over all siblings */
4064 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4065 int rc = SQLITE_OK; /* Result code */
4066 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004067
drhd91c68f2010-05-14 14:52:25 +00004068 assert( pShmNode==pDbFd->pInode->pShmNode );
4069 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004070 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004071 assert( n>=1 );
4072 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4073 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4074 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4075 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4076 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004077 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4078 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004079
drhc99597c2010-05-31 01:41:15 +00004080 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004081 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004082 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004083 if( flags & SQLITE_SHM_UNLOCK ){
4084 u16 allMask = 0; /* Mask of locks held by siblings */
4085
4086 /* See if any siblings hold this same lock */
4087 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4088 if( pX==p ) continue;
4089 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4090 allMask |= pX->sharedMask;
4091 }
4092
4093 /* Unlock the system-level locks */
4094 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004095 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004096 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004097 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004098 }
drh73b64e42010-05-30 19:55:15 +00004099
4100 /* Undo the local locks */
4101 if( rc==SQLITE_OK ){
4102 p->exclMask &= ~mask;
4103 p->sharedMask &= ~mask;
4104 }
4105 }else if( flags & SQLITE_SHM_SHARED ){
4106 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4107
4108 /* Find out which shared locks are already held by sibling connections.
4109 ** If any sibling already holds an exclusive lock, go ahead and return
4110 ** SQLITE_BUSY.
4111 */
4112 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004113 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004114 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004115 break;
4116 }
4117 allShared |= pX->sharedMask;
4118 }
4119
4120 /* Get shared locks at the system level, if necessary */
4121 if( rc==SQLITE_OK ){
4122 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004123 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004124 }else{
drh73b64e42010-05-30 19:55:15 +00004125 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004126 }
drhd9e5c4f2010-05-12 18:01:39 +00004127 }
drh73b64e42010-05-30 19:55:15 +00004128
4129 /* Get the local shared locks */
4130 if( rc==SQLITE_OK ){
4131 p->sharedMask |= mask;
4132 }
4133 }else{
4134 /* Make sure no sibling connections hold locks that will block this
4135 ** lock. If any do, return SQLITE_BUSY right away.
4136 */
4137 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004138 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4139 rc = SQLITE_BUSY;
4140 break;
4141 }
4142 }
4143
4144 /* Get the exclusive locks at the system level. Then if successful
4145 ** also mark the local connection as being locked.
4146 */
4147 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004148 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004149 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004150 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004151 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004152 }
drhd9e5c4f2010-05-12 18:01:39 +00004153 }
4154 }
drhd91c68f2010-05-14 14:52:25 +00004155 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004156 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4157 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004158 return rc;
4159}
4160
drh286a2882010-05-20 23:51:06 +00004161/*
4162** Implement a memory barrier or memory fence on shared memory.
4163**
4164** All loads and stores begun before the barrier must complete before
4165** any load or store begun after the barrier.
4166*/
4167static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004168 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004169){
drhff828942010-06-26 21:34:06 +00004170 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004171 unixEnterMutex();
4172 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004173}
4174
dan18801912010-06-14 14:07:50 +00004175/*
danda9fe0c2010-07-13 18:44:03 +00004176** Close a connection to shared-memory. Delete the underlying
4177** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004178**
4179** If there is no shared memory associated with the connection then this
4180** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004181*/
danda9fe0c2010-07-13 18:44:03 +00004182static int unixShmUnmap(
4183 sqlite3_file *fd, /* The underlying database file */
4184 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004185){
danda9fe0c2010-07-13 18:44:03 +00004186 unixShm *p; /* The connection to be closed */
4187 unixShmNode *pShmNode; /* The underlying shared-memory file */
4188 unixShm **pp; /* For looping over sibling connections */
4189 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004190
danda9fe0c2010-07-13 18:44:03 +00004191 pDbFd = (unixFile*)fd;
4192 p = pDbFd->pShm;
4193 if( p==0 ) return SQLITE_OK;
4194 pShmNode = p->pShmNode;
4195
4196 assert( pShmNode==pDbFd->pInode->pShmNode );
4197 assert( pShmNode->pInode==pDbFd->pInode );
4198
4199 /* Remove connection p from the set of connections associated
4200 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004201 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004202 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4203 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004204
danda9fe0c2010-07-13 18:44:03 +00004205 /* Free the connection p */
4206 sqlite3_free(p);
4207 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004208 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004209
4210 /* If pShmNode->nRef has reached 0, then close the underlying
4211 ** shared-memory file, too */
4212 unixEnterMutex();
4213 assert( pShmNode->nRef>0 );
4214 pShmNode->nRef--;
4215 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004216 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004217 unixShmPurge(pDbFd);
4218 }
4219 unixLeaveMutex();
4220
4221 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004222}
drh286a2882010-05-20 23:51:06 +00004223
danda9fe0c2010-07-13 18:44:03 +00004224
drhd9e5c4f2010-05-12 18:01:39 +00004225#else
drh6b017cc2010-06-14 18:01:46 +00004226# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004227# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004228# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004229# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004230#endif /* #ifndef SQLITE_OMIT_WAL */
4231
drh734c9862008-11-28 15:37:20 +00004232/*
4233** Here ends the implementation of all sqlite3_file methods.
4234**
4235********************** End sqlite3_file Methods *******************************
4236******************************************************************************/
4237
4238/*
drh6b9d6dd2008-12-03 19:34:47 +00004239** This division contains definitions of sqlite3_io_methods objects that
4240** implement various file locking strategies. It also contains definitions
4241** of "finder" functions. A finder-function is used to locate the appropriate
4242** sqlite3_io_methods object for a particular database file. The pAppData
4243** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4244** the correct finder-function for that VFS.
4245**
4246** Most finder functions return a pointer to a fixed sqlite3_io_methods
4247** object. The only interesting finder-function is autolockIoFinder, which
4248** looks at the filesystem type and tries to guess the best locking
4249** strategy from that.
4250**
drh1875f7a2008-12-08 18:19:17 +00004251** For finder-funtion F, two objects are created:
4252**
4253** (1) The real finder-function named "FImpt()".
4254**
dane946c392009-08-22 11:39:46 +00004255** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004256**
4257**
4258** A pointer to the F pointer is used as the pAppData value for VFS
4259** objects. We have to do this instead of letting pAppData point
4260** directly at the finder-function since C90 rules prevent a void*
4261** from be cast into a function pointer.
4262**
drh6b9d6dd2008-12-03 19:34:47 +00004263**
drh7708e972008-11-29 00:56:52 +00004264** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004265**
drh7708e972008-11-29 00:56:52 +00004266** * A constant sqlite3_io_methods object call METHOD that has locking
4267** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4268**
4269** * An I/O method finder function called FINDER that returns a pointer
4270** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004271*/
drhd9e5c4f2010-05-12 18:01:39 +00004272#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004273static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004274 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004275 CLOSE, /* xClose */ \
4276 unixRead, /* xRead */ \
4277 unixWrite, /* xWrite */ \
4278 unixTruncate, /* xTruncate */ \
4279 unixSync, /* xSync */ \
4280 unixFileSize, /* xFileSize */ \
4281 LOCK, /* xLock */ \
4282 UNLOCK, /* xUnlock */ \
4283 CKLOCK, /* xCheckReservedLock */ \
4284 unixFileControl, /* xFileControl */ \
4285 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004286 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004287 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004288 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004289 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004290 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004291}; \
drh0c2694b2009-09-03 16:23:44 +00004292static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4293 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004294 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004295} \
drh0c2694b2009-09-03 16:23:44 +00004296static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004297 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004298
4299/*
4300** Here are all of the sqlite3_io_methods objects for each of the
4301** locking strategies. Functions that return pointers to these methods
4302** are also created.
4303*/
4304IOMETHODS(
4305 posixIoFinder, /* Finder function name */
4306 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004307 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004308 unixClose, /* xClose method */
4309 unixLock, /* xLock method */
4310 unixUnlock, /* xUnlock method */
4311 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004312)
drh7708e972008-11-29 00:56:52 +00004313IOMETHODS(
4314 nolockIoFinder, /* Finder function name */
4315 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004316 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004317 nolockClose, /* xClose method */
4318 nolockLock, /* xLock method */
4319 nolockUnlock, /* xUnlock method */
4320 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004321)
drh7708e972008-11-29 00:56:52 +00004322IOMETHODS(
4323 dotlockIoFinder, /* Finder function name */
4324 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004325 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004326 dotlockClose, /* xClose method */
4327 dotlockLock, /* xLock method */
4328 dotlockUnlock, /* xUnlock method */
4329 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004330)
drh7708e972008-11-29 00:56:52 +00004331
chw78a13182009-04-07 05:35:03 +00004332#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004333IOMETHODS(
4334 flockIoFinder, /* Finder function name */
4335 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004336 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004337 flockClose, /* xClose method */
4338 flockLock, /* xLock method */
4339 flockUnlock, /* xUnlock method */
4340 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004341)
drh7708e972008-11-29 00:56:52 +00004342#endif
4343
drh6c7d5c52008-11-21 20:32:33 +00004344#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004345IOMETHODS(
4346 semIoFinder, /* Finder function name */
4347 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004348 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004349 semClose, /* xClose method */
4350 semLock, /* xLock method */
4351 semUnlock, /* xUnlock method */
4352 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004353)
aswiftaebf4132008-11-21 00:10:35 +00004354#endif
drh7708e972008-11-29 00:56:52 +00004355
drhd2cb50b2009-01-09 21:41:17 +00004356#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004357IOMETHODS(
4358 afpIoFinder, /* Finder function name */
4359 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004360 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004361 afpClose, /* xClose method */
4362 afpLock, /* xLock method */
4363 afpUnlock, /* xUnlock method */
4364 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004365)
drh715ff302008-12-03 22:32:44 +00004366#endif
4367
4368/*
4369** The proxy locking method is a "super-method" in the sense that it
4370** opens secondary file descriptors for the conch and lock files and
4371** it uses proxy, dot-file, AFP, and flock() locking methods on those
4372** secondary files. For this reason, the division that implements
4373** proxy locking is located much further down in the file. But we need
4374** to go ahead and define the sqlite3_io_methods and finder function
4375** for proxy locking here. So we forward declare the I/O methods.
4376*/
drhd2cb50b2009-01-09 21:41:17 +00004377#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004378static int proxyClose(sqlite3_file*);
4379static int proxyLock(sqlite3_file*, int);
4380static int proxyUnlock(sqlite3_file*, int);
4381static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004382IOMETHODS(
4383 proxyIoFinder, /* Finder function name */
4384 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004385 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004386 proxyClose, /* xClose method */
4387 proxyLock, /* xLock method */
4388 proxyUnlock, /* xUnlock method */
4389 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004390)
aswiftaebf4132008-11-21 00:10:35 +00004391#endif
drh7708e972008-11-29 00:56:52 +00004392
drh7ed97b92010-01-20 13:07:21 +00004393/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4394#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4395IOMETHODS(
4396 nfsIoFinder, /* Finder function name */
4397 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004398 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004399 unixClose, /* xClose method */
4400 unixLock, /* xLock method */
4401 nfsUnlock, /* xUnlock method */
4402 unixCheckReservedLock /* xCheckReservedLock method */
4403)
4404#endif
drh7708e972008-11-29 00:56:52 +00004405
drhd2cb50b2009-01-09 21:41:17 +00004406#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004407/*
drh6b9d6dd2008-12-03 19:34:47 +00004408** This "finder" function attempts to determine the best locking strategy
4409** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004410** object that implements that strategy.
4411**
4412** This is for MacOSX only.
4413*/
drh1875f7a2008-12-08 18:19:17 +00004414static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004415 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004416 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004417){
4418 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004419 const char *zFilesystem; /* Filesystem type name */
4420 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004421 } aMap[] = {
4422 { "hfs", &posixIoMethods },
4423 { "ufs", &posixIoMethods },
4424 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004425 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004426 { "webdav", &nolockIoMethods },
4427 { 0, 0 }
4428 };
4429 int i;
4430 struct statfs fsInfo;
4431 struct flock lockInfo;
4432
4433 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004434 /* If filePath==NULL that means we are dealing with a transient file
4435 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004436 return &nolockIoMethods;
4437 }
4438 if( statfs(filePath, &fsInfo) != -1 ){
4439 if( fsInfo.f_flags & MNT_RDONLY ){
4440 return &nolockIoMethods;
4441 }
4442 for(i=0; aMap[i].zFilesystem; i++){
4443 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4444 return aMap[i].pMethods;
4445 }
4446 }
4447 }
4448
4449 /* Default case. Handles, amongst others, "nfs".
4450 ** Test byte-range lock using fcntl(). If the call succeeds,
4451 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004452 */
drh7708e972008-11-29 00:56:52 +00004453 lockInfo.l_len = 1;
4454 lockInfo.l_start = 0;
4455 lockInfo.l_whence = SEEK_SET;
4456 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004457 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004458 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4459 return &nfsIoMethods;
4460 } else {
4461 return &posixIoMethods;
4462 }
drh7708e972008-11-29 00:56:52 +00004463 }else{
4464 return &dotlockIoMethods;
4465 }
4466}
drh0c2694b2009-09-03 16:23:44 +00004467static const sqlite3_io_methods
4468 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004469
drhd2cb50b2009-01-09 21:41:17 +00004470#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004471
chw78a13182009-04-07 05:35:03 +00004472#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4473/*
4474** This "finder" function attempts to determine the best locking strategy
4475** for the database file "filePath". It then returns the sqlite3_io_methods
4476** object that implements that strategy.
4477**
4478** This is for VXWorks only.
4479*/
4480static const sqlite3_io_methods *autolockIoFinderImpl(
4481 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004482 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004483){
4484 struct flock lockInfo;
4485
4486 if( !filePath ){
4487 /* If filePath==NULL that means we are dealing with a transient file
4488 ** that does not need to be locked. */
4489 return &nolockIoMethods;
4490 }
4491
4492 /* Test if fcntl() is supported and use POSIX style locks.
4493 ** Otherwise fall back to the named semaphore method.
4494 */
4495 lockInfo.l_len = 1;
4496 lockInfo.l_start = 0;
4497 lockInfo.l_whence = SEEK_SET;
4498 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004499 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004500 return &posixIoMethods;
4501 }else{
4502 return &semIoMethods;
4503 }
4504}
drh0c2694b2009-09-03 16:23:44 +00004505static const sqlite3_io_methods
4506 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004507
4508#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4509
drh7708e972008-11-29 00:56:52 +00004510/*
4511** An abstract type for a pointer to a IO method finder function:
4512*/
drh0c2694b2009-09-03 16:23:44 +00004513typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004514
aswiftaebf4132008-11-21 00:10:35 +00004515
drh734c9862008-11-28 15:37:20 +00004516/****************************************************************************
4517**************************** sqlite3_vfs methods ****************************
4518**
4519** This division contains the implementation of methods on the
4520** sqlite3_vfs object.
4521*/
4522
danielk1977a3d4c882007-03-23 10:08:38 +00004523/*
danielk1977e339d652008-06-28 11:23:00 +00004524** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004525*/
4526static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004527 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004528 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004529 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004530 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004531 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004532 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004533 int isDelete, /* Delete on close if true */
4534 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004535){
drh7708e972008-11-29 00:56:52 +00004536 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004537 unixFile *pNew = (unixFile *)pId;
4538 int rc = SQLITE_OK;
4539
drh8af6c222010-05-14 12:43:01 +00004540 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004541
dane946c392009-08-22 11:39:46 +00004542 /* Parameter isDelete is only used on vxworks. Express this explicitly
4543 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004544 */
drh7708e972008-11-29 00:56:52 +00004545 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004546
dan00157392010-10-05 11:33:15 +00004547 /* Usually the path zFilename should not be a relative pathname. The
4548 ** exception is when opening the proxy "conch" file in builds that
4549 ** include the special Apple locking styles.
4550 */
dan00157392010-10-05 11:33:15 +00004551#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004552 assert( zFilename==0 || zFilename[0]=='/'
4553 || pVfs->pAppData==(void*)&autolockIoFinder );
4554#else
4555 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004556#endif
dan00157392010-10-05 11:33:15 +00004557
drhb07028f2011-10-14 21:49:18 +00004558 /* No locking occurs in temporary files */
4559 assert( zFilename!=0 || noLock );
4560
drh308c2a52010-05-14 11:30:18 +00004561 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004562 pNew->h = h;
drhd9e5c4f2010-05-12 18:01:39 +00004563 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004564 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4565 pNew->ctrlFlags = UNIXFILE_EXCL;
4566 }else{
4567 pNew->ctrlFlags = 0;
4568 }
drh77197112011-03-15 19:08:48 +00004569 if( isReadOnly ){
4570 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4571 }
drh0059eae2011-08-08 23:48:40 +00004572 if( syncDir ){
4573 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4574 }
drh339eb0b2008-03-07 15:34:11 +00004575
drh6c7d5c52008-11-21 20:32:33 +00004576#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004577 pNew->pId = vxworksFindFileId(zFilename);
4578 if( pNew->pId==0 ){
4579 noLock = 1;
4580 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004581 }
4582#endif
4583
drhda0e7682008-07-30 15:27:54 +00004584 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004585 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004586 }else{
drh0c2694b2009-09-03 16:23:44 +00004587 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004588#if SQLITE_ENABLE_LOCKING_STYLE
4589 /* Cache zFilename in the locking context (AFP and dotlock override) for
4590 ** proxyLock activation is possible (remote proxy is based on db name)
4591 ** zFilename remains valid until file is closed, to support */
4592 pNew->lockingContext = (void*)zFilename;
4593#endif
drhda0e7682008-07-30 15:27:54 +00004594 }
danielk1977e339d652008-06-28 11:23:00 +00004595
drh7ed97b92010-01-20 13:07:21 +00004596 if( pLockingStyle == &posixIoMethods
4597#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4598 || pLockingStyle == &nfsIoMethods
4599#endif
4600 ){
drh7708e972008-11-29 00:56:52 +00004601 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004602 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004603 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004604 /* If an error occured in findInodeInfo(), close the file descriptor
4605 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004606 ** in two scenarios:
4607 **
4608 ** (a) A call to fstat() failed.
4609 ** (b) A malloc failed.
4610 **
4611 ** Scenario (b) may only occur if the process is holding no other
4612 ** file descriptors open on the same file. If there were other file
4613 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004614 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004615 ** handle h - as it is guaranteed that no posix locks will be released
4616 ** by doing so.
4617 **
4618 ** If scenario (a) caused the error then things are not so safe. The
4619 ** implicit assumption here is that if fstat() fails, things are in
4620 ** such bad shape that dropping a lock or two doesn't matter much.
4621 */
drh0e9365c2011-03-02 02:08:13 +00004622 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004623 h = -1;
4624 }
drh7708e972008-11-29 00:56:52 +00004625 unixLeaveMutex();
4626 }
danielk1977e339d652008-06-28 11:23:00 +00004627
drhd2cb50b2009-01-09 21:41:17 +00004628#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004629 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004630 /* AFP locking uses the file path so it needs to be included in
4631 ** the afpLockingContext.
4632 */
4633 afpLockingContext *pCtx;
4634 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4635 if( pCtx==0 ){
4636 rc = SQLITE_NOMEM;
4637 }else{
4638 /* NB: zFilename exists and remains valid until the file is closed
4639 ** according to requirement F11141. So we do not need to make a
4640 ** copy of the filename. */
4641 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004642 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004643 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004644 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004645 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004646 if( rc!=SQLITE_OK ){
4647 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004648 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004649 h = -1;
4650 }
drh7708e972008-11-29 00:56:52 +00004651 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004652 }
drh7708e972008-11-29 00:56:52 +00004653 }
4654#endif
danielk1977e339d652008-06-28 11:23:00 +00004655
drh7708e972008-11-29 00:56:52 +00004656 else if( pLockingStyle == &dotlockIoMethods ){
4657 /* Dotfile locking uses the file path so it needs to be included in
4658 ** the dotlockLockingContext
4659 */
4660 char *zLockFile;
4661 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004662 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004663 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004664 zLockFile = (char *)sqlite3_malloc(nFilename);
4665 if( zLockFile==0 ){
4666 rc = SQLITE_NOMEM;
4667 }else{
4668 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004669 }
drh7708e972008-11-29 00:56:52 +00004670 pNew->lockingContext = zLockFile;
4671 }
danielk1977e339d652008-06-28 11:23:00 +00004672
drh6c7d5c52008-11-21 20:32:33 +00004673#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004674 else if( pLockingStyle == &semIoMethods ){
4675 /* Named semaphore locking uses the file path so it needs to be
4676 ** included in the semLockingContext
4677 */
4678 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004679 rc = findInodeInfo(pNew, &pNew->pInode);
4680 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4681 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004682 int n;
drh2238dcc2009-08-27 17:56:20 +00004683 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004684 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004685 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004686 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004687 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4688 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004689 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004690 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004691 }
chw97185482008-11-17 08:05:31 +00004692 }
drh7708e972008-11-29 00:56:52 +00004693 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004694 }
drh7708e972008-11-29 00:56:52 +00004695#endif
aswift5b1a2562008-08-22 00:22:35 +00004696
4697 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004698#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004699 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004700 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004701 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004702 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004703 isDelete = 0;
4704 }
4705 pNew->isDelete = isDelete;
4706#endif
danielk1977e339d652008-06-28 11:23:00 +00004707 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004708 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004709 }else{
drh7708e972008-11-29 00:56:52 +00004710 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004711 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004712 }
danielk1977e339d652008-06-28 11:23:00 +00004713 return rc;
drh054889e2005-11-30 03:20:31 +00004714}
drh9c06c952005-11-26 00:25:00 +00004715
danielk1977ad94b582007-08-20 06:44:22 +00004716/*
drh8b3cf822010-06-01 21:02:51 +00004717** Return the name of a directory in which to put temporary files.
4718** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004719*/
drh7234c6d2010-06-19 15:10:09 +00004720static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004721 static const char *azDirs[] = {
4722 0,
aswiftaebf4132008-11-21 00:10:35 +00004723 0,
danielk197717b90b52008-06-06 11:11:25 +00004724 "/var/tmp",
4725 "/usr/tmp",
4726 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004727 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004728 };
drh8b3cf822010-06-01 21:02:51 +00004729 unsigned int i;
4730 struct stat buf;
4731 const char *zDir = 0;
4732
4733 azDirs[0] = sqlite3_temp_directory;
4734 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004735 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004736 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004737 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004738 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004739 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004740 break;
4741 }
4742 return zDir;
4743}
4744
4745/*
4746** Create a temporary file name in zBuf. zBuf must be allocated
4747** by the calling process and must be big enough to hold at least
4748** pVfs->mxPathname bytes.
4749*/
4750static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004751 static const unsigned char zChars[] =
4752 "abcdefghijklmnopqrstuvwxyz"
4753 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4754 "0123456789";
drh41022642008-11-21 00:24:42 +00004755 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004756 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004757
4758 /* It's odd to simulate an io-error here, but really this is just
4759 ** using the io-error infrastructure to test that SQLite handles this
4760 ** function failing.
4761 */
4762 SimulateIOError( return SQLITE_IOERR );
4763
drh7234c6d2010-06-19 15:10:09 +00004764 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004765 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004766
4767 /* Check that the output buffer is large enough for the temporary file
4768 ** name. If it is not, return SQLITE_ERROR.
4769 */
danielk197700e13612008-11-17 19:18:54 +00004770 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004771 return SQLITE_ERROR;
4772 }
4773
4774 do{
4775 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004776 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004777 sqlite3_randomness(15, &zBuf[j]);
4778 for(i=0; i<15; i++, j++){
4779 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4780 }
4781 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004782 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004783 return SQLITE_OK;
4784}
4785
drhd2cb50b2009-01-09 21:41:17 +00004786#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004787/*
4788** Routine to transform a unixFile into a proxy-locking unixFile.
4789** Implementation in the proxy-lock division, but used by unixOpen()
4790** if SQLITE_PREFER_PROXY_LOCKING is defined.
4791*/
4792static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004793#endif
drhc66d5b62008-12-03 22:48:32 +00004794
dan08da86a2009-08-21 17:18:03 +00004795/*
4796** Search for an unused file descriptor that was opened on the database
4797** file (not a journal or master-journal file) identified by pathname
4798** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4799** argument to this function.
4800**
4801** Such a file descriptor may exist if a database connection was closed
4802** but the associated file descriptor could not be closed because some
4803** other file descriptor open on the same file is holding a file-lock.
4804** Refer to comments in the unixClose() function and the lengthy comment
4805** describing "Posix Advisory Locking" at the start of this file for
4806** further details. Also, ticket #4018.
4807**
4808** If a suitable file descriptor is found, then it is returned. If no
4809** such file descriptor is located, -1 is returned.
4810*/
dane946c392009-08-22 11:39:46 +00004811static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4812 UnixUnusedFd *pUnused = 0;
4813
4814 /* Do not search for an unused file descriptor on vxworks. Not because
4815 ** vxworks would not benefit from the change (it might, we're not sure),
4816 ** but because no way to test it is currently available. It is better
4817 ** not to risk breaking vxworks support for the sake of such an obscure
4818 ** feature. */
4819#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004820 struct stat sStat; /* Results of stat() call */
4821
4822 /* A stat() call may fail for various reasons. If this happens, it is
4823 ** almost certain that an open() call on the same path will also fail.
4824 ** For this reason, if an error occurs in the stat() call here, it is
4825 ** ignored and -1 is returned. The caller will try to open a new file
4826 ** descriptor on the same path, fail, and return an error to SQLite.
4827 **
4828 ** Even if a subsequent open() call does succeed, the consequences of
4829 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004830 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004831 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004832
4833 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004834 pInode = inodeList;
4835 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4836 || pInode->fileId.ino!=sStat.st_ino) ){
4837 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004838 }
drh8af6c222010-05-14 12:43:01 +00004839 if( pInode ){
dane946c392009-08-22 11:39:46 +00004840 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004841 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004842 pUnused = *pp;
4843 if( pUnused ){
4844 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004845 }
4846 }
4847 unixLeaveMutex();
4848 }
dane946c392009-08-22 11:39:46 +00004849#endif /* if !OS_VXWORKS */
4850 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004851}
danielk197717b90b52008-06-06 11:11:25 +00004852
4853/*
danddb0ac42010-07-14 14:48:58 +00004854** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004855** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004856** and a value suitable for passing as the third argument to open(2) is
4857** written to *pMode. If an IO error occurs, an SQLite error code is
4858** returned and the value of *pMode is not modified.
4859**
4860** If the file being opened is a temporary file, it is always created with
4861** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004862** is a database or master journal file, it is created with the permissions
4863** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004864**
drh8ab58662010-07-15 18:38:39 +00004865** Finally, if the file being opened is a WAL or regular journal file, then
4866** this function queries the file-system for the permissions on the
4867** corresponding database file and sets *pMode to this value. Whenever
4868** possible, WAL and journal files are created using the same permissions
4869** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004870**
4871** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4872** original filename is unavailable. But 8_3_NAMES is only used for
4873** FAT filesystems and permissions do not matter there, so just use
4874** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004875*/
4876static int findCreateFileMode(
4877 const char *zPath, /* Path of file (possibly) being created */
4878 int flags, /* Flags passed as 4th argument to xOpen() */
4879 mode_t *pMode /* OUT: Permissions to open file with */
4880){
4881 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004882 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004883 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004884 char zDb[MAX_PATHNAME+1]; /* Database file path */
4885 int nDb; /* Number of valid bytes in zDb */
4886 struct stat sStat; /* Output of stat() on database file */
4887
dana0c989d2010-11-05 18:07:37 +00004888 /* zPath is a path to a WAL or journal file. The following block derives
4889 ** the path to the associated database file from zPath. This block handles
4890 ** the following naming conventions:
4891 **
4892 ** "<path to db>-journal"
4893 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004894 ** "<path to db>-journalNN"
4895 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004896 **
drhd337c5b2011-10-20 18:23:35 +00004897 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004898 ** used by the test_multiplex.c module.
4899 */
4900 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004901#ifdef SQLITE_ENABLE_8_3_NAMES
drhd337c5b2011-10-20 18:23:35 +00004902 while( nDb>0 && !sqlite3Isalnum(zPath[nDb]) ) nDb--;
4903 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004904#else
4905 while( zPath[nDb]!='-' ){
4906 assert( nDb>0 );
4907 assert( zPath[nDb]!='\n' );
4908 nDb--;
4909 }
4910#endif
danddb0ac42010-07-14 14:48:58 +00004911 memcpy(zDb, zPath, nDb);
4912 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004913
drh58384f12011-07-28 00:14:45 +00004914 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004915 *pMode = sStat.st_mode & 0777;
4916 }else{
4917 rc = SQLITE_IOERR_FSTAT;
4918 }
4919 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4920 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004921 }
4922 return rc;
4923}
4924
4925/*
danielk1977ad94b582007-08-20 06:44:22 +00004926** Open the file zPath.
4927**
danielk1977b4b47412007-08-17 15:53:36 +00004928** Previously, the SQLite OS layer used three functions in place of this
4929** one:
4930**
4931** sqlite3OsOpenReadWrite();
4932** sqlite3OsOpenReadOnly();
4933** sqlite3OsOpenExclusive();
4934**
4935** These calls correspond to the following combinations of flags:
4936**
4937** ReadWrite() -> (READWRITE | CREATE)
4938** ReadOnly() -> (READONLY)
4939** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4940**
4941** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4942** true, the file was configured to be automatically deleted when the
4943** file handle closed. To achieve the same effect using this new
4944** interface, add the DELETEONCLOSE flag to those specified above for
4945** OpenExclusive().
4946*/
4947static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004948 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4949 const char *zPath, /* Pathname of file to be opened */
4950 sqlite3_file *pFile, /* The file descriptor to be filled in */
4951 int flags, /* Input flags to control the opening */
4952 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004953){
dan08da86a2009-08-21 17:18:03 +00004954 unixFile *p = (unixFile *)pFile;
4955 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004956 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004957 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004958 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004959 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004960
4961 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4962 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4963 int isCreate = (flags & SQLITE_OPEN_CREATE);
4964 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4965 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004966#if SQLITE_ENABLE_LOCKING_STYLE
4967 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4968#endif
drh3d4435b2011-08-26 20:55:50 +00004969#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4970 struct statfs fsInfo;
4971#endif
danielk1977b4b47412007-08-17 15:53:36 +00004972
danielk1977fee2d252007-08-18 10:59:19 +00004973 /* If creating a master or main-file journal, this function will open
4974 ** a file-descriptor on the directory too. The first time unixSync()
4975 ** is called the directory file descriptor will be fsync()ed and close()d.
4976 */
drh0059eae2011-08-08 23:48:40 +00004977 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00004978 eType==SQLITE_OPEN_MASTER_JOURNAL
4979 || eType==SQLITE_OPEN_MAIN_JOURNAL
4980 || eType==SQLITE_OPEN_WAL
4981 ));
danielk1977fee2d252007-08-18 10:59:19 +00004982
danielk197717b90b52008-06-06 11:11:25 +00004983 /* If argument zPath is a NULL pointer, this function is required to open
4984 ** a temporary file. Use this buffer to store the file name in.
4985 */
4986 char zTmpname[MAX_PATHNAME+1];
4987 const char *zName = zPath;
4988
danielk1977fee2d252007-08-18 10:59:19 +00004989 /* Check the following statements are true:
4990 **
4991 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4992 ** (b) if CREATE is set, then READWRITE must also be set, and
4993 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004994 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004995 */
danielk1977b4b47412007-08-17 15:53:36 +00004996 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004997 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004998 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004999 assert(isDelete==0 || isCreate);
5000
danddb0ac42010-07-14 14:48:58 +00005001 /* The main DB, main journal, WAL file and master journal are never
5002 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005003 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5004 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5005 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005006 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005007
danielk1977fee2d252007-08-18 10:59:19 +00005008 /* Assert that the upper layer has set one of the "file-type" flags. */
5009 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5010 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5011 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005012 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005013 );
5014
dan08da86a2009-08-21 17:18:03 +00005015 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005016
dan08da86a2009-08-21 17:18:03 +00005017 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005018 UnixUnusedFd *pUnused;
5019 pUnused = findReusableFd(zName, flags);
5020 if( pUnused ){
5021 fd = pUnused->fd;
5022 }else{
dan6aa657f2009-08-24 18:57:58 +00005023 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005024 if( !pUnused ){
5025 return SQLITE_NOMEM;
5026 }
5027 }
5028 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00005029 }else if( !zName ){
5030 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005031 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00005032 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005033 if( rc!=SQLITE_OK ){
5034 return rc;
5035 }
5036 zName = zTmpname;
5037 }
5038
dan08da86a2009-08-21 17:18:03 +00005039 /* Determine the value of the flags parameter passed to POSIX function
5040 ** open(). These must be calculated even if open() is not called, as
5041 ** they may be stored as part of the file handle and used by the
5042 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005043 if( isReadonly ) openFlags |= O_RDONLY;
5044 if( isReadWrite ) openFlags |= O_RDWR;
5045 if( isCreate ) openFlags |= O_CREAT;
5046 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5047 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005048
danielk1977b4b47412007-08-17 15:53:36 +00005049 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005050 mode_t openMode; /* Permissions to create file with */
5051 rc = findCreateFileMode(zName, flags, &openMode);
5052 if( rc!=SQLITE_OK ){
5053 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005054 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005055 return rc;
5056 }
drhad4f1e52011-03-04 15:43:57 +00005057 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005058 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005059 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5060 /* Failed to open the file for read/write access. Try read-only. */
5061 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005062 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005063 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005064 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005065 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005066 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005067 }
5068 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005069 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005070 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005071 }
danielk1977b4b47412007-08-17 15:53:36 +00005072 }
dan08da86a2009-08-21 17:18:03 +00005073 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005074 if( pOutFlags ){
5075 *pOutFlags = flags;
5076 }
5077
dane946c392009-08-22 11:39:46 +00005078 if( p->pUnused ){
5079 p->pUnused->fd = fd;
5080 p->pUnused->flags = flags;
5081 }
5082
danielk1977b4b47412007-08-17 15:53:36 +00005083 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005084#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005085 zPath = zName;
5086#else
drh036ac7f2011-08-08 23:18:05 +00005087 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005088#endif
danielk1977b4b47412007-08-17 15:53:36 +00005089 }
drh41022642008-11-21 00:24:42 +00005090#if SQLITE_ENABLE_LOCKING_STYLE
5091 else{
dan08da86a2009-08-21 17:18:03 +00005092 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005093 }
5094#endif
5095
danielk1977e339d652008-06-28 11:23:00 +00005096#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005097 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005098#endif
5099
drhda0e7682008-07-30 15:27:54 +00005100 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005101
drh7ed97b92010-01-20 13:07:21 +00005102
5103#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005104 if( fstatfs(fd, &fsInfo) == -1 ){
5105 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005106 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005107 return SQLITE_IOERR_ACCESS;
5108 }
5109 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5110 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5111 }
5112#endif
5113
5114#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005115#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005116 isAutoProxy = 1;
5117#endif
5118 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005119 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5120 int useProxy = 0;
5121
dan08da86a2009-08-21 17:18:03 +00005122 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5123 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005124 if( envforce!=NULL ){
5125 useProxy = atoi(envforce)>0;
5126 }else{
aswiftaebf4132008-11-21 00:10:35 +00005127 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005128 /* In theory, the close(fd) call is sub-optimal. If the file opened
5129 ** with fd is a database file, and there are other connections open
5130 ** on that file that are currently holding advisory locks on it,
5131 ** then the call to close() will cancel those locks. In practice,
5132 ** we're assuming that statfs() doesn't fail very often. At least
5133 ** not while other file descriptors opened by the same process on
5134 ** the same file are working. */
5135 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005136 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005137 rc = SQLITE_IOERR_ACCESS;
5138 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005139 }
5140 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5141 }
5142 if( useProxy ){
drh0059eae2011-08-08 23:48:40 +00005143 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005144 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005145 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005146 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005147 if( rc!=SQLITE_OK ){
5148 /* Use unixClose to clean up the resources added in fillInUnixFile
5149 ** and clear all the structure's references. Specifically,
5150 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5151 */
5152 unixClose(pFile);
5153 return rc;
5154 }
aswiftaebf4132008-11-21 00:10:35 +00005155 }
dane946c392009-08-22 11:39:46 +00005156 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005157 }
5158 }
5159#endif
5160
drh0059eae2011-08-08 23:48:40 +00005161 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005162 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005163open_finished:
5164 if( rc!=SQLITE_OK ){
5165 sqlite3_free(p->pUnused);
5166 }
5167 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005168}
5169
dane946c392009-08-22 11:39:46 +00005170
danielk1977b4b47412007-08-17 15:53:36 +00005171/*
danielk1977fee2d252007-08-18 10:59:19 +00005172** Delete the file at zPath. If the dirSync argument is true, fsync()
5173** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005174*/
drh6b9d6dd2008-12-03 19:34:47 +00005175static int unixDelete(
5176 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5177 const char *zPath, /* Name of file to be deleted */
5178 int dirSync /* If true, fsync() directory after deleting file */
5179){
danielk1977fee2d252007-08-18 10:59:19 +00005180 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005181 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005182 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005183 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005184 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005185 }
danielk1977d39fa702008-10-16 13:27:40 +00005186#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005187 if( dirSync ){
5188 int fd;
drh90315a22011-08-10 01:52:12 +00005189 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005190 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005191#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005192 if( fsync(fd)==-1 )
5193#else
5194 if( fsync(fd) )
5195#endif
5196 {
dane18d4952011-02-21 11:46:24 +00005197 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005198 }
drh0e9365c2011-03-02 02:08:13 +00005199 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005200 }else if( rc==SQLITE_CANTOPEN ){
5201 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005202 }
5203 }
danielk1977d138dd82008-10-15 16:02:48 +00005204#endif
danielk1977fee2d252007-08-18 10:59:19 +00005205 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005206}
5207
danielk197790949c22007-08-17 16:50:38 +00005208/*
5209** Test the existance of or access permissions of file zPath. The
5210** test performed depends on the value of flags:
5211**
5212** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5213** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5214** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5215**
5216** Otherwise return 0.
5217*/
danielk1977861f7452008-06-05 11:39:11 +00005218static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005219 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5220 const char *zPath, /* Path of the file to examine */
5221 int flags, /* What do we want to learn about the zPath file? */
5222 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005223){
rse25c0d1a2007-09-20 08:38:14 +00005224 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005225 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005226 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005227 switch( flags ){
5228 case SQLITE_ACCESS_EXISTS:
5229 amode = F_OK;
5230 break;
5231 case SQLITE_ACCESS_READWRITE:
5232 amode = W_OK|R_OK;
5233 break;
drh50d3f902007-08-27 21:10:36 +00005234 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005235 amode = R_OK;
5236 break;
5237
5238 default:
5239 assert(!"Invalid flags argument");
5240 }
drh99ab3b12011-03-02 15:09:07 +00005241 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005242 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5243 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005244 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005245 *pResOut = 0;
5246 }
5247 }
danielk1977861f7452008-06-05 11:39:11 +00005248 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005249}
5250
danielk1977b4b47412007-08-17 15:53:36 +00005251
5252/*
5253** Turn a relative pathname into a full pathname. The relative path
5254** is stored as a nul-terminated string in the buffer pointed to by
5255** zPath.
5256**
5257** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5258** (in this case, MAX_PATHNAME bytes). The full-path is written to
5259** this buffer before returning.
5260*/
danielk1977adfb9b02007-09-17 07:02:56 +00005261static int unixFullPathname(
5262 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5263 const char *zPath, /* Possibly relative input path */
5264 int nOut, /* Size of output buffer in bytes */
5265 char *zOut /* Output buffer */
5266){
danielk1977843e65f2007-09-01 16:16:15 +00005267
5268 /* It's odd to simulate an io-error here, but really this is just
5269 ** using the io-error infrastructure to test that SQLite handles this
5270 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005271 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005272 */
5273 SimulateIOError( return SQLITE_ERROR );
5274
drh153c62c2007-08-24 03:51:33 +00005275 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005276 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005277
drh3c7f2dc2007-12-06 13:26:20 +00005278 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005279 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005280 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005281 }else{
5282 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005283 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005284 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005285 }
drhea678832008-12-10 19:26:22 +00005286 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005287 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005288 }
5289 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005290}
5291
drh0ccebe72005-06-07 22:22:50 +00005292
drh761df872006-12-21 01:29:22 +00005293#ifndef SQLITE_OMIT_LOAD_EXTENSION
5294/*
5295** Interfaces for opening a shared library, finding entry points
5296** within the shared library, and closing the shared library.
5297*/
5298#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005299static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5300 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005301 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5302}
danielk197795c8a542007-09-01 06:51:27 +00005303
5304/*
5305** SQLite calls this function immediately after a call to unixDlSym() or
5306** unixDlOpen() fails (returns a null pointer). If a more detailed error
5307** message is available, it is written to zBufOut. If no error message
5308** is available, zBufOut is left unmodified and SQLite uses a default
5309** error message.
5310*/
danielk1977397d65f2008-11-19 11:35:39 +00005311static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005312 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005313 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005314 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005315 zErr = dlerror();
5316 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005317 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005318 }
drh6c7d5c52008-11-21 20:32:33 +00005319 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005320}
drh1875f7a2008-12-08 18:19:17 +00005321static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5322 /*
5323 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5324 ** cast into a pointer to a function. And yet the library dlsym() routine
5325 ** returns a void* which is really a pointer to a function. So how do we
5326 ** use dlsym() with -pedantic-errors?
5327 **
5328 ** Variable x below is defined to be a pointer to a function taking
5329 ** parameters void* and const char* and returning a pointer to a function.
5330 ** We initialize x by assigning it a pointer to the dlsym() function.
5331 ** (That assignment requires a cast.) Then we call the function that
5332 ** x points to.
5333 **
5334 ** This work-around is unlikely to work correctly on any system where
5335 ** you really cannot cast a function pointer into void*. But then, on the
5336 ** other hand, dlsym() will not work on such a system either, so we have
5337 ** not really lost anything.
5338 */
5339 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005340 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005341 x = (void(*(*)(void*,const char*))(void))dlsym;
5342 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005343}
danielk1977397d65f2008-11-19 11:35:39 +00005344static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5345 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005346 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005347}
danielk1977b4b47412007-08-17 15:53:36 +00005348#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5349 #define unixDlOpen 0
5350 #define unixDlError 0
5351 #define unixDlSym 0
5352 #define unixDlClose 0
5353#endif
5354
5355/*
danielk197790949c22007-08-17 16:50:38 +00005356** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005357*/
danielk1977397d65f2008-11-19 11:35:39 +00005358static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5359 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005360 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005361
drhbbd42a62004-05-22 17:41:58 +00005362 /* We have to initialize zBuf to prevent valgrind from reporting
5363 ** errors. The reports issued by valgrind are incorrect - we would
5364 ** prefer that the randomness be increased by making use of the
5365 ** uninitialized space in zBuf - but valgrind errors tend to worry
5366 ** some users. Rather than argue, it seems easier just to initialize
5367 ** the whole array and silence valgrind, even if that means less randomness
5368 ** in the random seed.
5369 **
5370 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005371 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005372 ** tests repeatable.
5373 */
danielk1977b4b47412007-08-17 15:53:36 +00005374 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005375#if !defined(SQLITE_TEST)
5376 {
drh842b8642005-01-21 17:53:17 +00005377 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005378 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005379 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005380 time_t t;
5381 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005382 memcpy(zBuf, &t, sizeof(t));
5383 pid = getpid();
5384 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005385 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005386 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005387 }else{
drhe562be52011-03-02 18:01:10 +00005388 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005389 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005390 }
drhbbd42a62004-05-22 17:41:58 +00005391 }
5392#endif
drh72cbd072008-10-14 17:58:38 +00005393 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005394}
5395
danielk1977b4b47412007-08-17 15:53:36 +00005396
drhbbd42a62004-05-22 17:41:58 +00005397/*
5398** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005399** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005400** The return value is the number of microseconds of sleep actually
5401** requested from the underlying operating system, a number which
5402** might be greater than or equal to the argument, but not less
5403** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005404*/
danielk1977397d65f2008-11-19 11:35:39 +00005405static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005406#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005407 struct timespec sp;
5408
5409 sp.tv_sec = microseconds / 1000000;
5410 sp.tv_nsec = (microseconds % 1000000) * 1000;
5411 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005412 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005413 return microseconds;
5414#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005415 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005416 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005417 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005418#else
danielk1977b4b47412007-08-17 15:53:36 +00005419 int seconds = (microseconds+999999)/1000000;
5420 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005421 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005422 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005423#endif
drh88f474a2006-01-02 20:00:12 +00005424}
5425
5426/*
drh6b9d6dd2008-12-03 19:34:47 +00005427** The following variable, if set to a non-zero value, is interpreted as
5428** the number of seconds since 1970 and is used to set the result of
5429** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005430*/
5431#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005432int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005433#endif
5434
5435/*
drhb7e8ea22010-05-03 14:32:30 +00005436** Find the current time (in Universal Coordinated Time). Write into *piNow
5437** the current time and date as a Julian Day number times 86_400_000. In
5438** other words, write into *piNow the number of milliseconds since the Julian
5439** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5440** proleptic Gregorian calendar.
5441**
drh31702252011-10-12 23:13:43 +00005442** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5443** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005444*/
5445static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5446 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005447 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005448#if defined(NO_GETTOD)
5449 time_t t;
5450 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005451 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005452#elif OS_VXWORKS
5453 struct timespec sNow;
5454 clock_gettime(CLOCK_REALTIME, &sNow);
5455 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5456#else
5457 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005458 if( gettimeofday(&sNow, 0)==0 ){
5459 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5460 }else{
5461 rc = SQLITE_ERROR;
5462 }
drhb7e8ea22010-05-03 14:32:30 +00005463#endif
5464
5465#ifdef SQLITE_TEST
5466 if( sqlite3_current_time ){
5467 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5468 }
5469#endif
5470 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005471 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005472}
5473
5474/*
drhbbd42a62004-05-22 17:41:58 +00005475** Find the current time (in Universal Coordinated Time). Write the
5476** current time and date as a Julian Day number into *prNow and
5477** return 0. Return 1 if the time and date cannot be found.
5478*/
danielk1977397d65f2008-11-19 11:35:39 +00005479static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005480 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005481 int rc;
drhff828942010-06-26 21:34:06 +00005482 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005483 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005484 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005485 return rc;
drhbbd42a62004-05-22 17:41:58 +00005486}
danielk1977b4b47412007-08-17 15:53:36 +00005487
drh6b9d6dd2008-12-03 19:34:47 +00005488/*
5489** We added the xGetLastError() method with the intention of providing
5490** better low-level error messages when operating-system problems come up
5491** during SQLite operation. But so far, none of that has been implemented
5492** in the core. So this routine is never called. For now, it is merely
5493** a place-holder.
5494*/
danielk1977397d65f2008-11-19 11:35:39 +00005495static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5496 UNUSED_PARAMETER(NotUsed);
5497 UNUSED_PARAMETER(NotUsed2);
5498 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005499 return 0;
5500}
5501
drhf2424c52010-04-26 00:04:55 +00005502
5503/*
drh734c9862008-11-28 15:37:20 +00005504************************ End of sqlite3_vfs methods ***************************
5505******************************************************************************/
5506
drh715ff302008-12-03 22:32:44 +00005507/******************************************************************************
5508************************** Begin Proxy Locking ********************************
5509**
5510** Proxy locking is a "uber-locking-method" in this sense: It uses the
5511** other locking methods on secondary lock files. Proxy locking is a
5512** meta-layer over top of the primitive locking implemented above. For
5513** this reason, the division that implements of proxy locking is deferred
5514** until late in the file (here) after all of the other I/O methods have
5515** been defined - so that the primitive locking methods are available
5516** as services to help with the implementation of proxy locking.
5517**
5518****
5519**
5520** The default locking schemes in SQLite use byte-range locks on the
5521** database file to coordinate safe, concurrent access by multiple readers
5522** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5523** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5524** as POSIX read & write locks over fixed set of locations (via fsctl),
5525** on AFP and SMB only exclusive byte-range locks are available via fsctl
5526** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5527** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5528** address in the shared range is taken for a SHARED lock, the entire
5529** shared range is taken for an EXCLUSIVE lock):
5530**
5531** PENDING_BYTE 0x40000000
5532** RESERVED_BYTE 0x40000001
5533** SHARED_RANGE 0x40000002 -> 0x40000200
5534**
5535** This works well on the local file system, but shows a nearly 100x
5536** slowdown in read performance on AFP because the AFP client disables
5537** the read cache when byte-range locks are present. Enabling the read
5538** cache exposes a cache coherency problem that is present on all OS X
5539** supported network file systems. NFS and AFP both observe the
5540** close-to-open semantics for ensuring cache coherency
5541** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5542** address the requirements for concurrent database access by multiple
5543** readers and writers
5544** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5545**
5546** To address the performance and cache coherency issues, proxy file locking
5547** changes the way database access is controlled by limiting access to a
5548** single host at a time and moving file locks off of the database file
5549** and onto a proxy file on the local file system.
5550**
5551**
5552** Using proxy locks
5553** -----------------
5554**
5555** C APIs
5556**
5557** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5558** <proxy_path> | ":auto:");
5559** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5560**
5561**
5562** SQL pragmas
5563**
5564** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5565** PRAGMA [database.]lock_proxy_file
5566**
5567** Specifying ":auto:" means that if there is a conch file with a matching
5568** host ID in it, the proxy path in the conch file will be used, otherwise
5569** a proxy path based on the user's temp dir
5570** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5571** actual proxy file name is generated from the name and path of the
5572** database file. For example:
5573**
5574** For database path "/Users/me/foo.db"
5575** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5576**
5577** Once a lock proxy is configured for a database connection, it can not
5578** be removed, however it may be switched to a different proxy path via
5579** the above APIs (assuming the conch file is not being held by another
5580** connection or process).
5581**
5582**
5583** How proxy locking works
5584** -----------------------
5585**
5586** Proxy file locking relies primarily on two new supporting files:
5587**
5588** * conch file to limit access to the database file to a single host
5589** at a time
5590**
5591** * proxy file to act as a proxy for the advisory locks normally
5592** taken on the database
5593**
5594** The conch file - to use a proxy file, sqlite must first "hold the conch"
5595** by taking an sqlite-style shared lock on the conch file, reading the
5596** contents and comparing the host's unique host ID (see below) and lock
5597** proxy path against the values stored in the conch. The conch file is
5598** stored in the same directory as the database file and the file name
5599** is patterned after the database file name as ".<databasename>-conch".
5600** If the conch file does not exist, or it's contents do not match the
5601** host ID and/or proxy path, then the lock is escalated to an exclusive
5602** lock and the conch file contents is updated with the host ID and proxy
5603** path and the lock is downgraded to a shared lock again. If the conch
5604** is held by another process (with a shared lock), the exclusive lock
5605** will fail and SQLITE_BUSY is returned.
5606**
5607** The proxy file - a single-byte file used for all advisory file locks
5608** normally taken on the database file. This allows for safe sharing
5609** of the database file for multiple readers and writers on the same
5610** host (the conch ensures that they all use the same local lock file).
5611**
drh715ff302008-12-03 22:32:44 +00005612** Requesting the lock proxy does not immediately take the conch, it is
5613** only taken when the first request to lock database file is made.
5614** This matches the semantics of the traditional locking behavior, where
5615** opening a connection to a database file does not take a lock on it.
5616** The shared lock and an open file descriptor are maintained until
5617** the connection to the database is closed.
5618**
5619** The proxy file and the lock file are never deleted so they only need
5620** to be created the first time they are used.
5621**
5622** Configuration options
5623** ---------------------
5624**
5625** SQLITE_PREFER_PROXY_LOCKING
5626**
5627** Database files accessed on non-local file systems are
5628** automatically configured for proxy locking, lock files are
5629** named automatically using the same logic as
5630** PRAGMA lock_proxy_file=":auto:"
5631**
5632** SQLITE_PROXY_DEBUG
5633**
5634** Enables the logging of error messages during host id file
5635** retrieval and creation
5636**
drh715ff302008-12-03 22:32:44 +00005637** LOCKPROXYDIR
5638**
5639** Overrides the default directory used for lock proxy files that
5640** are named automatically via the ":auto:" setting
5641**
5642** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5643**
5644** Permissions to use when creating a directory for storing the
5645** lock proxy files, only used when LOCKPROXYDIR is not set.
5646**
5647**
5648** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5649** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5650** force proxy locking to be used for every database file opened, and 0
5651** will force automatic proxy locking to be disabled for all database
5652** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5653** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5654*/
5655
5656/*
5657** Proxy locking is only available on MacOSX
5658*/
drhd2cb50b2009-01-09 21:41:17 +00005659#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005660
drh715ff302008-12-03 22:32:44 +00005661/*
5662** The proxyLockingContext has the path and file structures for the remote
5663** and local proxy files in it
5664*/
5665typedef struct proxyLockingContext proxyLockingContext;
5666struct proxyLockingContext {
5667 unixFile *conchFile; /* Open conch file */
5668 char *conchFilePath; /* Name of the conch file */
5669 unixFile *lockProxy; /* Open proxy lock file */
5670 char *lockProxyPath; /* Name of the proxy lock file */
5671 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005672 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005673 void *oldLockingContext; /* Original lockingcontext to restore on close */
5674 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5675};
5676
drh7ed97b92010-01-20 13:07:21 +00005677/*
5678** The proxy lock file path for the database at dbPath is written into lPath,
5679** which must point to valid, writable memory large enough for a maxLen length
5680** file path.
drh715ff302008-12-03 22:32:44 +00005681*/
drh715ff302008-12-03 22:32:44 +00005682static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5683 int len;
5684 int dbLen;
5685 int i;
5686
5687#ifdef LOCKPROXYDIR
5688 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5689#else
5690# ifdef _CS_DARWIN_USER_TEMP_DIR
5691 {
drh7ed97b92010-01-20 13:07:21 +00005692 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005693 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5694 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005695 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005696 }
drh7ed97b92010-01-20 13:07:21 +00005697 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005698 }
5699# else
5700 len = strlcpy(lPath, "/tmp/", maxLen);
5701# endif
5702#endif
5703
5704 if( lPath[len-1]!='/' ){
5705 len = strlcat(lPath, "/", maxLen);
5706 }
5707
5708 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005709 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005710 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005711 char c = dbPath[i];
5712 lPath[i+len] = (c=='/')?'_':c;
5713 }
5714 lPath[i+len]='\0';
5715 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005716 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005717 return SQLITE_OK;
5718}
5719
drh7ed97b92010-01-20 13:07:21 +00005720/*
5721 ** Creates the lock file and any missing directories in lockPath
5722 */
5723static int proxyCreateLockPath(const char *lockPath){
5724 int i, len;
5725 char buf[MAXPATHLEN];
5726 int start = 0;
5727
5728 assert(lockPath!=NULL);
5729 /* try to create all the intermediate directories */
5730 len = (int)strlen(lockPath);
5731 buf[0] = lockPath[0];
5732 for( i=1; i<len; i++ ){
5733 if( lockPath[i] == '/' && (i - start > 0) ){
5734 /* only mkdir if leaf dir != "." or "/" or ".." */
5735 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5736 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5737 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005738 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005739 int err=errno;
5740 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005741 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005742 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005743 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005744 return err;
5745 }
5746 }
5747 }
5748 start=i+1;
5749 }
5750 buf[i] = lockPath[i];
5751 }
drh308c2a52010-05-14 11:30:18 +00005752 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005753 return 0;
5754}
5755
drh715ff302008-12-03 22:32:44 +00005756/*
5757** Create a new VFS file descriptor (stored in memory obtained from
5758** sqlite3_malloc) and open the file named "path" in the file descriptor.
5759**
5760** The caller is responsible not only for closing the file descriptor
5761** but also for freeing the memory associated with the file descriptor.
5762*/
drh7ed97b92010-01-20 13:07:21 +00005763static int proxyCreateUnixFile(
5764 const char *path, /* path for the new unixFile */
5765 unixFile **ppFile, /* unixFile created and returned by ref */
5766 int islockfile /* if non zero missing dirs will be created */
5767) {
5768 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005769 unixFile *pNew;
5770 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005771 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005772 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005773 int terrno = 0;
5774 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005775
drh7ed97b92010-01-20 13:07:21 +00005776 /* 1. first try to open/create the file
5777 ** 2. if that fails, and this is a lock file (not-conch), try creating
5778 ** the parent directories and then try again.
5779 ** 3. if that fails, try to open the file read-only
5780 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5781 */
5782 pUnused = findReusableFd(path, openFlags);
5783 if( pUnused ){
5784 fd = pUnused->fd;
5785 }else{
5786 pUnused = sqlite3_malloc(sizeof(*pUnused));
5787 if( !pUnused ){
5788 return SQLITE_NOMEM;
5789 }
5790 }
5791 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005792 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005793 terrno = errno;
5794 if( fd<0 && errno==ENOENT && islockfile ){
5795 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005796 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005797 }
5798 }
5799 }
5800 if( fd<0 ){
5801 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005802 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005803 terrno = errno;
5804 }
5805 if( fd<0 ){
5806 if( islockfile ){
5807 return SQLITE_BUSY;
5808 }
5809 switch (terrno) {
5810 case EACCES:
5811 return SQLITE_PERM;
5812 case EIO:
5813 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5814 default:
drh9978c972010-02-23 17:36:32 +00005815 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005816 }
5817 }
5818
5819 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5820 if( pNew==NULL ){
5821 rc = SQLITE_NOMEM;
5822 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005823 }
5824 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005825 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005826 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005827 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005828 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005829 pUnused->fd = fd;
5830 pUnused->flags = openFlags;
5831 pNew->pUnused = pUnused;
5832
drh0059eae2011-08-08 23:48:40 +00005833 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005834 if( rc==SQLITE_OK ){
5835 *ppFile = pNew;
5836 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005837 }
drh7ed97b92010-01-20 13:07:21 +00005838end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005839 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005840 sqlite3_free(pNew);
5841 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005842 return rc;
5843}
5844
drh7ed97b92010-01-20 13:07:21 +00005845#ifdef SQLITE_TEST
5846/* simulate multiple hosts by creating unique hostid file paths */
5847int sqlite3_hostid_num = 0;
5848#endif
5849
5850#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5851
drh0ab216a2010-07-02 17:10:40 +00005852/* Not always defined in the headers as it ought to be */
5853extern int gethostuuid(uuid_t id, const struct timespec *wait);
5854
drh7ed97b92010-01-20 13:07:21 +00005855/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5856** bytes of writable memory.
5857*/
5858static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005859 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5860 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005861#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5862 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005863 {
5864 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5865 if( gethostuuid(pHostID, &timeout) ){
5866 int err = errno;
5867 if( pError ){
5868 *pError = err;
5869 }
5870 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005871 }
drh7ed97b92010-01-20 13:07:21 +00005872 }
drh3d4435b2011-08-26 20:55:50 +00005873#else
5874 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005875#endif
drh7ed97b92010-01-20 13:07:21 +00005876#ifdef SQLITE_TEST
5877 /* simulate multiple hosts by creating unique hostid file paths */
5878 if( sqlite3_hostid_num != 0){
5879 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5880 }
5881#endif
5882
5883 return SQLITE_OK;
5884}
5885
5886/* The conch file contains the header, host id and lock file path
5887 */
5888#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5889#define PROXY_HEADERLEN 1 /* conch file header length */
5890#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5891#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5892
5893/*
5894** Takes an open conch file, copies the contents to a new path and then moves
5895** it back. The newly created file's file descriptor is assigned to the
5896** conch file structure and finally the original conch file descriptor is
5897** closed. Returns zero if successful.
5898*/
5899static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5900 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5901 unixFile *conchFile = pCtx->conchFile;
5902 char tPath[MAXPATHLEN];
5903 char buf[PROXY_MAXCONCHLEN];
5904 char *cPath = pCtx->conchFilePath;
5905 size_t readLen = 0;
5906 size_t pathLen = 0;
5907 char errmsg[64] = "";
5908 int fd = -1;
5909 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005910 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005911
5912 /* create a new path by replace the trailing '-conch' with '-break' */
5913 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5914 if( pathLen>MAXPATHLEN || pathLen<6 ||
5915 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005916 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005917 goto end_breaklock;
5918 }
5919 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005920 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005921 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005922 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005923 goto end_breaklock;
5924 }
5925 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005926 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5927 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005928 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005929 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005930 goto end_breaklock;
5931 }
drhe562be52011-03-02 18:01:10 +00005932 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005933 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005934 goto end_breaklock;
5935 }
5936 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005937 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005938 goto end_breaklock;
5939 }
5940 rc = 0;
5941 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005942 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005943 conchFile->h = fd;
5944 conchFile->openFlags = O_RDWR | O_CREAT;
5945
5946end_breaklock:
5947 if( rc ){
5948 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005949 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005950 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005951 }
5952 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5953 }
5954 return rc;
5955}
5956
5957/* Take the requested lock on the conch file and break a stale lock if the
5958** host id matches.
5959*/
5960static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5961 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5962 unixFile *conchFile = pCtx->conchFile;
5963 int rc = SQLITE_OK;
5964 int nTries = 0;
5965 struct timespec conchModTime;
5966
drh3d4435b2011-08-26 20:55:50 +00005967 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00005968 do {
5969 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5970 nTries ++;
5971 if( rc==SQLITE_BUSY ){
5972 /* If the lock failed (busy):
5973 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5974 * 2nd try: fail if the mod time changed or host id is different, wait
5975 * 10 sec and try again
5976 * 3rd try: break the lock unless the mod time has changed.
5977 */
5978 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005979 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005980 pFile->lastErrno = errno;
5981 return SQLITE_IOERR_LOCK;
5982 }
5983
5984 if( nTries==1 ){
5985 conchModTime = buf.st_mtimespec;
5986 usleep(500000); /* wait 0.5 sec and try the lock again*/
5987 continue;
5988 }
5989
5990 assert( nTries>1 );
5991 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5992 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5993 return SQLITE_BUSY;
5994 }
5995
5996 if( nTries==2 ){
5997 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005998 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005999 if( len<0 ){
6000 pFile->lastErrno = errno;
6001 return SQLITE_IOERR_LOCK;
6002 }
6003 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6004 /* don't break the lock if the host id doesn't match */
6005 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6006 return SQLITE_BUSY;
6007 }
6008 }else{
6009 /* don't break the lock on short read or a version mismatch */
6010 return SQLITE_BUSY;
6011 }
6012 usleep(10000000); /* wait 10 sec and try the lock again */
6013 continue;
6014 }
6015
6016 assert( nTries==3 );
6017 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6018 rc = SQLITE_OK;
6019 if( lockType==EXCLUSIVE_LOCK ){
6020 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6021 }
6022 if( !rc ){
6023 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6024 }
6025 }
6026 }
6027 } while( rc==SQLITE_BUSY && nTries<3 );
6028
6029 return rc;
6030}
6031
6032/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006033** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6034** lockPath means that the lockPath in the conch file will be used if the
6035** host IDs match, or a new lock path will be generated automatically
6036** and written to the conch file.
6037*/
6038static int proxyTakeConch(unixFile *pFile){
6039 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6040
drh7ed97b92010-01-20 13:07:21 +00006041 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006042 return SQLITE_OK;
6043 }else{
6044 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006045 uuid_t myHostID;
6046 int pError = 0;
6047 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006048 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006049 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006050 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006051 int createConch = 0;
6052 int hostIdMatch = 0;
6053 int readLen = 0;
6054 int tryOldLockPath = 0;
6055 int forceNewLockPath = 0;
6056
drh308c2a52010-05-14 11:30:18 +00006057 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6058 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006059
drh7ed97b92010-01-20 13:07:21 +00006060 rc = proxyGetHostID(myHostID, &pError);
6061 if( (rc&0xff)==SQLITE_IOERR ){
6062 pFile->lastErrno = pError;
6063 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006064 }
drh7ed97b92010-01-20 13:07:21 +00006065 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006066 if( rc!=SQLITE_OK ){
6067 goto end_takeconch;
6068 }
drh7ed97b92010-01-20 13:07:21 +00006069 /* read the existing conch file */
6070 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6071 if( readLen<0 ){
6072 /* I/O error: lastErrno set by seekAndRead */
6073 pFile->lastErrno = conchFile->lastErrno;
6074 rc = SQLITE_IOERR_READ;
6075 goto end_takeconch;
6076 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6077 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6078 /* a short read or version format mismatch means we need to create a new
6079 ** conch file.
6080 */
6081 createConch = 1;
6082 }
6083 /* if the host id matches and the lock path already exists in the conch
6084 ** we'll try to use the path there, if we can't open that path, we'll
6085 ** retry with a new auto-generated path
6086 */
6087 do { /* in case we need to try again for an :auto: named lock file */
6088
6089 if( !createConch && !forceNewLockPath ){
6090 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6091 PROXY_HOSTIDLEN);
6092 /* if the conch has data compare the contents */
6093 if( !pCtx->lockProxyPath ){
6094 /* for auto-named local lock file, just check the host ID and we'll
6095 ** use the local lock file path that's already in there
6096 */
6097 if( hostIdMatch ){
6098 size_t pathLen = (readLen - PROXY_PATHINDEX);
6099
6100 if( pathLen>=MAXPATHLEN ){
6101 pathLen=MAXPATHLEN-1;
6102 }
6103 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6104 lockPath[pathLen] = 0;
6105 tempLockPath = lockPath;
6106 tryOldLockPath = 1;
6107 /* create a copy of the lock path if the conch is taken */
6108 goto end_takeconch;
6109 }
6110 }else if( hostIdMatch
6111 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6112 readLen-PROXY_PATHINDEX)
6113 ){
6114 /* conch host and lock path match */
6115 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006116 }
drh7ed97b92010-01-20 13:07:21 +00006117 }
6118
6119 /* if the conch isn't writable and doesn't match, we can't take it */
6120 if( (conchFile->openFlags&O_RDWR) == 0 ){
6121 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006122 goto end_takeconch;
6123 }
drh7ed97b92010-01-20 13:07:21 +00006124
6125 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006126 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006127 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6128 tempLockPath = lockPath;
6129 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006130 }
drh7ed97b92010-01-20 13:07:21 +00006131
6132 /* update conch with host and path (this will fail if other process
6133 ** has a shared lock already), if the host id matches, use the big
6134 ** stick.
drh715ff302008-12-03 22:32:44 +00006135 */
drh7ed97b92010-01-20 13:07:21 +00006136 futimes(conchFile->h, NULL);
6137 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006138 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006139 /* We are trying for an exclusive lock but another thread in this
6140 ** same process is still holding a shared lock. */
6141 rc = SQLITE_BUSY;
6142 } else {
6143 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006144 }
drh715ff302008-12-03 22:32:44 +00006145 }else{
drh7ed97b92010-01-20 13:07:21 +00006146 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006147 }
drh7ed97b92010-01-20 13:07:21 +00006148 if( rc==SQLITE_OK ){
6149 char writeBuffer[PROXY_MAXCONCHLEN];
6150 int writeSize = 0;
6151
6152 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6153 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6154 if( pCtx->lockProxyPath!=NULL ){
6155 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6156 }else{
6157 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6158 }
6159 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006160 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006161 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6162 fsync(conchFile->h);
6163 /* If we created a new conch file (not just updated the contents of a
6164 ** valid conch file), try to match the permissions of the database
6165 */
6166 if( rc==SQLITE_OK && createConch ){
6167 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006168 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006169 if( err==0 ){
6170 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6171 S_IROTH|S_IWOTH);
6172 /* try to match the database file R/W permissions, ignore failure */
6173#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006174 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006175#else
drhff812312011-02-23 13:33:46 +00006176 do{
drhe562be52011-03-02 18:01:10 +00006177 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006178 }while( rc==(-1) && errno==EINTR );
6179 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006180 int code = errno;
6181 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6182 cmode, code, strerror(code));
6183 } else {
6184 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6185 }
6186 }else{
6187 int code = errno;
6188 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6189 err, code, strerror(code));
6190#endif
6191 }
drh715ff302008-12-03 22:32:44 +00006192 }
6193 }
drh7ed97b92010-01-20 13:07:21 +00006194 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6195
6196 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006197 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006198 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006199 int fd;
drh7ed97b92010-01-20 13:07:21 +00006200 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006201 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006202 }
6203 pFile->h = -1;
drh3d4435b2011-08-26 20:55:50 +00006204 fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006205 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006206 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006207 if( fd>=0 ){
6208 pFile->h = fd;
6209 }else{
drh9978c972010-02-23 17:36:32 +00006210 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006211 during locking */
6212 }
6213 }
6214 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6215 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6216 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6217 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6218 /* we couldn't create the proxy lock file with the old lock file path
6219 ** so try again via auto-naming
6220 */
6221 forceNewLockPath = 1;
6222 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006223 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006224 }
6225 }
6226 if( rc==SQLITE_OK ){
6227 /* Need to make a copy of path if we extracted the value
6228 ** from the conch file or the path was allocated on the stack
6229 */
6230 if( tempLockPath ){
6231 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6232 if( !pCtx->lockProxyPath ){
6233 rc = SQLITE_NOMEM;
6234 }
6235 }
6236 }
6237 if( rc==SQLITE_OK ){
6238 pCtx->conchHeld = 1;
6239
6240 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6241 afpLockingContext *afpCtx;
6242 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6243 afpCtx->dbPath = pCtx->lockProxyPath;
6244 }
6245 } else {
6246 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6247 }
drh308c2a52010-05-14 11:30:18 +00006248 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6249 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006250 return rc;
drh308c2a52010-05-14 11:30:18 +00006251 } while (1); /* in case we need to retry the :auto: lock file -
6252 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006253 }
6254}
6255
6256/*
6257** If pFile holds a lock on a conch file, then release that lock.
6258*/
6259static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006260 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006261 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6262 unixFile *conchFile; /* Name of the conch file */
6263
6264 pCtx = (proxyLockingContext *)pFile->lockingContext;
6265 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006266 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006267 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006268 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006269 if( pCtx->conchHeld>0 ){
6270 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6271 }
drh715ff302008-12-03 22:32:44 +00006272 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006273 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6274 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006275 return rc;
6276}
6277
6278/*
6279** Given the name of a database file, compute the name of its conch file.
6280** Store the conch filename in memory obtained from sqlite3_malloc().
6281** Make *pConchPath point to the new name. Return SQLITE_OK on success
6282** or SQLITE_NOMEM if unable to obtain memory.
6283**
6284** The caller is responsible for ensuring that the allocated memory
6285** space is eventually freed.
6286**
6287** *pConchPath is set to NULL if a memory allocation error occurs.
6288*/
6289static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6290 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006291 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006292 char *conchPath; /* buffer in which to construct conch name */
6293
6294 /* Allocate space for the conch filename and initialize the name to
6295 ** the name of the original database file. */
6296 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6297 if( conchPath==0 ){
6298 return SQLITE_NOMEM;
6299 }
6300 memcpy(conchPath, dbPath, len+1);
6301
6302 /* now insert a "." before the last / character */
6303 for( i=(len-1); i>=0; i-- ){
6304 if( conchPath[i]=='/' ){
6305 i++;
6306 break;
6307 }
6308 }
6309 conchPath[i]='.';
6310 while ( i<len ){
6311 conchPath[i+1]=dbPath[i];
6312 i++;
6313 }
6314
6315 /* append the "-conch" suffix to the file */
6316 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006317 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006318
6319 return SQLITE_OK;
6320}
6321
6322
6323/* Takes a fully configured proxy locking-style unix file and switches
6324** the local lock file path
6325*/
6326static int switchLockProxyPath(unixFile *pFile, const char *path) {
6327 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6328 char *oldPath = pCtx->lockProxyPath;
6329 int rc = SQLITE_OK;
6330
drh308c2a52010-05-14 11:30:18 +00006331 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006332 return SQLITE_BUSY;
6333 }
6334
6335 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6336 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6337 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6338 return SQLITE_OK;
6339 }else{
6340 unixFile *lockProxy = pCtx->lockProxy;
6341 pCtx->lockProxy=NULL;
6342 pCtx->conchHeld = 0;
6343 if( lockProxy!=NULL ){
6344 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6345 if( rc ) return rc;
6346 sqlite3_free(lockProxy);
6347 }
6348 sqlite3_free(oldPath);
6349 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6350 }
6351
6352 return rc;
6353}
6354
6355/*
6356** pFile is a file that has been opened by a prior xOpen call. dbPath
6357** is a string buffer at least MAXPATHLEN+1 characters in size.
6358**
6359** This routine find the filename associated with pFile and writes it
6360** int dbPath.
6361*/
6362static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006363#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006364 if( pFile->pMethod == &afpIoMethods ){
6365 /* afp style keeps a reference to the db path in the filePath field
6366 ** of the struct */
drhea678832008-12-10 19:26:22 +00006367 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006368 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6369 } else
drh715ff302008-12-03 22:32:44 +00006370#endif
6371 if( pFile->pMethod == &dotlockIoMethods ){
6372 /* dot lock style uses the locking context to store the dot lock
6373 ** file path */
6374 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6375 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6376 }else{
6377 /* all other styles use the locking context to store the db file path */
6378 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006379 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006380 }
6381 return SQLITE_OK;
6382}
6383
6384/*
6385** Takes an already filled in unix file and alters it so all file locking
6386** will be performed on the local proxy lock file. The following fields
6387** are preserved in the locking context so that they can be restored and
6388** the unix structure properly cleaned up at close time:
6389** ->lockingContext
6390** ->pMethod
6391*/
6392static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6393 proxyLockingContext *pCtx;
6394 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6395 char *lockPath=NULL;
6396 int rc = SQLITE_OK;
6397
drh308c2a52010-05-14 11:30:18 +00006398 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006399 return SQLITE_BUSY;
6400 }
6401 proxyGetDbPathForUnixFile(pFile, dbPath);
6402 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6403 lockPath=NULL;
6404 }else{
6405 lockPath=(char *)path;
6406 }
6407
drh308c2a52010-05-14 11:30:18 +00006408 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6409 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006410
6411 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6412 if( pCtx==0 ){
6413 return SQLITE_NOMEM;
6414 }
6415 memset(pCtx, 0, sizeof(*pCtx));
6416
6417 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6418 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006419 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6420 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6421 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6422 ** (c) the file system is read-only, then enable no-locking access.
6423 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6424 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6425 */
6426 struct statfs fsInfo;
6427 struct stat conchInfo;
6428 int goLockless = 0;
6429
drh99ab3b12011-03-02 15:09:07 +00006430 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006431 int err = errno;
6432 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6433 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6434 }
6435 }
6436 if( goLockless ){
6437 pCtx->conchHeld = -1; /* read only FS/ lockless */
6438 rc = SQLITE_OK;
6439 }
6440 }
drh715ff302008-12-03 22:32:44 +00006441 }
6442 if( rc==SQLITE_OK && lockPath ){
6443 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6444 }
6445
6446 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006447 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6448 if( pCtx->dbPath==NULL ){
6449 rc = SQLITE_NOMEM;
6450 }
6451 }
6452 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006453 /* all memory is allocated, proxys are created and assigned,
6454 ** switch the locking context and pMethod then return.
6455 */
drh715ff302008-12-03 22:32:44 +00006456 pCtx->oldLockingContext = pFile->lockingContext;
6457 pFile->lockingContext = pCtx;
6458 pCtx->pOldMethod = pFile->pMethod;
6459 pFile->pMethod = &proxyIoMethods;
6460 }else{
6461 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006462 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006463 sqlite3_free(pCtx->conchFile);
6464 }
drhd56b1212010-08-11 06:14:15 +00006465 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006466 sqlite3_free(pCtx->conchFilePath);
6467 sqlite3_free(pCtx);
6468 }
drh308c2a52010-05-14 11:30:18 +00006469 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6470 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006471 return rc;
6472}
6473
6474
6475/*
6476** This routine handles sqlite3_file_control() calls that are specific
6477** to proxy locking.
6478*/
6479static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6480 switch( op ){
6481 case SQLITE_GET_LOCKPROXYFILE: {
6482 unixFile *pFile = (unixFile*)id;
6483 if( pFile->pMethod == &proxyIoMethods ){
6484 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6485 proxyTakeConch(pFile);
6486 if( pCtx->lockProxyPath ){
6487 *(const char **)pArg = pCtx->lockProxyPath;
6488 }else{
6489 *(const char **)pArg = ":auto: (not held)";
6490 }
6491 } else {
6492 *(const char **)pArg = NULL;
6493 }
6494 return SQLITE_OK;
6495 }
6496 case SQLITE_SET_LOCKPROXYFILE: {
6497 unixFile *pFile = (unixFile*)id;
6498 int rc = SQLITE_OK;
6499 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6500 if( pArg==NULL || (const char *)pArg==0 ){
6501 if( isProxyStyle ){
6502 /* turn off proxy locking - not supported */
6503 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6504 }else{
6505 /* turn off proxy locking - already off - NOOP */
6506 rc = SQLITE_OK;
6507 }
6508 }else{
6509 const char *proxyPath = (const char *)pArg;
6510 if( isProxyStyle ){
6511 proxyLockingContext *pCtx =
6512 (proxyLockingContext*)pFile->lockingContext;
6513 if( !strcmp(pArg, ":auto:")
6514 || (pCtx->lockProxyPath &&
6515 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6516 ){
6517 rc = SQLITE_OK;
6518 }else{
6519 rc = switchLockProxyPath(pFile, proxyPath);
6520 }
6521 }else{
6522 /* turn on proxy file locking */
6523 rc = proxyTransformUnixFile(pFile, proxyPath);
6524 }
6525 }
6526 return rc;
6527 }
6528 default: {
6529 assert( 0 ); /* The call assures that only valid opcodes are sent */
6530 }
6531 }
6532 /*NOTREACHED*/
6533 return SQLITE_ERROR;
6534}
6535
6536/*
6537** Within this division (the proxying locking implementation) the procedures
6538** above this point are all utilities. The lock-related methods of the
6539** proxy-locking sqlite3_io_method object follow.
6540*/
6541
6542
6543/*
6544** This routine checks if there is a RESERVED lock held on the specified
6545** file by this or any other process. If such a lock is held, set *pResOut
6546** to a non-zero value otherwise *pResOut is set to zero. The return value
6547** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6548*/
6549static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6550 unixFile *pFile = (unixFile*)id;
6551 int rc = proxyTakeConch(pFile);
6552 if( rc==SQLITE_OK ){
6553 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006554 if( pCtx->conchHeld>0 ){
6555 unixFile *proxy = pCtx->lockProxy;
6556 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6557 }else{ /* conchHeld < 0 is lockless */
6558 pResOut=0;
6559 }
drh715ff302008-12-03 22:32:44 +00006560 }
6561 return rc;
6562}
6563
6564/*
drh308c2a52010-05-14 11:30:18 +00006565** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006566** of the following:
6567**
6568** (1) SHARED_LOCK
6569** (2) RESERVED_LOCK
6570** (3) PENDING_LOCK
6571** (4) EXCLUSIVE_LOCK
6572**
6573** Sometimes when requesting one lock state, additional lock states
6574** are inserted in between. The locking might fail on one of the later
6575** transitions leaving the lock state different from what it started but
6576** still short of its goal. The following chart shows the allowed
6577** transitions and the inserted intermediate states:
6578**
6579** UNLOCKED -> SHARED
6580** SHARED -> RESERVED
6581** SHARED -> (PENDING) -> EXCLUSIVE
6582** RESERVED -> (PENDING) -> EXCLUSIVE
6583** PENDING -> EXCLUSIVE
6584**
6585** This routine will only increase a lock. Use the sqlite3OsUnlock()
6586** routine to lower a locking level.
6587*/
drh308c2a52010-05-14 11:30:18 +00006588static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006589 unixFile *pFile = (unixFile*)id;
6590 int rc = proxyTakeConch(pFile);
6591 if( rc==SQLITE_OK ){
6592 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006593 if( pCtx->conchHeld>0 ){
6594 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006595 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6596 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006597 }else{
6598 /* conchHeld < 0 is lockless */
6599 }
drh715ff302008-12-03 22:32:44 +00006600 }
6601 return rc;
6602}
6603
6604
6605/*
drh308c2a52010-05-14 11:30:18 +00006606** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006607** must be either NO_LOCK or SHARED_LOCK.
6608**
6609** If the locking level of the file descriptor is already at or below
6610** the requested locking level, this routine is a no-op.
6611*/
drh308c2a52010-05-14 11:30:18 +00006612static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006613 unixFile *pFile = (unixFile*)id;
6614 int rc = proxyTakeConch(pFile);
6615 if( rc==SQLITE_OK ){
6616 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006617 if( pCtx->conchHeld>0 ){
6618 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006619 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6620 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006621 }else{
6622 /* conchHeld < 0 is lockless */
6623 }
drh715ff302008-12-03 22:32:44 +00006624 }
6625 return rc;
6626}
6627
6628/*
6629** Close a file that uses proxy locks.
6630*/
6631static int proxyClose(sqlite3_file *id) {
6632 if( id ){
6633 unixFile *pFile = (unixFile*)id;
6634 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6635 unixFile *lockProxy = pCtx->lockProxy;
6636 unixFile *conchFile = pCtx->conchFile;
6637 int rc = SQLITE_OK;
6638
6639 if( lockProxy ){
6640 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6641 if( rc ) return rc;
6642 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6643 if( rc ) return rc;
6644 sqlite3_free(lockProxy);
6645 pCtx->lockProxy = 0;
6646 }
6647 if( conchFile ){
6648 if( pCtx->conchHeld ){
6649 rc = proxyReleaseConch(pFile);
6650 if( rc ) return rc;
6651 }
6652 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6653 if( rc ) return rc;
6654 sqlite3_free(conchFile);
6655 }
drhd56b1212010-08-11 06:14:15 +00006656 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006657 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006658 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006659 /* restore the original locking context and pMethod then close it */
6660 pFile->lockingContext = pCtx->oldLockingContext;
6661 pFile->pMethod = pCtx->pOldMethod;
6662 sqlite3_free(pCtx);
6663 return pFile->pMethod->xClose(id);
6664 }
6665 return SQLITE_OK;
6666}
6667
6668
6669
drhd2cb50b2009-01-09 21:41:17 +00006670#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006671/*
6672** The proxy locking style is intended for use with AFP filesystems.
6673** And since AFP is only supported on MacOSX, the proxy locking is also
6674** restricted to MacOSX.
6675**
6676**
6677******************* End of the proxy lock implementation **********************
6678******************************************************************************/
6679
drh734c9862008-11-28 15:37:20 +00006680/*
danielk1977e339d652008-06-28 11:23:00 +00006681** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006682**
6683** This routine registers all VFS implementations for unix-like operating
6684** systems. This routine, and the sqlite3_os_end() routine that follows,
6685** should be the only routines in this file that are visible from other
6686** files.
drh6b9d6dd2008-12-03 19:34:47 +00006687**
6688** This routine is called once during SQLite initialization and by a
6689** single thread. The memory allocation and mutex subsystems have not
6690** necessarily been initialized when this routine is called, and so they
6691** should not be used.
drh153c62c2007-08-24 03:51:33 +00006692*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006693int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006694 /*
6695 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006696 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6697 ** to the "finder" function. (pAppData is a pointer to a pointer because
6698 ** silly C90 rules prohibit a void* from being cast to a function pointer
6699 ** and so we have to go through the intermediate pointer to avoid problems
6700 ** when compiling with -pedantic-errors on GCC.)
6701 **
6702 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006703 ** finder-function. The finder-function returns a pointer to the
6704 ** sqlite_io_methods object that implements the desired locking
6705 ** behaviors. See the division above that contains the IOMETHODS
6706 ** macro for addition information on finder-functions.
6707 **
6708 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6709 ** object. But the "autolockIoFinder" available on MacOSX does a little
6710 ** more than that; it looks at the filesystem type that hosts the
6711 ** database file and tries to choose an locking method appropriate for
6712 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006713 */
drh7708e972008-11-29 00:56:52 +00006714 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006715 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006716 sizeof(unixFile), /* szOsFile */ \
6717 MAX_PATHNAME, /* mxPathname */ \
6718 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006719 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006720 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006721 unixOpen, /* xOpen */ \
6722 unixDelete, /* xDelete */ \
6723 unixAccess, /* xAccess */ \
6724 unixFullPathname, /* xFullPathname */ \
6725 unixDlOpen, /* xDlOpen */ \
6726 unixDlError, /* xDlError */ \
6727 unixDlSym, /* xDlSym */ \
6728 unixDlClose, /* xDlClose */ \
6729 unixRandomness, /* xRandomness */ \
6730 unixSleep, /* xSleep */ \
6731 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006732 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006733 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006734 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006735 unixGetSystemCall, /* xGetSystemCall */ \
6736 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006737 }
6738
drh6b9d6dd2008-12-03 19:34:47 +00006739 /*
6740 ** All default VFSes for unix are contained in the following array.
6741 **
6742 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6743 ** by the SQLite core when the VFS is registered. So the following
6744 ** array cannot be const.
6745 */
danielk1977e339d652008-06-28 11:23:00 +00006746 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006747#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006748 UNIXVFS("unix", autolockIoFinder ),
6749#else
6750 UNIXVFS("unix", posixIoFinder ),
6751#endif
6752 UNIXVFS("unix-none", nolockIoFinder ),
6753 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006754 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006755#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006756 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006757#endif
6758#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006759 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006760#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006761 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006762#endif
chw78a13182009-04-07 05:35:03 +00006763#endif
drhd2cb50b2009-01-09 21:41:17 +00006764#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006765 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006766 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006767 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006768#endif
drh153c62c2007-08-24 03:51:33 +00006769 };
drh6b9d6dd2008-12-03 19:34:47 +00006770 unsigned int i; /* Loop counter */
6771
drh2aa5a002011-04-13 13:42:25 +00006772 /* Double-check that the aSyscall[] array has been constructed
6773 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh9ef6bc42011-11-04 02:24:02 +00006774 assert( ArraySize(aSyscall)==20 );
drh2aa5a002011-04-13 13:42:25 +00006775
drh6b9d6dd2008-12-03 19:34:47 +00006776 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006777 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006778 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006779 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006780 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006781}
danielk1977e339d652008-06-28 11:23:00 +00006782
6783/*
drh6b9d6dd2008-12-03 19:34:47 +00006784** Shutdown the operating system interface.
6785**
6786** Some operating systems might need to do some cleanup in this routine,
6787** to release dynamically allocated objects. But not on unix.
6788** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006789*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006790int sqlite3_os_end(void){
6791 return SQLITE_OK;
6792}
drhdce8bdb2007-08-16 13:01:44 +00006793
danielk197729bafea2008-06-26 10:41:19 +00006794#endif /* SQLITE_OS_UNIX */