blob: a23a76234be24ec99bf5bbc02195e9d3aa114568 [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
drhe562be52011-03-02 18:01:10 +0000410}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000411
412/*
413** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000414** "unix" VFSes. Return SQLITE_OK opon successfully updating the
415** system call pointer, or SQLITE_NOTFOUND if there is no configurable
416** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000417*/
418static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000419 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
420 const char *zName, /* Name of system call to override */
421 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000422){
drh58ad5802011-03-23 22:02:23 +0000423 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000424 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000425
426 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000427 if( zName==0 ){
428 /* If no zName is given, restore all system calls to their default
429 ** settings and return NULL
430 */
dan51438a72011-04-02 17:00:47 +0000431 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000432 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
433 if( aSyscall[i].pDefault ){
434 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000435 }
436 }
437 }else{
438 /* If zName is specified, operate on only the one system call
439 ** specified.
440 */
441 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
442 if( strcmp(zName, aSyscall[i].zName)==0 ){
443 if( aSyscall[i].pDefault==0 ){
444 aSyscall[i].pDefault = aSyscall[i].pCurrent;
445 }
drh1df30962011-03-02 19:06:42 +0000446 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000447 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
448 aSyscall[i].pCurrent = pNewFunc;
449 break;
450 }
451 }
452 }
453 return rc;
454}
455
drh1df30962011-03-02 19:06:42 +0000456/*
457** Return the value of a system call. Return NULL if zName is not a
458** recognized system call name. NULL is also returned if the system call
459** is currently undefined.
460*/
drh58ad5802011-03-23 22:02:23 +0000461static sqlite3_syscall_ptr unixGetSystemCall(
462 sqlite3_vfs *pNotUsed,
463 const char *zName
464){
465 unsigned int i;
466
467 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000468 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
469 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
470 }
471 return 0;
472}
473
474/*
475** Return the name of the first system call after zName. If zName==NULL
476** then return the name of the first system call. Return NULL if zName
477** is the last system call or if zName is not the name of a valid
478** system call.
479*/
480static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000481 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000482
483 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000484 if( zName ){
485 for(i=0; i<ArraySize(aSyscall)-1; i++){
486 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000487 }
488 }
dan0fd7d862011-03-29 10:04:23 +0000489 for(i++; i<ArraySize(aSyscall); i++){
490 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000491 }
492 return 0;
493}
494
drhad4f1e52011-03-04 15:43:57 +0000495/*
496** Retry open() calls that fail due to EINTR
497*/
498static int robust_open(const char *z, int f, int m){
499 int rc;
500 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
501 return rc;
502}
danielk197713adf8a2004-06-03 16:08:41 +0000503
drh107886a2008-11-21 22:21:50 +0000504/*
dan9359c7b2009-08-21 08:29:10 +0000505** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000506** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000507** vxworksFileId objects used by this file, all of which may be
508** shared by multiple threads.
509**
510** Function unixMutexHeld() is used to assert() that the global mutex
511** is held when required. This function is only used as part of assert()
512** statements. e.g.
513**
514** unixEnterMutex()
515** assert( unixMutexHeld() );
516** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000517*/
518static void unixEnterMutex(void){
519 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
520}
521static void unixLeaveMutex(void){
522 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
523}
dan9359c7b2009-08-21 08:29:10 +0000524#ifdef SQLITE_DEBUG
525static int unixMutexHeld(void) {
526 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
527}
528#endif
drh107886a2008-11-21 22:21:50 +0000529
drh734c9862008-11-28 15:37:20 +0000530
531#ifdef SQLITE_DEBUG
532/*
533** Helper function for printing out trace information from debugging
534** binaries. This returns the string represetation of the supplied
535** integer lock-type.
536*/
drh308c2a52010-05-14 11:30:18 +0000537static const char *azFileLock(int eFileLock){
538 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000539 case NO_LOCK: return "NONE";
540 case SHARED_LOCK: return "SHARED";
541 case RESERVED_LOCK: return "RESERVED";
542 case PENDING_LOCK: return "PENDING";
543 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000544 }
545 return "ERROR";
546}
547#endif
548
549#ifdef SQLITE_LOCK_TRACE
550/*
551** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000552**
drh734c9862008-11-28 15:37:20 +0000553** This routine is used for troubleshooting locks on multithreaded
554** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
555** command-line option on the compiler. This code is normally
556** turned off.
557*/
558static int lockTrace(int fd, int op, struct flock *p){
559 char *zOpName, *zType;
560 int s;
561 int savedErrno;
562 if( op==F_GETLK ){
563 zOpName = "GETLK";
564 }else if( op==F_SETLK ){
565 zOpName = "SETLK";
566 }else{
drh99ab3b12011-03-02 15:09:07 +0000567 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000568 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
569 return s;
570 }
571 if( p->l_type==F_RDLCK ){
572 zType = "RDLCK";
573 }else if( p->l_type==F_WRLCK ){
574 zType = "WRLCK";
575 }else if( p->l_type==F_UNLCK ){
576 zType = "UNLCK";
577 }else{
578 assert( 0 );
579 }
580 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000581 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000582 savedErrno = errno;
583 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
584 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
585 (int)p->l_pid, s);
586 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
587 struct flock l2;
588 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000589 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000590 if( l2.l_type==F_RDLCK ){
591 zType = "RDLCK";
592 }else if( l2.l_type==F_WRLCK ){
593 zType = "WRLCK";
594 }else if( l2.l_type==F_UNLCK ){
595 zType = "UNLCK";
596 }else{
597 assert( 0 );
598 }
599 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
600 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
601 }
602 errno = savedErrno;
603 return s;
604}
drh99ab3b12011-03-02 15:09:07 +0000605#undef osFcntl
606#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000607#endif /* SQLITE_LOCK_TRACE */
608
drhff812312011-02-23 13:33:46 +0000609/*
610** Retry ftruncate() calls that fail due to EINTR
611*/
drhff812312011-02-23 13:33:46 +0000612static int robust_ftruncate(int h, sqlite3_int64 sz){
613 int rc;
drh99ab3b12011-03-02 15:09:07 +0000614 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000615 return rc;
616}
drh734c9862008-11-28 15:37:20 +0000617
618/*
619** This routine translates a standard POSIX errno code into something
620** useful to the clients of the sqlite3 functions. Specifically, it is
621** intended to translate a variety of "try again" errors into SQLITE_BUSY
622** and a variety of "please close the file descriptor NOW" errors into
623** SQLITE_IOERR
624**
625** Errors during initialization of locks, or file system support for locks,
626** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
627*/
628static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
629 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000630#if 0
631 /* At one point this code was not commented out. In theory, this branch
632 ** should never be hit, as this function should only be called after
633 ** a locking-related function (i.e. fcntl()) has returned non-zero with
634 ** the value of errno as the first argument. Since a system call has failed,
635 ** errno should be non-zero.
636 **
637 ** Despite this, if errno really is zero, we still don't want to return
638 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
639 ** propagated back to the caller. Commenting this branch out means errno==0
640 ** will be handled by the "default:" case below.
641 */
drh734c9862008-11-28 15:37:20 +0000642 case 0:
643 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000644#endif
645
drh734c9862008-11-28 15:37:20 +0000646 case EAGAIN:
647 case ETIMEDOUT:
648 case EBUSY:
649 case EINTR:
650 case ENOLCK:
651 /* random NFS retry error, unless during file system support
652 * introspection, in which it actually means what it says */
653 return SQLITE_BUSY;
654
655 case EACCES:
656 /* EACCES is like EAGAIN during locking operations, but not any other time*/
657 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
658 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
659 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
660 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
661 return SQLITE_BUSY;
662 }
663 /* else fall through */
664 case EPERM:
665 return SQLITE_PERM;
666
danea83bc62011-04-01 11:56:32 +0000667 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
668 ** this module never makes such a call. And the code in SQLite itself
669 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
670 ** this case is also commented out. If the system does set errno to EDEADLK,
671 ** the default SQLITE_IOERR_XXX code will be returned. */
672#if 0
drh734c9862008-11-28 15:37:20 +0000673 case EDEADLK:
674 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000675#endif
drh734c9862008-11-28 15:37:20 +0000676
677#if EOPNOTSUPP!=ENOTSUP
678 case EOPNOTSUPP:
679 /* something went terribly awry, unless during file system support
680 * introspection, in which it actually means what it says */
681#endif
682#ifdef ENOTSUP
683 case ENOTSUP:
684 /* invalid fd, unless during file system support introspection, in which
685 * it actually means what it says */
686#endif
687 case EIO:
688 case EBADF:
689 case EINVAL:
690 case ENOTCONN:
691 case ENODEV:
692 case ENXIO:
693 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000694#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000695 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000696#endif
drh734c9862008-11-28 15:37:20 +0000697 case ENOSYS:
698 /* these should force the client to close the file and reconnect */
699
700 default:
701 return sqliteIOErr;
702 }
703}
704
705
706
707/******************************************************************************
708****************** Begin Unique File ID Utility Used By VxWorks ***************
709**
710** On most versions of unix, we can get a unique ID for a file by concatenating
711** the device number and the inode number. But this does not work on VxWorks.
712** On VxWorks, a unique file id must be based on the canonical filename.
713**
714** A pointer to an instance of the following structure can be used as a
715** unique file ID in VxWorks. Each instance of this structure contains
716** a copy of the canonical filename. There is also a reference count.
717** The structure is reclaimed when the number of pointers to it drops to
718** zero.
719**
720** There are never very many files open at one time and lookups are not
721** a performance-critical path, so it is sufficient to put these
722** structures on a linked list.
723*/
724struct vxworksFileId {
725 struct vxworksFileId *pNext; /* Next in a list of them all */
726 int nRef; /* Number of references to this one */
727 int nName; /* Length of the zCanonicalName[] string */
728 char *zCanonicalName; /* Canonical filename */
729};
730
731#if OS_VXWORKS
732/*
drh9b35ea62008-11-29 02:20:26 +0000733** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000734** variable:
735*/
736static struct vxworksFileId *vxworksFileList = 0;
737
738/*
739** Simplify a filename into its canonical form
740** by making the following changes:
741**
742** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000743** * convert /./ into just /
744** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000745**
746** Changes are made in-place. Return the new name length.
747**
748** The original filename is in z[0..n-1]. Return the number of
749** characters in the simplified name.
750*/
751static int vxworksSimplifyName(char *z, int n){
752 int i, j;
753 while( n>1 && z[n-1]=='/' ){ n--; }
754 for(i=j=0; i<n; i++){
755 if( z[i]=='/' ){
756 if( z[i+1]=='/' ) continue;
757 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
758 i += 1;
759 continue;
760 }
761 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
762 while( j>0 && z[j-1]!='/' ){ j--; }
763 if( j>0 ){ j--; }
764 i += 2;
765 continue;
766 }
767 }
768 z[j++] = z[i];
769 }
770 z[j] = 0;
771 return j;
772}
773
774/*
775** Find a unique file ID for the given absolute pathname. Return
776** a pointer to the vxworksFileId object. This pointer is the unique
777** file ID.
778**
779** The nRef field of the vxworksFileId object is incremented before
780** the object is returned. A new vxworksFileId object is created
781** and added to the global list if necessary.
782**
783** If a memory allocation error occurs, return NULL.
784*/
785static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
786 struct vxworksFileId *pNew; /* search key and new file ID */
787 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
788 int n; /* Length of zAbsoluteName string */
789
790 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000791 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000792 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
793 if( pNew==0 ) return 0;
794 pNew->zCanonicalName = (char*)&pNew[1];
795 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
796 n = vxworksSimplifyName(pNew->zCanonicalName, n);
797
798 /* Search for an existing entry that matching the canonical name.
799 ** If found, increment the reference count and return a pointer to
800 ** the existing file ID.
801 */
802 unixEnterMutex();
803 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
804 if( pCandidate->nName==n
805 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
806 ){
807 sqlite3_free(pNew);
808 pCandidate->nRef++;
809 unixLeaveMutex();
810 return pCandidate;
811 }
812 }
813
814 /* No match was found. We will make a new file ID */
815 pNew->nRef = 1;
816 pNew->nName = n;
817 pNew->pNext = vxworksFileList;
818 vxworksFileList = pNew;
819 unixLeaveMutex();
820 return pNew;
821}
822
823/*
824** Decrement the reference count on a vxworksFileId object. Free
825** the object when the reference count reaches zero.
826*/
827static void vxworksReleaseFileId(struct vxworksFileId *pId){
828 unixEnterMutex();
829 assert( pId->nRef>0 );
830 pId->nRef--;
831 if( pId->nRef==0 ){
832 struct vxworksFileId **pp;
833 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
834 assert( *pp==pId );
835 *pp = pId->pNext;
836 sqlite3_free(pId);
837 }
838 unixLeaveMutex();
839}
840#endif /* OS_VXWORKS */
841/*************** End of Unique File ID Utility Used By VxWorks ****************
842******************************************************************************/
843
844
845/******************************************************************************
846*************************** Posix Advisory Locking ****************************
847**
drh9b35ea62008-11-29 02:20:26 +0000848** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000849** section 6.5.2.2 lines 483 through 490 specify that when a process
850** sets or clears a lock, that operation overrides any prior locks set
851** by the same process. It does not explicitly say so, but this implies
852** that it overrides locks set by the same process using a different
853** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000854**
855** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000856** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
857**
858** Suppose ./file1 and ./file2 are really the same file (because
859** one is a hard or symbolic link to the other) then if you set
860** an exclusive lock on fd1, then try to get an exclusive lock
861** on fd2, it works. I would have expected the second lock to
862** fail since there was already a lock on the file due to fd1.
863** But not so. Since both locks came from the same process, the
864** second overrides the first, even though they were on different
865** file descriptors opened on different file names.
866**
drh734c9862008-11-28 15:37:20 +0000867** This means that we cannot use POSIX locks to synchronize file access
868** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000869** to synchronize access for threads in separate processes, but not
870** threads within the same process.
871**
872** To work around the problem, SQLite has to manage file locks internally
873** on its own. Whenever a new database is opened, we have to find the
874** specific inode of the database file (the inode is determined by the
875** st_dev and st_ino fields of the stat structure that fstat() fills in)
876** and check for locks already existing on that inode. When locks are
877** created or removed, we have to look at our own internal record of the
878** locks to see if another thread has previously set a lock on that same
879** inode.
880**
drh9b35ea62008-11-29 02:20:26 +0000881** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
882** For VxWorks, we have to use the alternative unique ID system based on
883** canonical filename and implemented in the previous division.)
884**
danielk1977ad94b582007-08-20 06:44:22 +0000885** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000886** descriptor. It is now a structure that holds the integer file
887** descriptor and a pointer to a structure that describes the internal
888** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000889** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000890** point to the same locking structure. The locking structure keeps
891** a reference count (so we will know when to delete it) and a "cnt"
892** field that tells us its internal lock status. cnt==0 means the
893** file is unlocked. cnt==-1 means the file has an exclusive lock.
894** cnt>0 means there are cnt shared locks on the file.
895**
896** Any attempt to lock or unlock a file first checks the locking
897** structure. The fcntl() system call is only invoked to set a
898** POSIX lock if the internal lock structure transitions between
899** a locked and an unlocked state.
900**
drh734c9862008-11-28 15:37:20 +0000901** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000902**
903** If you close a file descriptor that points to a file that has locks,
904** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000905** released. To work around this problem, each unixInodeInfo object
906** maintains a count of the number of pending locks on tha inode.
907** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000908** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000909** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000910** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000911** be closed and that list is walked (and cleared) when the last lock
912** clears.
913**
drh9b35ea62008-11-29 02:20:26 +0000914** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000915**
drh9b35ea62008-11-29 02:20:26 +0000916** Many older versions of linux use the LinuxThreads library which is
917** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000918** A cannot be modified or overridden by a different thread B.
919** Only thread A can modify the lock. Locking behavior is correct
920** if the appliation uses the newer Native Posix Thread Library (NPTL)
921** on linux - with NPTL a lock created by thread A can override locks
922** in thread B. But there is no way to know at compile-time which
923** threading library is being used. So there is no way to know at
924** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000925** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000926** current process.
drh5fdae772004-06-29 03:29:00 +0000927**
drh8af6c222010-05-14 12:43:01 +0000928** SQLite used to support LinuxThreads. But support for LinuxThreads
929** was dropped beginning with version 3.7.0. SQLite will still work with
930** LinuxThreads provided that (1) there is no more than one connection
931** per database file in the same process and (2) database connections
932** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000933*/
934
935/*
936** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000937** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000938*/
939struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000940 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000941#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000942 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000943#else
drh107886a2008-11-21 22:21:50 +0000944 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000945#endif
946};
947
948/*
drhbbd42a62004-05-22 17:41:58 +0000949** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000950** inode. Or, on LinuxThreads, there is one of these structures for
951** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000952**
danielk1977ad94b582007-08-20 06:44:22 +0000953** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000954** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000955** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000956*/
drh8af6c222010-05-14 12:43:01 +0000957struct unixInodeInfo {
958 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000959 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000960 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
961 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000962 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000963 unixShmNode *pShmNode; /* Shared memory associated with this inode */
964 int nLock; /* Number of outstanding file locks */
965 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
966 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
967 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000968#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000969 unsigned long long sharedByte; /* for AFP simulated shared lock */
970#endif
drh6c7d5c52008-11-21 20:32:33 +0000971#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000972 sem_t *pSem; /* Named POSIX semaphore */
973 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000974#endif
drhbbd42a62004-05-22 17:41:58 +0000975};
976
drhda0e7682008-07-30 15:27:54 +0000977/*
drh8af6c222010-05-14 12:43:01 +0000978** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000979*/
drhd91c68f2010-05-14 14:52:25 +0000980static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000981
drh5fdae772004-06-29 03:29:00 +0000982/*
dane18d4952011-02-21 11:46:24 +0000983**
984** This function - unixLogError_x(), is only ever called via the macro
985** unixLogError().
986**
987** It is invoked after an error occurs in an OS function and errno has been
988** set. It logs a message using sqlite3_log() containing the current value of
989** errno and, if possible, the human-readable equivalent from strerror() or
990** strerror_r().
991**
992** The first argument passed to the macro should be the error code that
993** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
994** The two subsequent arguments should be the name of the OS function that
995** failed (e.g. "unlink", "open") and the the associated file-system path,
996** if any.
997*/
drh0e9365c2011-03-02 02:08:13 +0000998#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
999static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001000 int errcode, /* SQLite error code */
1001 const char *zFunc, /* Name of OS function that failed */
1002 const char *zPath, /* File path associated with error */
1003 int iLine /* Source line number where error occurred */
1004){
1005 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001006 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001007
1008 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1009 ** the strerror() function to obtain the human-readable error message
1010 ** equivalent to errno. Otherwise, use strerror_r().
1011 */
1012#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1013 char aErr[80];
1014 memset(aErr, 0, sizeof(aErr));
1015 zErr = aErr;
1016
1017 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1018 ** assume that the system provides the the GNU version of strerror_r() that
1019 ** returns a pointer to a buffer containing the error message. That pointer
1020 ** may point to aErr[], or it may point to some static storage somewhere.
1021 ** Otherwise, assume that the system provides the POSIX version of
1022 ** strerror_r(), which always writes an error message into aErr[].
1023 **
1024 ** If the code incorrectly assumes that it is the POSIX version that is
1025 ** available, the error message will often be an empty string. Not a
1026 ** huge problem. Incorrectly concluding that the GNU version is available
1027 ** could lead to a segfault though.
1028 */
1029#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1030 zErr =
1031# endif
drh0e9365c2011-03-02 02:08:13 +00001032 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001033
1034#elif SQLITE_THREADSAFE
1035 /* This is a threadsafe build, but strerror_r() is not available. */
1036 zErr = "";
1037#else
1038 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001039 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001040#endif
1041
1042 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001043 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001044 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001045 "os_unix.c:%d: (%d) %s(%s) - %s",
1046 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001047 );
1048
1049 return errcode;
1050}
1051
drh0e9365c2011-03-02 02:08:13 +00001052/*
1053** Close a file descriptor.
1054**
1055** We assume that close() almost always works, since it is only in a
1056** very sick application or on a very sick platform that it might fail.
1057** If it does fail, simply leak the file descriptor, but do log the
1058** error.
1059**
1060** Note that it is not safe to retry close() after EINTR since the
1061** file descriptor might have already been reused by another thread.
1062** So we don't even try to recover from an EINTR. Just log the error
1063** and move on.
1064*/
1065static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001066 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001067 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1068 pFile ? pFile->zPath : 0, lineno);
1069 }
1070}
dane18d4952011-02-21 11:46:24 +00001071
1072/*
danb0ac3e32010-06-16 10:55:42 +00001073** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001074*/
drh0e9365c2011-03-02 02:08:13 +00001075static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001076 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001077 UnixUnusedFd *p;
1078 UnixUnusedFd *pNext;
1079 for(p=pInode->pUnused; p; p=pNext){
1080 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001081 robust_close(pFile, p->fd, __LINE__);
1082 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001083 }
drh0e9365c2011-03-02 02:08:13 +00001084 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001085}
1086
1087/*
drh8af6c222010-05-14 12:43:01 +00001088** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001089**
1090** The mutex entered using the unixEnterMutex() function must be held
1091** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001092*/
danb0ac3e32010-06-16 10:55:42 +00001093static void releaseInodeInfo(unixFile *pFile){
1094 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001095 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001096 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001097 pInode->nRef--;
1098 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001099 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001100 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001101 if( pInode->pPrev ){
1102 assert( pInode->pPrev->pNext==pInode );
1103 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001104 }else{
drh8af6c222010-05-14 12:43:01 +00001105 assert( inodeList==pInode );
1106 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001107 }
drh8af6c222010-05-14 12:43:01 +00001108 if( pInode->pNext ){
1109 assert( pInode->pNext->pPrev==pInode );
1110 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001111 }
drh8af6c222010-05-14 12:43:01 +00001112 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001113 }
drhbbd42a62004-05-22 17:41:58 +00001114 }
1115}
1116
1117/*
drh8af6c222010-05-14 12:43:01 +00001118** Given a file descriptor, locate the unixInodeInfo object that
1119** describes that file descriptor. Create a new one if necessary. The
1120** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001121**
dan9359c7b2009-08-21 08:29:10 +00001122** The mutex entered using the unixEnterMutex() function must be held
1123** when this function is called.
1124**
drh6c7d5c52008-11-21 20:32:33 +00001125** Return an appropriate error code.
1126*/
drh8af6c222010-05-14 12:43:01 +00001127static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001128 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001129 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001130){
1131 int rc; /* System call return code */
1132 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001133 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1134 struct stat statbuf; /* Low-level file information */
1135 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001136
dan9359c7b2009-08-21 08:29:10 +00001137 assert( unixMutexHeld() );
1138
drh6c7d5c52008-11-21 20:32:33 +00001139 /* Get low-level information about the file that we can used to
1140 ** create a unique name for the file.
1141 */
1142 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001143 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001144 if( rc!=0 ){
1145 pFile->lastErrno = errno;
1146#ifdef EOVERFLOW
1147 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1148#endif
1149 return SQLITE_IOERR;
1150 }
1151
drheb0d74f2009-02-03 15:27:02 +00001152#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001153 /* On OS X on an msdos filesystem, the inode number is reported
1154 ** incorrectly for zero-size files. See ticket #3260. To work
1155 ** around this problem (we consider it a bug in OS X, not SQLite)
1156 ** we always increase the file size to 1 by writing a single byte
1157 ** prior to accessing the inode number. The one byte written is
1158 ** an ASCII 'S' character which also happens to be the first byte
1159 ** in the header of every SQLite database. In this way, if there
1160 ** is a race condition such that another thread has already populated
1161 ** the first page of the database, no damage is done.
1162 */
drh7ed97b92010-01-20 13:07:21 +00001163 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001164 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001165 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001166 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001167 return SQLITE_IOERR;
1168 }
drh99ab3b12011-03-02 15:09:07 +00001169 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001170 if( rc!=0 ){
1171 pFile->lastErrno = errno;
1172 return SQLITE_IOERR;
1173 }
1174 }
drheb0d74f2009-02-03 15:27:02 +00001175#endif
drh6c7d5c52008-11-21 20:32:33 +00001176
drh8af6c222010-05-14 12:43:01 +00001177 memset(&fileId, 0, sizeof(fileId));
1178 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001179#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001180 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001181#else
drh8af6c222010-05-14 12:43:01 +00001182 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001183#endif
drh8af6c222010-05-14 12:43:01 +00001184 pInode = inodeList;
1185 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1186 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001187 }
drh8af6c222010-05-14 12:43:01 +00001188 if( pInode==0 ){
1189 pInode = sqlite3_malloc( sizeof(*pInode) );
1190 if( pInode==0 ){
1191 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001192 }
drh8af6c222010-05-14 12:43:01 +00001193 memset(pInode, 0, sizeof(*pInode));
1194 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1195 pInode->nRef = 1;
1196 pInode->pNext = inodeList;
1197 pInode->pPrev = 0;
1198 if( inodeList ) inodeList->pPrev = pInode;
1199 inodeList = pInode;
1200 }else{
1201 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001202 }
drh8af6c222010-05-14 12:43:01 +00001203 *ppInode = pInode;
1204 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001205}
drh6c7d5c52008-11-21 20:32:33 +00001206
aswift5b1a2562008-08-22 00:22:35 +00001207
1208/*
danielk197713adf8a2004-06-03 16:08:41 +00001209** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001210** file by this or any other process. If such a lock is held, set *pResOut
1211** to a non-zero value otherwise *pResOut is set to zero. The return value
1212** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001213*/
danielk1977861f7452008-06-05 11:39:11 +00001214static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001215 int rc = SQLITE_OK;
1216 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001217 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001218
danielk1977861f7452008-06-05 11:39:11 +00001219 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1220
drh054889e2005-11-30 03:20:31 +00001221 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001222 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001223
1224 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001225 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001226 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001227 }
1228
drh2ac3ee92004-06-07 16:27:46 +00001229 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001230 */
danielk197709480a92009-02-09 05:32:32 +00001231#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001232 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001233 struct flock lock;
1234 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001235 lock.l_start = RESERVED_BYTE;
1236 lock.l_len = 1;
1237 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001238 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1239 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1240 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001241 } else if( lock.l_type!=F_UNLCK ){
1242 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001243 }
1244 }
danielk197709480a92009-02-09 05:32:32 +00001245#endif
danielk197713adf8a2004-06-03 16:08:41 +00001246
drh6c7d5c52008-11-21 20:32:33 +00001247 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001248 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001249
aswift5b1a2562008-08-22 00:22:35 +00001250 *pResOut = reserved;
1251 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001252}
1253
1254/*
drha7e61d82011-03-12 17:02:57 +00001255** Attempt to set a system-lock on the file pFile. The lock is
1256** described by pLock.
1257**
drh77197112011-03-15 19:08:48 +00001258** If the pFile was opened read/write from unix-excl, then the only lock
1259** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001260** the first time any lock is attempted. All subsequent system locking
1261** operations become no-ops. Locking operations still happen internally,
1262** in order to coordinate access between separate database connections
1263** within this process, but all of that is handled in memory and the
1264** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001265**
1266** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1267** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1268** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001269**
1270** Zero is returned if the call completes successfully, or -1 if a call
1271** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001272*/
1273static int unixFileLock(unixFile *pFile, struct flock *pLock){
1274 int rc;
drh3cb93392011-03-12 18:10:44 +00001275 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001276 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001277 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001278 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1279 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1280 ){
drh3cb93392011-03-12 18:10:44 +00001281 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001282 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001283 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001284 lock.l_whence = SEEK_SET;
1285 lock.l_start = SHARED_FIRST;
1286 lock.l_len = SHARED_SIZE;
1287 lock.l_type = F_WRLCK;
1288 rc = osFcntl(pFile->h, F_SETLK, &lock);
1289 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001290 pInode->bProcessLock = 1;
1291 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001292 }else{
1293 rc = 0;
1294 }
1295 }else{
1296 rc = osFcntl(pFile->h, F_SETLK, pLock);
1297 }
1298 return rc;
1299}
1300
1301/*
drh308c2a52010-05-14 11:30:18 +00001302** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001303** of the following:
1304**
drh2ac3ee92004-06-07 16:27:46 +00001305** (1) SHARED_LOCK
1306** (2) RESERVED_LOCK
1307** (3) PENDING_LOCK
1308** (4) EXCLUSIVE_LOCK
1309**
drhb3e04342004-06-08 00:47:47 +00001310** Sometimes when requesting one lock state, additional lock states
1311** are inserted in between. The locking might fail on one of the later
1312** transitions leaving the lock state different from what it started but
1313** still short of its goal. The following chart shows the allowed
1314** transitions and the inserted intermediate states:
1315**
1316** UNLOCKED -> SHARED
1317** SHARED -> RESERVED
1318** SHARED -> (PENDING) -> EXCLUSIVE
1319** RESERVED -> (PENDING) -> EXCLUSIVE
1320** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001321**
drha6abd042004-06-09 17:37:22 +00001322** This routine will only increase a lock. Use the sqlite3OsUnlock()
1323** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001324*/
drh308c2a52010-05-14 11:30:18 +00001325static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001326 /* The following describes the implementation of the various locks and
1327 ** lock transitions in terms of the POSIX advisory shared and exclusive
1328 ** lock primitives (called read-locks and write-locks below, to avoid
1329 ** confusion with SQLite lock names). The algorithms are complicated
1330 ** slightly in order to be compatible with windows systems simultaneously
1331 ** accessing the same database file, in case that is ever required.
1332 **
1333 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1334 ** byte', each single bytes at well known offsets, and the 'shared byte
1335 ** range', a range of 510 bytes at a well known offset.
1336 **
1337 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1338 ** byte'. If this is successful, a random byte from the 'shared byte
1339 ** range' is read-locked and the lock on the 'pending byte' released.
1340 **
danielk197790ba3bd2004-06-25 08:32:25 +00001341 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1342 ** A RESERVED lock is implemented by grabbing a write-lock on the
1343 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001344 **
1345 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001346 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1347 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1348 ** obtained, but existing SHARED locks are allowed to persist. A process
1349 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1350 ** This property is used by the algorithm for rolling back a journal file
1351 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001352 **
danielk197790ba3bd2004-06-25 08:32:25 +00001353 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1354 ** implemented by obtaining a write-lock on the entire 'shared byte
1355 ** range'. Since all other locks require a read-lock on one of the bytes
1356 ** within this range, this ensures that no other locks are held on the
1357 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001358 **
1359 ** The reason a single byte cannot be used instead of the 'shared byte
1360 ** range' is that some versions of windows do not support read-locks. By
1361 ** locking a random byte from a range, concurrent SHARED locks may exist
1362 ** even if the locking primitive used is always a write-lock.
1363 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001364 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001365 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001366 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001367 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001368 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001369
drh054889e2005-11-30 03:20:31 +00001370 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001371 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1372 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001373 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001374
1375 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001376 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001377 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001378 */
drh308c2a52010-05-14 11:30:18 +00001379 if( pFile->eFileLock>=eFileLock ){
1380 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1381 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001382 return SQLITE_OK;
1383 }
1384
drh0c2694b2009-09-03 16:23:44 +00001385 /* Make sure the locking sequence is correct.
1386 ** (1) We never move from unlocked to anything higher than shared lock.
1387 ** (2) SQLite never explicitly requests a pendig lock.
1388 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001389 */
drh308c2a52010-05-14 11:30:18 +00001390 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1391 assert( eFileLock!=PENDING_LOCK );
1392 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001393
drh8af6c222010-05-14 12:43:01 +00001394 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001395 */
drh6c7d5c52008-11-21 20:32:33 +00001396 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001397 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001398
danielk1977ad94b582007-08-20 06:44:22 +00001399 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001400 ** handle that precludes the requested lock, return BUSY.
1401 */
drh8af6c222010-05-14 12:43:01 +00001402 if( (pFile->eFileLock!=pInode->eFileLock &&
1403 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001404 ){
1405 rc = SQLITE_BUSY;
1406 goto end_lock;
1407 }
1408
1409 /* If a SHARED lock is requested, and some thread using this PID already
1410 ** has a SHARED or RESERVED lock, then increment reference counts and
1411 ** return SQLITE_OK.
1412 */
drh308c2a52010-05-14 11:30:18 +00001413 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001414 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001415 assert( eFileLock==SHARED_LOCK );
1416 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001417 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001418 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001419 pInode->nShared++;
1420 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001421 goto end_lock;
1422 }
1423
danielk19779a1d0ab2004-06-01 14:09:28 +00001424
drh3cde3bb2004-06-12 02:17:14 +00001425 /* A PENDING lock is needed before acquiring a SHARED lock and before
1426 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1427 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001428 */
drh0c2694b2009-09-03 16:23:44 +00001429 lock.l_len = 1L;
1430 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001431 if( eFileLock==SHARED_LOCK
1432 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001433 ){
drh308c2a52010-05-14 11:30:18 +00001434 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001435 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001436 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001437 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001438 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001439 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001440 pFile->lastErrno = tErrno;
1441 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001442 goto end_lock;
1443 }
drh3cde3bb2004-06-12 02:17:14 +00001444 }
1445
1446
1447 /* If control gets to this point, then actually go ahead and make
1448 ** operating system calls for the specified lock.
1449 */
drh308c2a52010-05-14 11:30:18 +00001450 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001451 assert( pInode->nShared==0 );
1452 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001453 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001454
drh2ac3ee92004-06-07 16:27:46 +00001455 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001456 lock.l_start = SHARED_FIRST;
1457 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001458 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001459 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001460 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001461 }
dan661d71a2011-03-30 19:08:03 +00001462
drh2ac3ee92004-06-07 16:27:46 +00001463 /* Drop the temporary PENDING lock */
1464 lock.l_start = PENDING_BYTE;
1465 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001466 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001467 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1468 /* This could happen with a network mount */
1469 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001470 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001471 }
dan661d71a2011-03-30 19:08:03 +00001472
1473 if( rc ){
1474 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001475 pFile->lastErrno = tErrno;
1476 }
dan661d71a2011-03-30 19:08:03 +00001477 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001478 }else{
drh308c2a52010-05-14 11:30:18 +00001479 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001480 pInode->nLock++;
1481 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001482 }
drh8af6c222010-05-14 12:43:01 +00001483 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001484 /* We are trying for an exclusive lock but another thread in this
1485 ** same process is still holding a shared lock. */
1486 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001487 }else{
drh3cde3bb2004-06-12 02:17:14 +00001488 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001489 ** assumed that there is a SHARED or greater lock on the file
1490 ** already.
1491 */
drh308c2a52010-05-14 11:30:18 +00001492 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001493 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001494
1495 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1496 if( eFileLock==RESERVED_LOCK ){
1497 lock.l_start = RESERVED_BYTE;
1498 lock.l_len = 1L;
1499 }else{
1500 lock.l_start = SHARED_FIRST;
1501 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001502 }
dan661d71a2011-03-30 19:08:03 +00001503
1504 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001505 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001506 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001507 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001508 pFile->lastErrno = tErrno;
1509 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001510 }
drhbbd42a62004-05-22 17:41:58 +00001511 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001512
drh8f941bc2009-01-14 23:03:40 +00001513
1514#ifndef NDEBUG
1515 /* Set up the transaction-counter change checking flags when
1516 ** transitioning from a SHARED to a RESERVED lock. The change
1517 ** from SHARED to RESERVED marks the beginning of a normal
1518 ** write operation (not a hot journal rollback).
1519 */
1520 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001521 && pFile->eFileLock<=SHARED_LOCK
1522 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001523 ){
1524 pFile->transCntrChng = 0;
1525 pFile->dbUpdate = 0;
1526 pFile->inNormalWrite = 1;
1527 }
1528#endif
1529
1530
danielk1977ecb2a962004-06-02 06:30:16 +00001531 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001532 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001533 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001534 }else if( eFileLock==EXCLUSIVE_LOCK ){
1535 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001536 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001537 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001538
1539end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001540 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001541 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1542 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001543 return rc;
1544}
1545
1546/*
dan08da86a2009-08-21 17:18:03 +00001547** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001548** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001549*/
1550static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001551 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001552 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001553 p->pNext = pInode->pUnused;
1554 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001555 pFile->h = -1;
1556 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001557}
1558
1559/*
drh308c2a52010-05-14 11:30:18 +00001560** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001561** must be either NO_LOCK or SHARED_LOCK.
1562**
1563** If the locking level of the file descriptor is already at or below
1564** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001565**
1566** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1567** the byte range is divided into 2 parts and the first part is unlocked then
1568** set to a read lock, then the other part is simply unlocked. This works
1569** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1570** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001571*/
drha7e61d82011-03-12 17:02:57 +00001572static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001573 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001574 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001575 struct flock lock;
1576 int rc = SQLITE_OK;
1577 int h;
drha6abd042004-06-09 17:37:22 +00001578
drh054889e2005-11-30 03:20:31 +00001579 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001580 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001581 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001582 getpid()));
drha6abd042004-06-09 17:37:22 +00001583
drh308c2a52010-05-14 11:30:18 +00001584 assert( eFileLock<=SHARED_LOCK );
1585 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001586 return SQLITE_OK;
1587 }
drh6c7d5c52008-11-21 20:32:33 +00001588 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001589 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001590 pInode = pFile->pInode;
1591 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001592 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001593 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001594 SimulateIOErrorBenign(1);
1595 SimulateIOError( h=(-1) )
1596 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001597
1598#ifndef NDEBUG
1599 /* When reducing a lock such that other processes can start
1600 ** reading the database file again, make sure that the
1601 ** transaction counter was updated if any part of the database
1602 ** file changed. If the transaction counter is not updated,
1603 ** other connections to the same file might not realize that
1604 ** the file has changed and hence might not know to flush their
1605 ** cache. The use of a stale cache can lead to database corruption.
1606 */
dan7c246102010-04-12 19:00:29 +00001607#if 0
drh8f941bc2009-01-14 23:03:40 +00001608 assert( pFile->inNormalWrite==0
1609 || pFile->dbUpdate==0
1610 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001611#endif
drh8f941bc2009-01-14 23:03:40 +00001612 pFile->inNormalWrite = 0;
1613#endif
1614
drh7ed97b92010-01-20 13:07:21 +00001615 /* downgrading to a shared lock on NFS involves clearing the write lock
1616 ** before establishing the readlock - to avoid a race condition we downgrade
1617 ** the lock in 2 blocks, so that part of the range will be covered by a
1618 ** write lock until the rest is covered by a read lock:
1619 ** 1: [WWWWW]
1620 ** 2: [....W]
1621 ** 3: [RRRRW]
1622 ** 4: [RRRR.]
1623 */
drh308c2a52010-05-14 11:30:18 +00001624 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001625
1626#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001627 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001628 assert( handleNFSUnlock==0 );
1629#endif
1630#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001631 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001632 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001633 off_t divSize = SHARED_SIZE - 1;
1634
1635 lock.l_type = F_UNLCK;
1636 lock.l_whence = SEEK_SET;
1637 lock.l_start = SHARED_FIRST;
1638 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001639 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001640 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001641 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001642 if( IS_LOCK_ERROR(rc) ){
1643 pFile->lastErrno = tErrno;
1644 }
1645 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001646 }
drh7ed97b92010-01-20 13:07:21 +00001647 lock.l_type = F_RDLCK;
1648 lock.l_whence = SEEK_SET;
1649 lock.l_start = SHARED_FIRST;
1650 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001651 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001652 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001653 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1654 if( IS_LOCK_ERROR(rc) ){
1655 pFile->lastErrno = tErrno;
1656 }
1657 goto end_unlock;
1658 }
1659 lock.l_type = F_UNLCK;
1660 lock.l_whence = SEEK_SET;
1661 lock.l_start = SHARED_FIRST+divSize;
1662 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001663 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001664 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001665 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001666 if( IS_LOCK_ERROR(rc) ){
1667 pFile->lastErrno = tErrno;
1668 }
1669 goto end_unlock;
1670 }
drh30f776f2011-02-25 03:25:07 +00001671 }else
1672#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1673 {
drh7ed97b92010-01-20 13:07:21 +00001674 lock.l_type = F_RDLCK;
1675 lock.l_whence = SEEK_SET;
1676 lock.l_start = SHARED_FIRST;
1677 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001678 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001679 /* In theory, the call to unixFileLock() cannot fail because another
1680 ** process is holding an incompatible lock. If it does, this
1681 ** indicates that the other process is not following the locking
1682 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1683 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1684 ** an assert to fail). */
1685 rc = SQLITE_IOERR_RDLOCK;
1686 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001687 goto end_unlock;
1688 }
drh9c105bb2004-10-02 20:38:28 +00001689 }
1690 }
drhbbd42a62004-05-22 17:41:58 +00001691 lock.l_type = F_UNLCK;
1692 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001693 lock.l_start = PENDING_BYTE;
1694 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001695 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001696 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001697 }else{
danea83bc62011-04-01 11:56:32 +00001698 rc = SQLITE_IOERR_UNLOCK;
1699 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001700 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001701 }
drhbbd42a62004-05-22 17:41:58 +00001702 }
drh308c2a52010-05-14 11:30:18 +00001703 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001704 /* Decrement the shared lock counter. Release the lock using an
1705 ** OS call only when all threads in this same process have released
1706 ** the lock.
1707 */
drh8af6c222010-05-14 12:43:01 +00001708 pInode->nShared--;
1709 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001710 lock.l_type = F_UNLCK;
1711 lock.l_whence = SEEK_SET;
1712 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001713 SimulateIOErrorBenign(1);
1714 SimulateIOError( h=(-1) )
1715 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001716 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001717 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001718 }else{
danea83bc62011-04-01 11:56:32 +00001719 rc = SQLITE_IOERR_UNLOCK;
1720 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001721 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001722 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001723 }
drha6abd042004-06-09 17:37:22 +00001724 }
1725
drhbbd42a62004-05-22 17:41:58 +00001726 /* Decrement the count of locks against this same file. When the
1727 ** count reaches zero, close any other file descriptors whose close
1728 ** was deferred because of outstanding locks.
1729 */
drh8af6c222010-05-14 12:43:01 +00001730 pInode->nLock--;
1731 assert( pInode->nLock>=0 );
1732 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001733 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001734 }
1735 }
aswift5b1a2562008-08-22 00:22:35 +00001736
1737end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001738 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001739 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001740 return rc;
drhbbd42a62004-05-22 17:41:58 +00001741}
1742
1743/*
drh308c2a52010-05-14 11:30:18 +00001744** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001745** must be either NO_LOCK or SHARED_LOCK.
1746**
1747** If the locking level of the file descriptor is already at or below
1748** the requested locking level, this routine is a no-op.
1749*/
drh308c2a52010-05-14 11:30:18 +00001750static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001751 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001752}
1753
1754/*
danielk1977e339d652008-06-28 11:23:00 +00001755** This function performs the parts of the "close file" operation
1756** common to all locking schemes. It closes the directory and file
1757** handles, if they are valid, and sets all fields of the unixFile
1758** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001759**
1760** It is *not* necessary to hold the mutex when this routine is called,
1761** even on VxWorks. A mutex will be acquired on VxWorks by the
1762** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001763*/
1764static int closeUnixFile(sqlite3_file *id){
1765 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001766 if( pFile->h>=0 ){
1767 robust_close(pFile, pFile->h, __LINE__);
1768 pFile->h = -1;
1769 }
1770#if OS_VXWORKS
1771 if( pFile->pId ){
1772 if( pFile->isDelete ){
drh036ac7f2011-08-08 23:18:05 +00001773 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001774 }
1775 vxworksReleaseFileId(pFile->pId);
1776 pFile->pId = 0;
1777 }
1778#endif
1779 OSTRACE(("CLOSE %-3d\n", pFile->h));
1780 OpenCounter(-1);
1781 sqlite3_free(pFile->pUnused);
1782 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001783 return SQLITE_OK;
1784}
1785
1786/*
danielk1977e3026632004-06-22 11:29:02 +00001787** Close a file.
1788*/
danielk197762079062007-08-15 17:08:46 +00001789static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001790 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001791 unixFile *pFile = (unixFile *)id;
1792 unixUnlock(id, NO_LOCK);
1793 unixEnterMutex();
1794
1795 /* unixFile.pInode is always valid here. Otherwise, a different close
1796 ** routine (e.g. nolockClose()) would be called instead.
1797 */
1798 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1799 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1800 /* If there are outstanding locks, do not actually close the file just
1801 ** yet because that would clear those locks. Instead, add the file
1802 ** descriptor to pInode->pUnused list. It will be automatically closed
1803 ** when the last lock is cleared.
1804 */
1805 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001806 }
dan661d71a2011-03-30 19:08:03 +00001807 releaseInodeInfo(pFile);
1808 rc = closeUnixFile(id);
1809 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001810 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001811}
1812
drh734c9862008-11-28 15:37:20 +00001813/************** End of the posix advisory lock implementation *****************
1814******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001815
drh734c9862008-11-28 15:37:20 +00001816/******************************************************************************
1817****************************** No-op Locking **********************************
1818**
1819** Of the various locking implementations available, this is by far the
1820** simplest: locking is ignored. No attempt is made to lock the database
1821** file for reading or writing.
1822**
1823** This locking mode is appropriate for use on read-only databases
1824** (ex: databases that are burned into CD-ROM, for example.) It can
1825** also be used if the application employs some external mechanism to
1826** prevent simultaneous access of the same database by two or more
1827** database connections. But there is a serious risk of database
1828** corruption if this locking mode is used in situations where multiple
1829** database connections are accessing the same database file at the same
1830** time and one or more of those connections are writing.
1831*/
drhbfe66312006-10-03 17:40:40 +00001832
drh734c9862008-11-28 15:37:20 +00001833static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1834 UNUSED_PARAMETER(NotUsed);
1835 *pResOut = 0;
1836 return SQLITE_OK;
1837}
drh734c9862008-11-28 15:37:20 +00001838static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1839 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1840 return SQLITE_OK;
1841}
drh734c9862008-11-28 15:37:20 +00001842static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1843 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1844 return SQLITE_OK;
1845}
1846
1847/*
drh9b35ea62008-11-29 02:20:26 +00001848** Close the file.
drh734c9862008-11-28 15:37:20 +00001849*/
1850static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001851 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001852}
1853
1854/******************* End of the no-op lock implementation *********************
1855******************************************************************************/
1856
1857/******************************************************************************
1858************************* Begin dot-file Locking ******************************
1859**
drh0c2694b2009-09-03 16:23:44 +00001860** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001861** files in order to control access to the database. This works on just
1862** about every filesystem imaginable. But there are serious downsides:
1863**
1864** (1) There is zero concurrency. A single reader blocks all other
1865** connections from reading or writing the database.
1866**
1867** (2) An application crash or power loss can leave stale lock files
1868** sitting around that need to be cleared manually.
1869**
1870** Nevertheless, a dotlock is an appropriate locking mode for use if no
1871** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001872**
1873** Dotfile locking works by creating a file in the same directory as the
1874** database and with the same name but with a ".lock" extension added.
1875** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1876** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001877*/
1878
1879/*
1880** The file suffix added to the data base filename in order to create the
1881** lock file.
1882*/
1883#define DOTLOCK_SUFFIX ".lock"
1884
drh7708e972008-11-29 00:56:52 +00001885/*
1886** This routine checks if there is a RESERVED lock held on the specified
1887** file by this or any other process. If such a lock is held, set *pResOut
1888** to a non-zero value otherwise *pResOut is set to zero. The return value
1889** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1890**
1891** In dotfile locking, either a lock exists or it does not. So in this
1892** variation of CheckReservedLock(), *pResOut is set to true if any lock
1893** is held on the file and false if the file is unlocked.
1894*/
drh734c9862008-11-28 15:37:20 +00001895static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1896 int rc = SQLITE_OK;
1897 int reserved = 0;
1898 unixFile *pFile = (unixFile*)id;
1899
1900 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1901
1902 assert( pFile );
1903
1904 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001905 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001906 /* Either this connection or some other connection in the same process
1907 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001908 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001909 }else{
1910 /* The lock is held if and only if the lockfile exists */
1911 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001912 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001913 }
drh308c2a52010-05-14 11:30:18 +00001914 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001915 *pResOut = reserved;
1916 return rc;
1917}
1918
drh7708e972008-11-29 00:56:52 +00001919/*
drh308c2a52010-05-14 11:30:18 +00001920** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001921** of the following:
1922**
1923** (1) SHARED_LOCK
1924** (2) RESERVED_LOCK
1925** (3) PENDING_LOCK
1926** (4) EXCLUSIVE_LOCK
1927**
1928** Sometimes when requesting one lock state, additional lock states
1929** are inserted in between. The locking might fail on one of the later
1930** transitions leaving the lock state different from what it started but
1931** still short of its goal. The following chart shows the allowed
1932** transitions and the inserted intermediate states:
1933**
1934** UNLOCKED -> SHARED
1935** SHARED -> RESERVED
1936** SHARED -> (PENDING) -> EXCLUSIVE
1937** RESERVED -> (PENDING) -> EXCLUSIVE
1938** PENDING -> EXCLUSIVE
1939**
1940** This routine will only increase a lock. Use the sqlite3OsUnlock()
1941** routine to lower a locking level.
1942**
1943** With dotfile locking, we really only support state (4): EXCLUSIVE.
1944** But we track the other locking levels internally.
1945*/
drh308c2a52010-05-14 11:30:18 +00001946static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001947 unixFile *pFile = (unixFile*)id;
1948 int fd;
1949 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001950 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001951
drh7708e972008-11-29 00:56:52 +00001952
1953 /* If we have any lock, then the lock file already exists. All we have
1954 ** to do is adjust our internal record of the lock level.
1955 */
drh308c2a52010-05-14 11:30:18 +00001956 if( pFile->eFileLock > NO_LOCK ){
1957 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001958 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001959#ifdef HAVE_UTIME
1960 utime(zLockFile, NULL);
1961#else
drh734c9862008-11-28 15:37:20 +00001962 utimes(zLockFile, NULL);
1963#endif
drh7708e972008-11-29 00:56:52 +00001964 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001965 }
1966
1967 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001968 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001969 if( fd<0 ){
1970 /* failed to open/create the file, someone else may have stolen the lock */
1971 int tErrno = errno;
1972 if( EEXIST == tErrno ){
1973 rc = SQLITE_BUSY;
1974 } else {
1975 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1976 if( IS_LOCK_ERROR(rc) ){
1977 pFile->lastErrno = tErrno;
1978 }
1979 }
drh7708e972008-11-29 00:56:52 +00001980 return rc;
drh734c9862008-11-28 15:37:20 +00001981 }
drh0e9365c2011-03-02 02:08:13 +00001982 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001983
1984 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001985 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001986 return rc;
1987}
1988
drh7708e972008-11-29 00:56:52 +00001989/*
drh308c2a52010-05-14 11:30:18 +00001990** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001991** must be either NO_LOCK or SHARED_LOCK.
1992**
1993** If the locking level of the file descriptor is already at or below
1994** the requested locking level, this routine is a no-op.
1995**
1996** When the locking level reaches NO_LOCK, delete the lock file.
1997*/
drh308c2a52010-05-14 11:30:18 +00001998static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001999 unixFile *pFile = (unixFile*)id;
2000 char *zLockFile = (char *)pFile->lockingContext;
2001
2002 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002003 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2004 pFile->eFileLock, getpid()));
2005 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002006
2007 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002008 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002009 return SQLITE_OK;
2010 }
drh7708e972008-11-29 00:56:52 +00002011
2012 /* To downgrade to shared, simply update our internal notion of the
2013 ** lock state. No need to mess with the file on disk.
2014 */
drh308c2a52010-05-14 11:30:18 +00002015 if( eFileLock==SHARED_LOCK ){
2016 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002017 return SQLITE_OK;
2018 }
2019
drh7708e972008-11-29 00:56:52 +00002020 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002021 assert( eFileLock==NO_LOCK );
drh036ac7f2011-08-08 23:18:05 +00002022 if( osUnlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00002023 int rc = 0;
2024 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002025 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002026 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002027 }
2028 if( IS_LOCK_ERROR(rc) ){
2029 pFile->lastErrno = tErrno;
2030 }
2031 return rc;
2032 }
drh308c2a52010-05-14 11:30:18 +00002033 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002034 return SQLITE_OK;
2035}
2036
2037/*
drh9b35ea62008-11-29 02:20:26 +00002038** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002039*/
2040static int dotlockClose(sqlite3_file *id) {
2041 int rc;
2042 if( id ){
2043 unixFile *pFile = (unixFile*)id;
2044 dotlockUnlock(id, NO_LOCK);
2045 sqlite3_free(pFile->lockingContext);
2046 }
drh734c9862008-11-28 15:37:20 +00002047 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002048 return rc;
2049}
2050/****************** End of the dot-file lock implementation *******************
2051******************************************************************************/
2052
2053/******************************************************************************
2054************************** Begin flock Locking ********************************
2055**
2056** Use the flock() system call to do file locking.
2057**
drh6b9d6dd2008-12-03 19:34:47 +00002058** flock() locking is like dot-file locking in that the various
2059** fine-grain locking levels supported by SQLite are collapsed into
2060** a single exclusive lock. In other words, SHARED, RESERVED, and
2061** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2062** still works when you do this, but concurrency is reduced since
2063** only a single process can be reading the database at a time.
2064**
drh734c9862008-11-28 15:37:20 +00002065** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2066** compiling for VXWORKS.
2067*/
2068#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002069
drh6b9d6dd2008-12-03 19:34:47 +00002070/*
drhff812312011-02-23 13:33:46 +00002071** Retry flock() calls that fail with EINTR
2072*/
2073#ifdef EINTR
2074static int robust_flock(int fd, int op){
2075 int rc;
2076 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2077 return rc;
2078}
2079#else
drh5c819272011-02-23 14:00:12 +00002080# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002081#endif
2082
2083
2084/*
drh6b9d6dd2008-12-03 19:34:47 +00002085** This routine checks if there is a RESERVED lock held on the specified
2086** file by this or any other process. If such a lock is held, set *pResOut
2087** to a non-zero value otherwise *pResOut is set to zero. The return value
2088** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2089*/
drh734c9862008-11-28 15:37:20 +00002090static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2091 int rc = SQLITE_OK;
2092 int reserved = 0;
2093 unixFile *pFile = (unixFile*)id;
2094
2095 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2096
2097 assert( pFile );
2098
2099 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002100 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002101 reserved = 1;
2102 }
2103
2104 /* Otherwise see if some other process holds it. */
2105 if( !reserved ){
2106 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002107 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002108 if( !lrc ){
2109 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002110 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002111 if ( lrc ) {
2112 int tErrno = errno;
2113 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002114 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002115 if( IS_LOCK_ERROR(lrc) ){
2116 pFile->lastErrno = tErrno;
2117 rc = lrc;
2118 }
2119 }
2120 } else {
2121 int tErrno = errno;
2122 reserved = 1;
2123 /* someone else might have it reserved */
2124 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2125 if( IS_LOCK_ERROR(lrc) ){
2126 pFile->lastErrno = tErrno;
2127 rc = lrc;
2128 }
2129 }
2130 }
drh308c2a52010-05-14 11:30:18 +00002131 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002132
2133#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2134 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2135 rc = SQLITE_OK;
2136 reserved=1;
2137 }
2138#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2139 *pResOut = reserved;
2140 return rc;
2141}
2142
drh6b9d6dd2008-12-03 19:34:47 +00002143/*
drh308c2a52010-05-14 11:30:18 +00002144** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002145** of the following:
2146**
2147** (1) SHARED_LOCK
2148** (2) RESERVED_LOCK
2149** (3) PENDING_LOCK
2150** (4) EXCLUSIVE_LOCK
2151**
2152** Sometimes when requesting one lock state, additional lock states
2153** are inserted in between. The locking might fail on one of the later
2154** transitions leaving the lock state different from what it started but
2155** still short of its goal. The following chart shows the allowed
2156** transitions and the inserted intermediate states:
2157**
2158** UNLOCKED -> SHARED
2159** SHARED -> RESERVED
2160** SHARED -> (PENDING) -> EXCLUSIVE
2161** RESERVED -> (PENDING) -> EXCLUSIVE
2162** PENDING -> EXCLUSIVE
2163**
2164** flock() only really support EXCLUSIVE locks. We track intermediate
2165** lock states in the sqlite3_file structure, but all locks SHARED or
2166** above are really EXCLUSIVE locks and exclude all other processes from
2167** access the file.
2168**
2169** This routine will only increase a lock. Use the sqlite3OsUnlock()
2170** routine to lower a locking level.
2171*/
drh308c2a52010-05-14 11:30:18 +00002172static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002173 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002174 unixFile *pFile = (unixFile*)id;
2175
2176 assert( pFile );
2177
2178 /* if we already have a lock, it is exclusive.
2179 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002180 if (pFile->eFileLock > NO_LOCK) {
2181 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002182 return SQLITE_OK;
2183 }
2184
2185 /* grab an exclusive lock */
2186
drhff812312011-02-23 13:33:46 +00002187 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002188 int tErrno = errno;
2189 /* didn't get, must be busy */
2190 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2191 if( IS_LOCK_ERROR(rc) ){
2192 pFile->lastErrno = tErrno;
2193 }
2194 } else {
2195 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002196 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002197 }
drh308c2a52010-05-14 11:30:18 +00002198 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2199 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002200#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2201 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2202 rc = SQLITE_BUSY;
2203 }
2204#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2205 return rc;
2206}
2207
drh6b9d6dd2008-12-03 19:34:47 +00002208
2209/*
drh308c2a52010-05-14 11:30:18 +00002210** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002211** must be either NO_LOCK or SHARED_LOCK.
2212**
2213** If the locking level of the file descriptor is already at or below
2214** the requested locking level, this routine is a no-op.
2215*/
drh308c2a52010-05-14 11:30:18 +00002216static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002217 unixFile *pFile = (unixFile*)id;
2218
2219 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002220 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2221 pFile->eFileLock, getpid()));
2222 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002223
2224 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002225 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002226 return SQLITE_OK;
2227 }
2228
2229 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002230 if (eFileLock==SHARED_LOCK) {
2231 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002232 return SQLITE_OK;
2233 }
2234
2235 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002236 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002237#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002238 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002239#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002240 return SQLITE_IOERR_UNLOCK;
2241 }else{
drh308c2a52010-05-14 11:30:18 +00002242 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002243 return SQLITE_OK;
2244 }
2245}
2246
2247/*
2248** Close a file.
2249*/
2250static int flockClose(sqlite3_file *id) {
2251 if( id ){
2252 flockUnlock(id, NO_LOCK);
2253 }
2254 return closeUnixFile(id);
2255}
2256
2257#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2258
2259/******************* End of the flock lock implementation *********************
2260******************************************************************************/
2261
2262/******************************************************************************
2263************************ Begin Named Semaphore Locking ************************
2264**
2265** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002266**
2267** Semaphore locking is like dot-lock and flock in that it really only
2268** supports EXCLUSIVE locking. Only a single process can read or write
2269** the database file at a time. This reduces potential concurrency, but
2270** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002271*/
2272#if OS_VXWORKS
2273
drh6b9d6dd2008-12-03 19:34:47 +00002274/*
2275** This routine checks if there is a RESERVED lock held on the specified
2276** file by this or any other process. If such a lock is held, set *pResOut
2277** to a non-zero value otherwise *pResOut is set to zero. The return value
2278** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2279*/
drh734c9862008-11-28 15:37:20 +00002280static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2281 int rc = SQLITE_OK;
2282 int reserved = 0;
2283 unixFile *pFile = (unixFile*)id;
2284
2285 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2286
2287 assert( pFile );
2288
2289 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002290 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002291 reserved = 1;
2292 }
2293
2294 /* Otherwise see if some other process holds it. */
2295 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002296 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002297 struct stat statBuf;
2298
2299 if( sem_trywait(pSem)==-1 ){
2300 int tErrno = errno;
2301 if( EAGAIN != tErrno ){
2302 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2303 pFile->lastErrno = tErrno;
2304 } else {
2305 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002306 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002307 }
2308 }else{
2309 /* we could have it if we want it */
2310 sem_post(pSem);
2311 }
2312 }
drh308c2a52010-05-14 11:30:18 +00002313 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002314
2315 *pResOut = reserved;
2316 return rc;
2317}
2318
drh6b9d6dd2008-12-03 19:34:47 +00002319/*
drh308c2a52010-05-14 11:30:18 +00002320** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002321** of the following:
2322**
2323** (1) SHARED_LOCK
2324** (2) RESERVED_LOCK
2325** (3) PENDING_LOCK
2326** (4) EXCLUSIVE_LOCK
2327**
2328** Sometimes when requesting one lock state, additional lock states
2329** are inserted in between. The locking might fail on one of the later
2330** transitions leaving the lock state different from what it started but
2331** still short of its goal. The following chart shows the allowed
2332** transitions and the inserted intermediate states:
2333**
2334** UNLOCKED -> SHARED
2335** SHARED -> RESERVED
2336** SHARED -> (PENDING) -> EXCLUSIVE
2337** RESERVED -> (PENDING) -> EXCLUSIVE
2338** PENDING -> EXCLUSIVE
2339**
2340** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2341** lock states in the sqlite3_file structure, but all locks SHARED or
2342** above are really EXCLUSIVE locks and exclude all other processes from
2343** access the file.
2344**
2345** This routine will only increase a lock. Use the sqlite3OsUnlock()
2346** routine to lower a locking level.
2347*/
drh308c2a52010-05-14 11:30:18 +00002348static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002349 unixFile *pFile = (unixFile*)id;
2350 int fd;
drh8af6c222010-05-14 12:43:01 +00002351 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002352 int rc = SQLITE_OK;
2353
2354 /* if we already have a lock, it is exclusive.
2355 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002356 if (pFile->eFileLock > NO_LOCK) {
2357 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002358 rc = SQLITE_OK;
2359 goto sem_end_lock;
2360 }
2361
2362 /* lock semaphore now but bail out when already locked. */
2363 if( sem_trywait(pSem)==-1 ){
2364 rc = SQLITE_BUSY;
2365 goto sem_end_lock;
2366 }
2367
2368 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002369 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002370
2371 sem_end_lock:
2372 return rc;
2373}
2374
drh6b9d6dd2008-12-03 19:34:47 +00002375/*
drh308c2a52010-05-14 11:30:18 +00002376** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002377** must be either NO_LOCK or SHARED_LOCK.
2378**
2379** If the locking level of the file descriptor is already at or below
2380** the requested locking level, this routine is a no-op.
2381*/
drh308c2a52010-05-14 11:30:18 +00002382static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002383 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002384 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002385
2386 assert( pFile );
2387 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002388 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2389 pFile->eFileLock, getpid()));
2390 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002391
2392 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002393 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002394 return SQLITE_OK;
2395 }
2396
2397 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002398 if (eFileLock==SHARED_LOCK) {
2399 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002400 return SQLITE_OK;
2401 }
2402
2403 /* no, really unlock. */
2404 if ( sem_post(pSem)==-1 ) {
2405 int rc, tErrno = errno;
2406 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2407 if( IS_LOCK_ERROR(rc) ){
2408 pFile->lastErrno = tErrno;
2409 }
2410 return rc;
2411 }
drh308c2a52010-05-14 11:30:18 +00002412 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002413 return SQLITE_OK;
2414}
2415
2416/*
2417 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002418 */
drh734c9862008-11-28 15:37:20 +00002419static int semClose(sqlite3_file *id) {
2420 if( id ){
2421 unixFile *pFile = (unixFile*)id;
2422 semUnlock(id, NO_LOCK);
2423 assert( pFile );
2424 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002425 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002426 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002427 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002428 }
2429 return SQLITE_OK;
2430}
2431
2432#endif /* OS_VXWORKS */
2433/*
2434** Named semaphore locking is only available on VxWorks.
2435**
2436*************** End of the named semaphore lock implementation ****************
2437******************************************************************************/
2438
2439
2440/******************************************************************************
2441*************************** Begin AFP Locking *********************************
2442**
2443** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2444** on Apple Macintosh computers - both OS9 and OSX.
2445**
2446** Third-party implementations of AFP are available. But this code here
2447** only works on OSX.
2448*/
2449
drhd2cb50b2009-01-09 21:41:17 +00002450#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002451/*
2452** The afpLockingContext structure contains all afp lock specific state
2453*/
drhbfe66312006-10-03 17:40:40 +00002454typedef struct afpLockingContext afpLockingContext;
2455struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002456 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002457 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002458};
2459
2460struct ByteRangeLockPB2
2461{
2462 unsigned long long offset; /* offset to first byte to lock */
2463 unsigned long long length; /* nbr of bytes to lock */
2464 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2465 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2466 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2467 int fd; /* file desc to assoc this lock with */
2468};
2469
drhfd131da2007-08-07 17:13:03 +00002470#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002471
drh6b9d6dd2008-12-03 19:34:47 +00002472/*
2473** This is a utility for setting or clearing a bit-range lock on an
2474** AFP filesystem.
2475**
2476** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2477*/
2478static int afpSetLock(
2479 const char *path, /* Name of the file to be locked or unlocked */
2480 unixFile *pFile, /* Open file descriptor on path */
2481 unsigned long long offset, /* First byte to be locked */
2482 unsigned long long length, /* Number of bytes to lock */
2483 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002484){
drh6b9d6dd2008-12-03 19:34:47 +00002485 struct ByteRangeLockPB2 pb;
2486 int err;
drhbfe66312006-10-03 17:40:40 +00002487
2488 pb.unLockFlag = setLockFlag ? 0 : 1;
2489 pb.startEndFlag = 0;
2490 pb.offset = offset;
2491 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002492 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002493
drh308c2a52010-05-14 11:30:18 +00002494 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002495 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002496 offset, length));
drhbfe66312006-10-03 17:40:40 +00002497 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2498 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002499 int rc;
2500 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002501 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2502 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002503#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2504 rc = SQLITE_BUSY;
2505#else
drh734c9862008-11-28 15:37:20 +00002506 rc = sqliteErrorFromPosixError(tErrno,
2507 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002508#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002509 if( IS_LOCK_ERROR(rc) ){
2510 pFile->lastErrno = tErrno;
2511 }
2512 return rc;
drhbfe66312006-10-03 17:40:40 +00002513 } else {
aswift5b1a2562008-08-22 00:22:35 +00002514 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002515 }
2516}
2517
drh6b9d6dd2008-12-03 19:34:47 +00002518/*
2519** This routine checks if there is a RESERVED lock held on the specified
2520** file by this or any other process. If such a lock is held, set *pResOut
2521** to a non-zero value otherwise *pResOut is set to zero. The return value
2522** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2523*/
danielk1977e339d652008-06-28 11:23:00 +00002524static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002525 int rc = SQLITE_OK;
2526 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002527 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002528 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002529
aswift5b1a2562008-08-22 00:22:35 +00002530 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2531
2532 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002533 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002534 if( context->reserved ){
2535 *pResOut = 1;
2536 return SQLITE_OK;
2537 }
drh8af6c222010-05-14 12:43:01 +00002538 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002539
2540 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002541 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002542 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002543 }
2544
2545 /* Otherwise see if some other process holds it.
2546 */
aswift5b1a2562008-08-22 00:22:35 +00002547 if( !reserved ){
2548 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002549 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002550 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002551 /* if we succeeded in taking the reserved lock, unlock it to restore
2552 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002553 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002554 } else {
2555 /* if we failed to get the lock then someone else must have it */
2556 reserved = 1;
2557 }
2558 if( IS_LOCK_ERROR(lrc) ){
2559 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002560 }
2561 }
drhbfe66312006-10-03 17:40:40 +00002562
drh7ed97b92010-01-20 13:07:21 +00002563 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002564 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002565
2566 *pResOut = reserved;
2567 return rc;
drhbfe66312006-10-03 17:40:40 +00002568}
2569
drh6b9d6dd2008-12-03 19:34:47 +00002570/*
drh308c2a52010-05-14 11:30:18 +00002571** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002572** of the following:
2573**
2574** (1) SHARED_LOCK
2575** (2) RESERVED_LOCK
2576** (3) PENDING_LOCK
2577** (4) EXCLUSIVE_LOCK
2578**
2579** Sometimes when requesting one lock state, additional lock states
2580** are inserted in between. The locking might fail on one of the later
2581** transitions leaving the lock state different from what it started but
2582** still short of its goal. The following chart shows the allowed
2583** transitions and the inserted intermediate states:
2584**
2585** UNLOCKED -> SHARED
2586** SHARED -> RESERVED
2587** SHARED -> (PENDING) -> EXCLUSIVE
2588** RESERVED -> (PENDING) -> EXCLUSIVE
2589** PENDING -> EXCLUSIVE
2590**
2591** This routine will only increase a lock. Use the sqlite3OsUnlock()
2592** routine to lower a locking level.
2593*/
drh308c2a52010-05-14 11:30:18 +00002594static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002595 int rc = SQLITE_OK;
2596 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002597 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002598 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002599
2600 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002601 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2602 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002603 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002604
drhbfe66312006-10-03 17:40:40 +00002605 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002606 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002607 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002608 */
drh308c2a52010-05-14 11:30:18 +00002609 if( pFile->eFileLock>=eFileLock ){
2610 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2611 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002612 return SQLITE_OK;
2613 }
2614
2615 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002616 ** (1) We never move from unlocked to anything higher than shared lock.
2617 ** (2) SQLite never explicitly requests a pendig lock.
2618 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002619 */
drh308c2a52010-05-14 11:30:18 +00002620 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2621 assert( eFileLock!=PENDING_LOCK );
2622 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002623
drh8af6c222010-05-14 12:43:01 +00002624 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002625 */
drh6c7d5c52008-11-21 20:32:33 +00002626 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002627 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002628
2629 /* If some thread using this PID has a lock via a different unixFile*
2630 ** handle that precludes the requested lock, return BUSY.
2631 */
drh8af6c222010-05-14 12:43:01 +00002632 if( (pFile->eFileLock!=pInode->eFileLock &&
2633 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002634 ){
2635 rc = SQLITE_BUSY;
2636 goto afp_end_lock;
2637 }
2638
2639 /* If a SHARED lock is requested, and some thread using this PID already
2640 ** has a SHARED or RESERVED lock, then increment reference counts and
2641 ** return SQLITE_OK.
2642 */
drh308c2a52010-05-14 11:30:18 +00002643 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002644 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002645 assert( eFileLock==SHARED_LOCK );
2646 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002647 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002648 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002649 pInode->nShared++;
2650 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002651 goto afp_end_lock;
2652 }
drhbfe66312006-10-03 17:40:40 +00002653
2654 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002655 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2656 ** be released.
2657 */
drh308c2a52010-05-14 11:30:18 +00002658 if( eFileLock==SHARED_LOCK
2659 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002660 ){
2661 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002662 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002663 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002664 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002665 goto afp_end_lock;
2666 }
2667 }
2668
2669 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002670 ** operating system calls for the specified lock.
2671 */
drh308c2a52010-05-14 11:30:18 +00002672 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002673 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002674 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002675
drh8af6c222010-05-14 12:43:01 +00002676 assert( pInode->nShared==0 );
2677 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002678
2679 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002680 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002681 /* note that the quality of the randomness doesn't matter that much */
2682 lk = random();
drh8af6c222010-05-14 12:43:01 +00002683 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002684 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002685 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002686 if( IS_LOCK_ERROR(lrc1) ){
2687 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002688 }
aswift5b1a2562008-08-22 00:22:35 +00002689 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002690 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002691
aswift5b1a2562008-08-22 00:22:35 +00002692 if( IS_LOCK_ERROR(lrc1) ) {
2693 pFile->lastErrno = lrc1Errno;
2694 rc = lrc1;
2695 goto afp_end_lock;
2696 } else if( IS_LOCK_ERROR(lrc2) ){
2697 rc = lrc2;
2698 goto afp_end_lock;
2699 } else if( lrc1 != SQLITE_OK ) {
2700 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002701 } else {
drh308c2a52010-05-14 11:30:18 +00002702 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002703 pInode->nLock++;
2704 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002705 }
drh8af6c222010-05-14 12:43:01 +00002706 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002707 /* We are trying for an exclusive lock but another thread in this
2708 ** same process is still holding a shared lock. */
2709 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002710 }else{
2711 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2712 ** assumed that there is a SHARED or greater lock on the file
2713 ** already.
2714 */
2715 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002716 assert( 0!=pFile->eFileLock );
2717 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002718 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002719 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002720 if( !failed ){
2721 context->reserved = 1;
2722 }
drhbfe66312006-10-03 17:40:40 +00002723 }
drh308c2a52010-05-14 11:30:18 +00002724 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002725 /* Acquire an EXCLUSIVE lock */
2726
2727 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002728 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002729 */
drh6b9d6dd2008-12-03 19:34:47 +00002730 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002731 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002732 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002733 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002734 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002735 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002736 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002737 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002738 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2739 ** a critical I/O error
2740 */
2741 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2742 SQLITE_IOERR_LOCK;
2743 goto afp_end_lock;
2744 }
2745 }else{
aswift5b1a2562008-08-22 00:22:35 +00002746 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002747 }
2748 }
aswift5b1a2562008-08-22 00:22:35 +00002749 if( failed ){
2750 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002751 }
2752 }
2753
2754 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002755 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002756 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002757 }else if( eFileLock==EXCLUSIVE_LOCK ){
2758 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002759 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002760 }
2761
2762afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002763 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002764 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2765 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002766 return rc;
2767}
2768
2769/*
drh308c2a52010-05-14 11:30:18 +00002770** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002771** must be either NO_LOCK or SHARED_LOCK.
2772**
2773** If the locking level of the file descriptor is already at or below
2774** the requested locking level, this routine is a no-op.
2775*/
drh308c2a52010-05-14 11:30:18 +00002776static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002777 int rc = SQLITE_OK;
2778 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002779 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002780 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2781 int skipShared = 0;
2782#ifdef SQLITE_TEST
2783 int h = pFile->h;
2784#endif
drhbfe66312006-10-03 17:40:40 +00002785
2786 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002787 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002788 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002789 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002790
drh308c2a52010-05-14 11:30:18 +00002791 assert( eFileLock<=SHARED_LOCK );
2792 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002793 return SQLITE_OK;
2794 }
drh6c7d5c52008-11-21 20:32:33 +00002795 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002796 pInode = pFile->pInode;
2797 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002798 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002799 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002800 SimulateIOErrorBenign(1);
2801 SimulateIOError( h=(-1) )
2802 SimulateIOErrorBenign(0);
2803
2804#ifndef NDEBUG
2805 /* When reducing a lock such that other processes can start
2806 ** reading the database file again, make sure that the
2807 ** transaction counter was updated if any part of the database
2808 ** file changed. If the transaction counter is not updated,
2809 ** other connections to the same file might not realize that
2810 ** the file has changed and hence might not know to flush their
2811 ** cache. The use of a stale cache can lead to database corruption.
2812 */
2813 assert( pFile->inNormalWrite==0
2814 || pFile->dbUpdate==0
2815 || pFile->transCntrChng==1 );
2816 pFile->inNormalWrite = 0;
2817#endif
aswiftaebf4132008-11-21 00:10:35 +00002818
drh308c2a52010-05-14 11:30:18 +00002819 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002820 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002821 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002822 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002823 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002824 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2825 } else {
2826 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002827 }
2828 }
drh308c2a52010-05-14 11:30:18 +00002829 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002830 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002831 }
drh308c2a52010-05-14 11:30:18 +00002832 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002833 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2834 if( !rc ){
2835 context->reserved = 0;
2836 }
aswiftaebf4132008-11-21 00:10:35 +00002837 }
drh8af6c222010-05-14 12:43:01 +00002838 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2839 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002840 }
aswiftaebf4132008-11-21 00:10:35 +00002841 }
drh308c2a52010-05-14 11:30:18 +00002842 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002843
drh7ed97b92010-01-20 13:07:21 +00002844 /* Decrement the shared lock counter. Release the lock using an
2845 ** OS call only when all threads in this same process have released
2846 ** the lock.
2847 */
drh8af6c222010-05-14 12:43:01 +00002848 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2849 pInode->nShared--;
2850 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002851 SimulateIOErrorBenign(1);
2852 SimulateIOError( h=(-1) )
2853 SimulateIOErrorBenign(0);
2854 if( !skipShared ){
2855 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2856 }
2857 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002858 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002859 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002860 }
2861 }
2862 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002863 pInode->nLock--;
2864 assert( pInode->nLock>=0 );
2865 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002866 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002867 }
2868 }
drhbfe66312006-10-03 17:40:40 +00002869 }
drh7ed97b92010-01-20 13:07:21 +00002870
drh6c7d5c52008-11-21 20:32:33 +00002871 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002872 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002873 return rc;
2874}
2875
2876/*
drh339eb0b2008-03-07 15:34:11 +00002877** Close a file & cleanup AFP specific locking context
2878*/
danielk1977e339d652008-06-28 11:23:00 +00002879static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002880 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002881 if( id ){
2882 unixFile *pFile = (unixFile*)id;
2883 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002884 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002885 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002886 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002887 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002888 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002889 ** the last lock is cleared.
2890 */
dan08da86a2009-08-21 17:18:03 +00002891 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002892 }
danb0ac3e32010-06-16 10:55:42 +00002893 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002894 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002895 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002896 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002897 }
drh7ed97b92010-01-20 13:07:21 +00002898 return rc;
drhbfe66312006-10-03 17:40:40 +00002899}
2900
drhd2cb50b2009-01-09 21:41:17 +00002901#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002902/*
2903** The code above is the AFP lock implementation. The code is specific
2904** to MacOSX and does not work on other unix platforms. No alternative
2905** is available. If you don't compile for a mac, then the "unix-afp"
2906** VFS is not available.
2907**
2908********************* End of the AFP lock implementation **********************
2909******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002910
drh7ed97b92010-01-20 13:07:21 +00002911/******************************************************************************
2912*************************** Begin NFS Locking ********************************/
2913
2914#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2915/*
drh308c2a52010-05-14 11:30:18 +00002916 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002917 ** must be either NO_LOCK or SHARED_LOCK.
2918 **
2919 ** If the locking level of the file descriptor is already at or below
2920 ** the requested locking level, this routine is a no-op.
2921 */
drh308c2a52010-05-14 11:30:18 +00002922static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002923 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002924}
2925
2926#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2927/*
2928** The code above is the NFS lock implementation. The code is specific
2929** to MacOSX and does not work on other unix platforms. No alternative
2930** is available.
2931**
2932********************* End of the NFS lock implementation **********************
2933******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002934
2935/******************************************************************************
2936**************** Non-locking sqlite3_file methods *****************************
2937**
2938** The next division contains implementations for all methods of the
2939** sqlite3_file object other than the locking methods. The locking
2940** methods were defined in divisions above (one locking method per
2941** division). Those methods that are common to all locking modes
2942** are gather together into this division.
2943*/
drhbfe66312006-10-03 17:40:40 +00002944
2945/*
drh734c9862008-11-28 15:37:20 +00002946** Seek to the offset passed as the second argument, then read cnt
2947** bytes into pBuf. Return the number of bytes actually read.
2948**
2949** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2950** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2951** one system to another. Since SQLite does not define USE_PREAD
2952** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2953** See tickets #2741 and #2681.
2954**
2955** To avoid stomping the errno value on a failed read the lastErrno value
2956** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002957*/
drh734c9862008-11-28 15:37:20 +00002958static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2959 int got;
drh7ed97b92010-01-20 13:07:21 +00002960#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002961 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002962#endif
drh734c9862008-11-28 15:37:20 +00002963 TIMER_START;
2964#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002965 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002966 SimulateIOError( got = -1 );
2967#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002968 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002969 SimulateIOError( got = -1 );
2970#else
2971 newOffset = lseek(id->h, offset, SEEK_SET);
2972 SimulateIOError( newOffset-- );
2973 if( newOffset!=offset ){
2974 if( newOffset == -1 ){
2975 ((unixFile*)id)->lastErrno = errno;
2976 }else{
2977 ((unixFile*)id)->lastErrno = 0;
2978 }
2979 return -1;
2980 }
drhe562be52011-03-02 18:01:10 +00002981 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002982#endif
2983 TIMER_END;
2984 if( got<0 ){
2985 ((unixFile*)id)->lastErrno = errno;
2986 }
drh308c2a52010-05-14 11:30:18 +00002987 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002988 return got;
drhbfe66312006-10-03 17:40:40 +00002989}
2990
2991/*
drh734c9862008-11-28 15:37:20 +00002992** Read data from a file into a buffer. Return SQLITE_OK if all
2993** bytes were read successfully and SQLITE_IOERR if anything goes
2994** wrong.
drh339eb0b2008-03-07 15:34:11 +00002995*/
drh734c9862008-11-28 15:37:20 +00002996static int unixRead(
2997 sqlite3_file *id,
2998 void *pBuf,
2999 int amt,
3000 sqlite3_int64 offset
3001){
dan08da86a2009-08-21 17:18:03 +00003002 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003003 int got;
3004 assert( id );
drh08c6d442009-02-09 17:34:07 +00003005
dan08da86a2009-08-21 17:18:03 +00003006 /* If this is a database file (not a journal, master-journal or temp
3007 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003008#if 0
dane946c392009-08-22 11:39:46 +00003009 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003010 || offset>=PENDING_BYTE+512
3011 || offset+amt<=PENDING_BYTE
3012 );
dan7c246102010-04-12 19:00:29 +00003013#endif
drh08c6d442009-02-09 17:34:07 +00003014
dan08da86a2009-08-21 17:18:03 +00003015 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003016 if( got==amt ){
3017 return SQLITE_OK;
3018 }else if( got<0 ){
3019 /* lastErrno set by seekAndRead */
3020 return SQLITE_IOERR_READ;
3021 }else{
dan08da86a2009-08-21 17:18:03 +00003022 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003023 /* Unread parts of the buffer must be zero-filled */
3024 memset(&((char*)pBuf)[got], 0, amt-got);
3025 return SQLITE_IOERR_SHORT_READ;
3026 }
3027}
3028
3029/*
3030** Seek to the offset in id->offset then read cnt bytes into pBuf.
3031** Return the number of bytes actually read. Update the offset.
3032**
3033** To avoid stomping the errno value on a failed write the lastErrno value
3034** is set before returning.
3035*/
3036static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3037 int got;
drh7ed97b92010-01-20 13:07:21 +00003038#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003039 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003040#endif
drh734c9862008-11-28 15:37:20 +00003041 TIMER_START;
3042#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003043 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003044#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003045 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003046#else
drhbd1e50c2011-08-19 14:54:12 +00003047 do{
3048 newOffset = lseek(id->h, offset, SEEK_SET);
3049 SimulateIOError( newOffset-- );
3050 if( newOffset!=offset ){
3051 if( newOffset == -1 ){
3052 ((unixFile*)id)->lastErrno = errno;
3053 }else{
3054 ((unixFile*)id)->lastErrno = 0;
3055 }
3056 return -1;
drh734c9862008-11-28 15:37:20 +00003057 }
drhbd1e50c2011-08-19 14:54:12 +00003058 got = osWrite(id->h, pBuf, cnt);
3059 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003060#endif
3061 TIMER_END;
3062 if( got<0 ){
3063 ((unixFile*)id)->lastErrno = errno;
3064 }
3065
drh308c2a52010-05-14 11:30:18 +00003066 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003067 return got;
3068}
3069
3070
3071/*
3072** Write data from a buffer into a file. Return SQLITE_OK on success
3073** or some other error code on failure.
3074*/
3075static int unixWrite(
3076 sqlite3_file *id,
3077 const void *pBuf,
3078 int amt,
3079 sqlite3_int64 offset
3080){
dan08da86a2009-08-21 17:18:03 +00003081 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003082 int wrote = 0;
3083 assert( id );
3084 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003085
dan08da86a2009-08-21 17:18:03 +00003086 /* If this is a database file (not a journal, master-journal or temp
3087 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003088#if 0
dane946c392009-08-22 11:39:46 +00003089 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003090 || offset>=PENDING_BYTE+512
3091 || offset+amt<=PENDING_BYTE
3092 );
dan7c246102010-04-12 19:00:29 +00003093#endif
drh08c6d442009-02-09 17:34:07 +00003094
drh8f941bc2009-01-14 23:03:40 +00003095#ifndef NDEBUG
3096 /* If we are doing a normal write to a database file (as opposed to
3097 ** doing a hot-journal rollback or a write to some file other than a
3098 ** normal database file) then record the fact that the database
3099 ** has changed. If the transaction counter is modified, record that
3100 ** fact too.
3101 */
dan08da86a2009-08-21 17:18:03 +00003102 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003103 pFile->dbUpdate = 1; /* The database has been modified */
3104 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003105 int rc;
drh8f941bc2009-01-14 23:03:40 +00003106 char oldCntr[4];
3107 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003108 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003109 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003110 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003111 pFile->transCntrChng = 1; /* The transaction counter has changed */
3112 }
3113 }
3114 }
3115#endif
3116
dan08da86a2009-08-21 17:18:03 +00003117 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003118 amt -= wrote;
3119 offset += wrote;
3120 pBuf = &((char*)pBuf)[wrote];
3121 }
3122 SimulateIOError(( wrote=(-1), amt=1 ));
3123 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003124
drh734c9862008-11-28 15:37:20 +00003125 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003126 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003127 /* lastErrno set by seekAndWrite */
3128 return SQLITE_IOERR_WRITE;
3129 }else{
dan08da86a2009-08-21 17:18:03 +00003130 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003131 return SQLITE_FULL;
3132 }
3133 }
dan6e09d692010-07-27 18:34:15 +00003134
drh734c9862008-11-28 15:37:20 +00003135 return SQLITE_OK;
3136}
3137
3138#ifdef SQLITE_TEST
3139/*
3140** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003141** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003142*/
3143int sqlite3_sync_count = 0;
3144int sqlite3_fullsync_count = 0;
3145#endif
3146
3147/*
drh89240432009-03-25 01:06:01 +00003148** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003149** Others do no. To be safe, we will stick with the (slightly slower)
3150** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003151** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003152*/
drh20f8e132011-08-31 21:01:55 +00003153#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003154# define fdatasync fsync
3155#endif
3156
3157/*
3158** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3159** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3160** only available on Mac OS X. But that could change.
3161*/
3162#ifdef F_FULLFSYNC
3163# define HAVE_FULLFSYNC 1
3164#else
3165# define HAVE_FULLFSYNC 0
3166#endif
3167
3168
3169/*
3170** The fsync() system call does not work as advertised on many
3171** unix systems. The following procedure is an attempt to make
3172** it work better.
3173**
3174** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3175** for testing when we want to run through the test suite quickly.
3176** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3177** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3178** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003179**
3180** SQLite sets the dataOnly flag if the size of the file is unchanged.
3181** The idea behind dataOnly is that it should only write the file content
3182** to disk, not the inode. We only set dataOnly if the file size is
3183** unchanged since the file size is part of the inode. However,
3184** Ted Ts'o tells us that fdatasync() will also write the inode if the
3185** file size has changed. The only real difference between fdatasync()
3186** and fsync(), Ted tells us, is that fdatasync() will not flush the
3187** inode if the mtime or owner or other inode attributes have changed.
3188** We only care about the file size, not the other file attributes, so
3189** as far as SQLite is concerned, an fdatasync() is always adequate.
3190** So, we always use fdatasync() if it is available, regardless of
3191** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003192*/
3193static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003194 int rc;
drh734c9862008-11-28 15:37:20 +00003195
3196 /* The following "ifdef/elif/else/" block has the same structure as
3197 ** the one below. It is replicated here solely to avoid cluttering
3198 ** up the real code with the UNUSED_PARAMETER() macros.
3199 */
3200#ifdef SQLITE_NO_SYNC
3201 UNUSED_PARAMETER(fd);
3202 UNUSED_PARAMETER(fullSync);
3203 UNUSED_PARAMETER(dataOnly);
3204#elif HAVE_FULLFSYNC
3205 UNUSED_PARAMETER(dataOnly);
3206#else
3207 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003208 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003209#endif
3210
3211 /* Record the number of times that we do a normal fsync() and
3212 ** FULLSYNC. This is used during testing to verify that this procedure
3213 ** gets called with the correct arguments.
3214 */
3215#ifdef SQLITE_TEST
3216 if( fullSync ) sqlite3_fullsync_count++;
3217 sqlite3_sync_count++;
3218#endif
3219
3220 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3221 ** no-op
3222 */
3223#ifdef SQLITE_NO_SYNC
3224 rc = SQLITE_OK;
3225#elif HAVE_FULLFSYNC
3226 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003227 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003228 }else{
3229 rc = 1;
3230 }
3231 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003232 ** It shouldn't be possible for fullfsync to fail on the local
3233 ** file system (on OSX), so failure indicates that FULLFSYNC
3234 ** isn't supported for this file system. So, attempt an fsync
3235 ** and (for now) ignore the overhead of a superfluous fcntl call.
3236 ** It'd be better to detect fullfsync support once and avoid
3237 ** the fcntl call every time sync is called.
3238 */
drh734c9862008-11-28 15:37:20 +00003239 if( rc ) rc = fsync(fd);
3240
drh7ed97b92010-01-20 13:07:21 +00003241#elif defined(__APPLE__)
3242 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3243 ** so currently we default to the macro that redefines fdatasync to fsync
3244 */
3245 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003246#else
drh0b647ff2009-03-21 14:41:04 +00003247 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003248#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003249 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003250 rc = fsync(fd);
3251 }
drh0b647ff2009-03-21 14:41:04 +00003252#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003253#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3254
3255 if( OS_VXWORKS && rc!= -1 ){
3256 rc = 0;
3257 }
chw97185482008-11-17 08:05:31 +00003258 return rc;
drhbfe66312006-10-03 17:40:40 +00003259}
3260
drh734c9862008-11-28 15:37:20 +00003261/*
drh0059eae2011-08-08 23:48:40 +00003262** Open a file descriptor to the directory containing file zFilename.
3263** If successful, *pFd is set to the opened file descriptor and
3264** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3265** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3266** value.
3267**
drh90315a22011-08-10 01:52:12 +00003268** The directory file descriptor is used for only one thing - to
3269** fsync() a directory to make sure file creation and deletion events
3270** are flushed to disk. Such fsyncs are not needed on newer
3271** journaling filesystems, but are required on older filesystems.
3272**
3273** This routine can be overridden using the xSetSysCall interface.
3274** The ability to override this routine was added in support of the
3275** chromium sandbox. Opening a directory is a security risk (we are
3276** told) so making it overrideable allows the chromium sandbox to
3277** replace this routine with a harmless no-op. To make this routine
3278** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3279** *pFd set to a negative number.
3280**
drh0059eae2011-08-08 23:48:40 +00003281** If SQLITE_OK is returned, the caller is responsible for closing
3282** the file descriptor *pFd using close().
3283*/
3284static int openDirectory(const char *zFilename, int *pFd){
3285 int ii;
3286 int fd = -1;
3287 char zDirname[MAX_PATHNAME+1];
3288
3289 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3290 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3291 if( ii>0 ){
3292 zDirname[ii] = '\0';
3293 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3294 if( fd>=0 ){
3295#ifdef FD_CLOEXEC
3296 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3297#endif
3298 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3299 }
3300 }
3301 *pFd = fd;
3302 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3303}
3304
3305/*
drh734c9862008-11-28 15:37:20 +00003306** Make sure all writes to a particular file are committed to disk.
3307**
3308** If dataOnly==0 then both the file itself and its metadata (file
3309** size, access time, etc) are synced. If dataOnly!=0 then only the
3310** file data is synced.
3311**
3312** Under Unix, also make sure that the directory entry for the file
3313** has been created by fsync-ing the directory that contains the file.
3314** If we do not do this and we encounter a power failure, the directory
3315** entry for the journal might not exist after we reboot. The next
3316** SQLite to access the file will not know that the journal exists (because
3317** the directory entry for the journal was never created) and the transaction
3318** will not roll back - possibly leading to database corruption.
3319*/
3320static int unixSync(sqlite3_file *id, int flags){
3321 int rc;
3322 unixFile *pFile = (unixFile*)id;
3323
3324 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3325 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3326
3327 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3328 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3329 || (flags&0x0F)==SQLITE_SYNC_FULL
3330 );
3331
3332 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3333 ** line is to test that doing so does not cause any problems.
3334 */
3335 SimulateDiskfullError( return SQLITE_FULL );
3336
3337 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003338 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003339 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3340 SimulateIOError( rc=1 );
3341 if( rc ){
3342 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003343 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003344 }
drh0059eae2011-08-08 23:48:40 +00003345
3346 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003347 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3348 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003349 */
3350 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3351 int dirfd;
3352 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003353 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003354 rc = osOpenDirectory(pFile->zPath, &dirfd);
3355 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003356 full_fsync(dirfd, 0, 0);
3357 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003358 }else if( rc==SQLITE_CANTOPEN ){
3359 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003360 }
drh0059eae2011-08-08 23:48:40 +00003361 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003362 }
3363 return rc;
3364}
3365
3366/*
3367** Truncate an open file to a specified size
3368*/
3369static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003370 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003371 int rc;
dan6e09d692010-07-27 18:34:15 +00003372 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003373 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003374
3375 /* If the user has configured a chunk-size for this file, truncate the
3376 ** file so that it consists of an integer number of chunks (i.e. the
3377 ** actual file size after the operation may be larger than the requested
3378 ** size).
3379 */
3380 if( pFile->szChunk ){
3381 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3382 }
3383
drhff812312011-02-23 13:33:46 +00003384 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003385 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003386 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003387 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003388 }else{
drh3313b142009-11-06 04:13:18 +00003389#ifndef NDEBUG
3390 /* If we are doing a normal write to a database file (as opposed to
3391 ** doing a hot-journal rollback or a write to some file other than a
3392 ** normal database file) and we truncate the file to zero length,
3393 ** that effectively updates the change counter. This might happen
3394 ** when restoring a database using the backup API from a zero-length
3395 ** source.
3396 */
dan6e09d692010-07-27 18:34:15 +00003397 if( pFile->inNormalWrite && nByte==0 ){
3398 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003399 }
3400#endif
3401
drh734c9862008-11-28 15:37:20 +00003402 return SQLITE_OK;
3403 }
3404}
3405
3406/*
3407** Determine the current size of a file in bytes
3408*/
3409static int unixFileSize(sqlite3_file *id, i64 *pSize){
3410 int rc;
3411 struct stat buf;
3412 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003413 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003414 SimulateIOError( rc=1 );
3415 if( rc!=0 ){
3416 ((unixFile*)id)->lastErrno = errno;
3417 return SQLITE_IOERR_FSTAT;
3418 }
3419 *pSize = buf.st_size;
3420
drh8af6c222010-05-14 12:43:01 +00003421 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003422 ** writes a single byte into that file in order to work around a bug
3423 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3424 ** layers, we need to report this file size as zero even though it is
3425 ** really 1. Ticket #3260.
3426 */
3427 if( *pSize==1 ) *pSize = 0;
3428
3429
3430 return SQLITE_OK;
3431}
3432
drhd2cb50b2009-01-09 21:41:17 +00003433#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003434/*
3435** Handler for proxy-locking file-control verbs. Defined below in the
3436** proxying locking division.
3437*/
3438static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003439#endif
drh715ff302008-12-03 22:32:44 +00003440
dan502019c2010-07-28 14:26:17 +00003441/*
3442** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003443** file-control operation. Enlarge the database to nBytes in size
3444** (rounded up to the next chunk-size). If the database is already
3445** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003446*/
3447static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003448 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003449 i64 nSize; /* Required file size */
3450 struct stat buf; /* Used to hold return values of fstat() */
3451
drh99ab3b12011-03-02 15:09:07 +00003452 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003453
3454 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3455 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003456
dan502019c2010-07-28 14:26:17 +00003457#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003458 /* The code below is handling the return value of osFallocate()
3459 ** correctly. posix_fallocate() is defined to "returns zero on success,
3460 ** or an error number on failure". See the manpage for details. */
3461 int err;
drhff812312011-02-23 13:33:46 +00003462 do{
dan661d71a2011-03-30 19:08:03 +00003463 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3464 }while( err==EINTR );
3465 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003466#else
3467 /* If the OS does not have posix_fallocate(), fake it. First use
3468 ** ftruncate() to set the file size, then write a single byte to
3469 ** the last byte in each block within the extended region. This
3470 ** is the same technique used by glibc to implement posix_fallocate()
3471 ** on systems that do not have a real fallocate() system call.
3472 */
3473 int nBlk = buf.st_blksize; /* File-system block size */
3474 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003475
drhff812312011-02-23 13:33:46 +00003476 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003477 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003478 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003479 }
3480 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003481 while( iWrite<nSize ){
3482 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3483 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003484 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003485 }
dan502019c2010-07-28 14:26:17 +00003486#endif
3487 }
3488 }
3489
3490 return SQLITE_OK;
3491}
danielk1977ad94b582007-08-20 06:44:22 +00003492
danielk1977e3026632004-06-22 11:29:02 +00003493/*
drh9e33c2c2007-08-31 18:34:59 +00003494** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003495*/
drhcc6bb3e2007-08-31 16:11:35 +00003496static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003497 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003498 switch( op ){
3499 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003500 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003501 return SQLITE_OK;
3502 }
drh7708e972008-11-29 00:56:52 +00003503 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003504 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003505 return SQLITE_OK;
3506 }
dan6e09d692010-07-27 18:34:15 +00003507 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003508 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003509 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003510 }
drh9ff27ec2010-05-19 19:26:05 +00003511 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003512 int rc;
3513 SimulateIOErrorBenign(1);
3514 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3515 SimulateIOErrorBenign(0);
3516 return rc;
drhf0b190d2011-07-26 16:03:07 +00003517 }
3518 case SQLITE_FCNTL_PERSIST_WAL: {
3519 int bPersist = *(int*)pArg;
3520 if( bPersist<0 ){
drh253cea52011-07-26 16:23:25 +00003521 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
drhf0b190d2011-07-26 16:03:07 +00003522 }else if( bPersist==0 ){
3523 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
3524 }else{
3525 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
3526 }
3527 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003528 }
drh8f941bc2009-01-14 23:03:40 +00003529#ifndef NDEBUG
3530 /* The pager calls this method to signal that it has done
3531 ** a rollback and that the database is therefore unchanged and
3532 ** it hence it is OK for the transaction change counter to be
3533 ** unchanged.
3534 */
3535 case SQLITE_FCNTL_DB_UNCHANGED: {
3536 ((unixFile*)id)->dbUpdate = 0;
3537 return SQLITE_OK;
3538 }
3539#endif
drhd2cb50b2009-01-09 21:41:17 +00003540#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003541 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003542 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003543 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003544 }
drhd2cb50b2009-01-09 21:41:17 +00003545#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003546 case SQLITE_FCNTL_SYNC_OMITTED: {
3547 return SQLITE_OK; /* A no-op */
3548 }
drh9e33c2c2007-08-31 18:34:59 +00003549 }
drh0b52b7d2011-01-26 19:46:22 +00003550 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003551}
3552
3553/*
danielk1977a3d4c882007-03-23 10:08:38 +00003554** Return the sector size in bytes of the underlying block device for
3555** the specified file. This is almost always 512 bytes, but may be
3556** larger for some devices.
3557**
3558** SQLite code assumes this function cannot fail. It also assumes that
3559** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003560** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003561** same for both.
3562*/
danielk1977397d65f2008-11-19 11:35:39 +00003563static int unixSectorSize(sqlite3_file *NotUsed){
3564 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003565 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003566}
3567
danielk197790949c22007-08-17 16:50:38 +00003568/*
danielk1977397d65f2008-11-19 11:35:39 +00003569** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003570*/
danielk1977397d65f2008-11-19 11:35:39 +00003571static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3572 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003573 return 0;
3574}
3575
drhd9e5c4f2010-05-12 18:01:39 +00003576#ifndef SQLITE_OMIT_WAL
3577
3578
3579/*
drhd91c68f2010-05-14 14:52:25 +00003580** Object used to represent an shared memory buffer.
3581**
3582** When multiple threads all reference the same wal-index, each thread
3583** has its own unixShm object, but they all point to a single instance
3584** of this unixShmNode object. In other words, each wal-index is opened
3585** only once per process.
3586**
3587** Each unixShmNode object is connected to a single unixInodeInfo object.
3588** We could coalesce this object into unixInodeInfo, but that would mean
3589** every open file that does not use shared memory (in other words, most
3590** open files) would have to carry around this extra information. So
3591** the unixInodeInfo object contains a pointer to this unixShmNode object
3592** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003593**
3594** unixMutexHeld() must be true when creating or destroying
3595** this object or while reading or writing the following fields:
3596**
3597** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003598**
3599** The following fields are read-only after the object is created:
3600**
3601** fid
3602** zFilename
3603**
drhd91c68f2010-05-14 14:52:25 +00003604** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003605** unixMutexHeld() is true when reading or writing any other field
3606** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003607*/
drhd91c68f2010-05-14 14:52:25 +00003608struct unixShmNode {
3609 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003610 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003611 char *zFilename; /* Name of the mmapped file */
3612 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003613 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003614 u16 nRegion; /* Size of array apRegion */
3615 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003616 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003617 int nRef; /* Number of unixShm objects pointing to this */
3618 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003619#ifdef SQLITE_DEBUG
3620 u8 exclMask; /* Mask of exclusive locks held */
3621 u8 sharedMask; /* Mask of shared locks held */
3622 u8 nextShmId; /* Next available unixShm.id value */
3623#endif
3624};
3625
3626/*
drhd9e5c4f2010-05-12 18:01:39 +00003627** Structure used internally by this VFS to record the state of an
3628** open shared memory connection.
3629**
drhd91c68f2010-05-14 14:52:25 +00003630** The following fields are initialized when this object is created and
3631** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003632**
drhd91c68f2010-05-14 14:52:25 +00003633** unixShm.pFile
3634** unixShm.id
3635**
3636** All other fields are read/write. The unixShm.pFile->mutex must be held
3637** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003638*/
3639struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003640 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3641 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003642 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003643 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003644 u16 sharedMask; /* Mask of shared locks held */
3645 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003646};
3647
3648/*
drhd9e5c4f2010-05-12 18:01:39 +00003649** Constants used for locking
3650*/
drhbd9676c2010-06-23 17:58:38 +00003651#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003652#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003653
drhd9e5c4f2010-05-12 18:01:39 +00003654/*
drh73b64e42010-05-30 19:55:15 +00003655** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003656**
3657** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3658** otherwise.
3659*/
3660static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003661 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3662 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003663 int ofst, /* First byte of the locking range */
3664 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003665){
3666 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003667 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003668
drhd91c68f2010-05-14 14:52:25 +00003669 /* Access to the unixShmNode object is serialized by the caller */
3670 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003671
drh73b64e42010-05-30 19:55:15 +00003672 /* Shared locks never span more than one byte */
3673 assert( n==1 || lockType!=F_RDLCK );
3674
3675 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003676 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003677
drh3cb93392011-03-12 18:10:44 +00003678 if( pShmNode->h>=0 ){
3679 /* Initialize the locking parameters */
3680 memset(&f, 0, sizeof(f));
3681 f.l_type = lockType;
3682 f.l_whence = SEEK_SET;
3683 f.l_start = ofst;
3684 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003685
drh3cb93392011-03-12 18:10:44 +00003686 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3687 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3688 }
drhd9e5c4f2010-05-12 18:01:39 +00003689
3690 /* Update the global lock state and do debug tracing */
3691#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003692 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003693 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003694 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003695 if( rc==SQLITE_OK ){
3696 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003697 OSTRACE(("unlock %d ok", ofst));
3698 pShmNode->exclMask &= ~mask;
3699 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003700 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003701 OSTRACE(("read-lock %d ok", ofst));
3702 pShmNode->exclMask &= ~mask;
3703 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003704 }else{
3705 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003706 OSTRACE(("write-lock %d ok", ofst));
3707 pShmNode->exclMask |= mask;
3708 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003709 }
3710 }else{
3711 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003712 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003713 }else if( lockType==F_RDLCK ){
3714 OSTRACE(("read-lock failed"));
3715 }else{
3716 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003717 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003718 }
3719 }
drh20e1f082010-05-31 16:10:12 +00003720 OSTRACE((" - afterwards %03x,%03x\n",
3721 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003722 }
drhd9e5c4f2010-05-12 18:01:39 +00003723#endif
3724
3725 return rc;
3726}
3727
drhd9e5c4f2010-05-12 18:01:39 +00003728
3729/*
drhd91c68f2010-05-14 14:52:25 +00003730** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003731**
3732** This is not a VFS shared-memory method; it is a utility function called
3733** by VFS shared-memory methods.
3734*/
drhd91c68f2010-05-14 14:52:25 +00003735static void unixShmPurge(unixFile *pFd){
3736 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003737 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003738 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003739 int i;
drhd91c68f2010-05-14 14:52:25 +00003740 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003741 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003742 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003743 if( p->h>=0 ){
3744 munmap(p->apRegion[i], p->szRegion);
3745 }else{
3746 sqlite3_free(p->apRegion[i]);
3747 }
dan13a3cb82010-06-11 19:04:21 +00003748 }
dan18801912010-06-14 14:07:50 +00003749 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003750 if( p->h>=0 ){
3751 robust_close(pFd, p->h, __LINE__);
3752 p->h = -1;
3753 }
drhd91c68f2010-05-14 14:52:25 +00003754 p->pInode->pShmNode = 0;
3755 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003756 }
3757}
3758
3759/*
danda9fe0c2010-07-13 18:44:03 +00003760** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003761** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003762**
drh7234c6d2010-06-19 15:10:09 +00003763** The file used to implement shared-memory is in the same directory
3764** as the open database file and has the same name as the open database
3765** file with the "-shm" suffix added. For example, if the database file
3766** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003767** for shared memory will be called "/home/user1/config.db-shm".
3768**
3769** Another approach to is to use files in /dev/shm or /dev/tmp or an
3770** some other tmpfs mount. But if a file in a different directory
3771** from the database file is used, then differing access permissions
3772** or a chroot() might cause two different processes on the same
3773** database to end up using different files for shared memory -
3774** meaning that their memory would not really be shared - resulting
3775** in database corruption. Nevertheless, this tmpfs file usage
3776** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3777** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3778** option results in an incompatible build of SQLite; builds of SQLite
3779** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3780** same database file at the same time, database corruption will likely
3781** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3782** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003783**
3784** When opening a new shared-memory file, if no other instances of that
3785** file are currently open, in this process or in other processes, then
3786** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003787**
3788** If the original database file (pDbFd) is using the "unix-excl" VFS
3789** that means that an exclusive lock is held on the database file and
3790** that no other processes are able to read or write the database. In
3791** that case, we do not really need shared memory. No shared memory
3792** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003793*/
danda9fe0c2010-07-13 18:44:03 +00003794static int unixOpenSharedMemory(unixFile *pDbFd){
3795 struct unixShm *p = 0; /* The connection to be opened */
3796 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3797 int rc; /* Result code */
3798 unixInodeInfo *pInode; /* The inode of fd */
3799 char *zShmFilename; /* Name of the file used for SHM */
3800 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003801
danda9fe0c2010-07-13 18:44:03 +00003802 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003803 p = sqlite3_malloc( sizeof(*p) );
3804 if( p==0 ) return SQLITE_NOMEM;
3805 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003806 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003807
danda9fe0c2010-07-13 18:44:03 +00003808 /* Check to see if a unixShmNode object already exists. Reuse an existing
3809 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003810 */
3811 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003812 pInode = pDbFd->pInode;
3813 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003814 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003815 struct stat sStat; /* fstat() info for database file */
3816
3817 /* Call fstat() to figure out the permissions on the database file. If
3818 ** a new *-shm file is created, an attempt will be made to create it
3819 ** with the same permissions. The actual permissions the file is created
3820 ** with are subject to the current umask setting.
3821 */
drh3cb93392011-03-12 18:10:44 +00003822 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003823 rc = SQLITE_IOERR_FSTAT;
3824 goto shm_open_err;
3825 }
3826
drha4ced192010-07-15 18:32:40 +00003827#ifdef SQLITE_SHM_DIRECTORY
3828 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3829#else
drh7234c6d2010-06-19 15:10:09 +00003830 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003831#endif
drh7234c6d2010-06-19 15:10:09 +00003832 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003833 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003834 rc = SQLITE_NOMEM;
3835 goto shm_open_err;
3836 }
drhd91c68f2010-05-14 14:52:25 +00003837 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003838 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003839#ifdef SQLITE_SHM_DIRECTORY
3840 sqlite3_snprintf(nShmFilename, zShmFilename,
3841 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3842 (u32)sStat.st_ino, (u32)sStat.st_dev);
3843#else
drh7234c6d2010-06-19 15:10:09 +00003844 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003845 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003846#endif
drhd91c68f2010-05-14 14:52:25 +00003847 pShmNode->h = -1;
3848 pDbFd->pInode->pShmNode = pShmNode;
3849 pShmNode->pInode = pDbFd->pInode;
3850 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3851 if( pShmNode->mutex==0 ){
3852 rc = SQLITE_NOMEM;
3853 goto shm_open_err;
3854 }
drhd9e5c4f2010-05-12 18:01:39 +00003855
drh3cb93392011-03-12 18:10:44 +00003856 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003857 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3858 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003859 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003860 const char *zRO;
3861 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003862 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003863 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3864 (sStat.st_mode & 0777));
3865 pShmNode->isReadonly = 1;
3866 }
3867 if( pShmNode->h<0 ){
3868 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3869 goto shm_open_err;
3870 }
drhd9e5c4f2010-05-12 18:01:39 +00003871 }
drh3cb93392011-03-12 18:10:44 +00003872
3873 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003874 ** If not, truncate the file to zero length.
3875 */
3876 rc = SQLITE_OK;
3877 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3878 if( robust_ftruncate(pShmNode->h, 0) ){
3879 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003880 }
3881 }
drh66dfec8b2011-06-01 20:01:49 +00003882 if( rc==SQLITE_OK ){
3883 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3884 }
3885 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003886 }
drhd9e5c4f2010-05-12 18:01:39 +00003887 }
3888
drhd91c68f2010-05-14 14:52:25 +00003889 /* Make the new connection a child of the unixShmNode */
3890 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003891#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003892 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003893#endif
drhd91c68f2010-05-14 14:52:25 +00003894 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003895 pDbFd->pShm = p;
3896 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003897
3898 /* The reference count on pShmNode has already been incremented under
3899 ** the cover of the unixEnterMutex() mutex and the pointer from the
3900 ** new (struct unixShm) object to the pShmNode has been set. All that is
3901 ** left to do is to link the new object into the linked list starting
3902 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3903 ** mutex.
3904 */
3905 sqlite3_mutex_enter(pShmNode->mutex);
3906 p->pNext = pShmNode->pFirst;
3907 pShmNode->pFirst = p;
3908 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003909 return SQLITE_OK;
3910
3911 /* Jump here on any error */
3912shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003913 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003914 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003915 unixLeaveMutex();
3916 return rc;
3917}
3918
3919/*
danda9fe0c2010-07-13 18:44:03 +00003920** This function is called to obtain a pointer to region iRegion of the
3921** shared-memory associated with the database file fd. Shared-memory regions
3922** are numbered starting from zero. Each shared-memory region is szRegion
3923** bytes in size.
3924**
3925** If an error occurs, an error code is returned and *pp is set to NULL.
3926**
3927** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3928** region has not been allocated (by any client, including one running in a
3929** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3930** bExtend is non-zero and the requested shared-memory region has not yet
3931** been allocated, it is allocated by this function.
3932**
3933** If the shared-memory region has already been allocated or is allocated by
3934** this call as described above, then it is mapped into this processes
3935** address space (if it is not already), *pp is set to point to the mapped
3936** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003937*/
danda9fe0c2010-07-13 18:44:03 +00003938static int unixShmMap(
3939 sqlite3_file *fd, /* Handle open on database file */
3940 int iRegion, /* Region to retrieve */
3941 int szRegion, /* Size of regions */
3942 int bExtend, /* True to extend file if necessary */
3943 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003944){
danda9fe0c2010-07-13 18:44:03 +00003945 unixFile *pDbFd = (unixFile*)fd;
3946 unixShm *p;
3947 unixShmNode *pShmNode;
3948 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003949
danda9fe0c2010-07-13 18:44:03 +00003950 /* If the shared-memory file has not yet been opened, open it now. */
3951 if( pDbFd->pShm==0 ){
3952 rc = unixOpenSharedMemory(pDbFd);
3953 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003954 }
drhd9e5c4f2010-05-12 18:01:39 +00003955
danda9fe0c2010-07-13 18:44:03 +00003956 p = pDbFd->pShm;
3957 pShmNode = p->pShmNode;
3958 sqlite3_mutex_enter(pShmNode->mutex);
3959 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003960 assert( pShmNode->pInode==pDbFd->pInode );
3961 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3962 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003963
3964 if( pShmNode->nRegion<=iRegion ){
3965 char **apNew; /* New apRegion[] array */
3966 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3967 struct stat sStat; /* Used by fstat() */
3968
3969 pShmNode->szRegion = szRegion;
3970
drh3cb93392011-03-12 18:10:44 +00003971 if( pShmNode->h>=0 ){
3972 /* The requested region is not mapped into this processes address space.
3973 ** Check to see if it has been allocated (i.e. if the wal-index file is
3974 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003975 */
drh3cb93392011-03-12 18:10:44 +00003976 if( osFstat(pShmNode->h, &sStat) ){
3977 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003978 goto shmpage_out;
3979 }
drh3cb93392011-03-12 18:10:44 +00003980
3981 if( sStat.st_size<nByte ){
3982 /* The requested memory region does not exist. If bExtend is set to
3983 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3984 **
3985 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3986 ** the requested memory region.
3987 */
3988 if( !bExtend ) goto shmpage_out;
3989 if( robust_ftruncate(pShmNode->h, nByte) ){
3990 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3991 pShmNode->zFilename);
3992 goto shmpage_out;
3993 }
3994 }
danda9fe0c2010-07-13 18:44:03 +00003995 }
3996
3997 /* Map the requested memory region into this processes address space. */
3998 apNew = (char **)sqlite3_realloc(
3999 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4000 );
4001 if( !apNew ){
4002 rc = SQLITE_IOERR_NOMEM;
4003 goto shmpage_out;
4004 }
4005 pShmNode->apRegion = apNew;
4006 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004007 void *pMem;
4008 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004009 pMem = mmap(0, szRegion,
4010 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004011 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4012 );
4013 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004014 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004015 goto shmpage_out;
4016 }
4017 }else{
4018 pMem = sqlite3_malloc(szRegion);
4019 if( pMem==0 ){
4020 rc = SQLITE_NOMEM;
4021 goto shmpage_out;
4022 }
4023 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004024 }
4025 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4026 pShmNode->nRegion++;
4027 }
4028 }
4029
4030shmpage_out:
4031 if( pShmNode->nRegion>iRegion ){
4032 *pp = pShmNode->apRegion[iRegion];
4033 }else{
4034 *pp = 0;
4035 }
drh66dfec8b2011-06-01 20:01:49 +00004036 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004037 sqlite3_mutex_leave(pShmNode->mutex);
4038 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004039}
4040
4041/*
drhd9e5c4f2010-05-12 18:01:39 +00004042** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004043**
4044** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4045** different here than in posix. In xShmLock(), one can go from unlocked
4046** to shared and back or from unlocked to exclusive and back. But one may
4047** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004048*/
4049static int unixShmLock(
4050 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004051 int ofst, /* First lock to acquire or release */
4052 int n, /* Number of locks to acquire or release */
4053 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004054){
drh73b64e42010-05-30 19:55:15 +00004055 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4056 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4057 unixShm *pX; /* For looping over all siblings */
4058 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4059 int rc = SQLITE_OK; /* Result code */
4060 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004061
drhd91c68f2010-05-14 14:52:25 +00004062 assert( pShmNode==pDbFd->pInode->pShmNode );
4063 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004064 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004065 assert( n>=1 );
4066 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4067 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4068 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4069 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4070 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004071 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4072 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004073
drhc99597c2010-05-31 01:41:15 +00004074 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004075 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004076 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004077 if( flags & SQLITE_SHM_UNLOCK ){
4078 u16 allMask = 0; /* Mask of locks held by siblings */
4079
4080 /* See if any siblings hold this same lock */
4081 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4082 if( pX==p ) continue;
4083 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4084 allMask |= pX->sharedMask;
4085 }
4086
4087 /* Unlock the system-level locks */
4088 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004089 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004090 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004091 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004092 }
drh73b64e42010-05-30 19:55:15 +00004093
4094 /* Undo the local locks */
4095 if( rc==SQLITE_OK ){
4096 p->exclMask &= ~mask;
4097 p->sharedMask &= ~mask;
4098 }
4099 }else if( flags & SQLITE_SHM_SHARED ){
4100 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4101
4102 /* Find out which shared locks are already held by sibling connections.
4103 ** If any sibling already holds an exclusive lock, go ahead and return
4104 ** SQLITE_BUSY.
4105 */
4106 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004107 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004108 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004109 break;
4110 }
4111 allShared |= pX->sharedMask;
4112 }
4113
4114 /* Get shared locks at the system level, if necessary */
4115 if( rc==SQLITE_OK ){
4116 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004117 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004118 }else{
drh73b64e42010-05-30 19:55:15 +00004119 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004120 }
drhd9e5c4f2010-05-12 18:01:39 +00004121 }
drh73b64e42010-05-30 19:55:15 +00004122
4123 /* Get the local shared locks */
4124 if( rc==SQLITE_OK ){
4125 p->sharedMask |= mask;
4126 }
4127 }else{
4128 /* Make sure no sibling connections hold locks that will block this
4129 ** lock. If any do, return SQLITE_BUSY right away.
4130 */
4131 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004132 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4133 rc = SQLITE_BUSY;
4134 break;
4135 }
4136 }
4137
4138 /* Get the exclusive locks at the system level. Then if successful
4139 ** also mark the local connection as being locked.
4140 */
4141 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004142 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004143 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004144 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004145 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004146 }
drhd9e5c4f2010-05-12 18:01:39 +00004147 }
4148 }
drhd91c68f2010-05-14 14:52:25 +00004149 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004150 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4151 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004152 return rc;
4153}
4154
drh286a2882010-05-20 23:51:06 +00004155/*
4156** Implement a memory barrier or memory fence on shared memory.
4157**
4158** All loads and stores begun before the barrier must complete before
4159** any load or store begun after the barrier.
4160*/
4161static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004162 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004163){
drhff828942010-06-26 21:34:06 +00004164 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004165 unixEnterMutex();
4166 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004167}
4168
dan18801912010-06-14 14:07:50 +00004169/*
danda9fe0c2010-07-13 18:44:03 +00004170** Close a connection to shared-memory. Delete the underlying
4171** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004172**
4173** If there is no shared memory associated with the connection then this
4174** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004175*/
danda9fe0c2010-07-13 18:44:03 +00004176static int unixShmUnmap(
4177 sqlite3_file *fd, /* The underlying database file */
4178 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004179){
danda9fe0c2010-07-13 18:44:03 +00004180 unixShm *p; /* The connection to be closed */
4181 unixShmNode *pShmNode; /* The underlying shared-memory file */
4182 unixShm **pp; /* For looping over sibling connections */
4183 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004184
danda9fe0c2010-07-13 18:44:03 +00004185 pDbFd = (unixFile*)fd;
4186 p = pDbFd->pShm;
4187 if( p==0 ) return SQLITE_OK;
4188 pShmNode = p->pShmNode;
4189
4190 assert( pShmNode==pDbFd->pInode->pShmNode );
4191 assert( pShmNode->pInode==pDbFd->pInode );
4192
4193 /* Remove connection p from the set of connections associated
4194 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004195 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004196 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4197 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004198
danda9fe0c2010-07-13 18:44:03 +00004199 /* Free the connection p */
4200 sqlite3_free(p);
4201 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004202 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004203
4204 /* If pShmNode->nRef has reached 0, then close the underlying
4205 ** shared-memory file, too */
4206 unixEnterMutex();
4207 assert( pShmNode->nRef>0 );
4208 pShmNode->nRef--;
4209 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004210 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004211 unixShmPurge(pDbFd);
4212 }
4213 unixLeaveMutex();
4214
4215 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004216}
drh286a2882010-05-20 23:51:06 +00004217
danda9fe0c2010-07-13 18:44:03 +00004218
drhd9e5c4f2010-05-12 18:01:39 +00004219#else
drh6b017cc2010-06-14 18:01:46 +00004220# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004221# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004222# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004223# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004224#endif /* #ifndef SQLITE_OMIT_WAL */
4225
drh734c9862008-11-28 15:37:20 +00004226/*
4227** Here ends the implementation of all sqlite3_file methods.
4228**
4229********************** End sqlite3_file Methods *******************************
4230******************************************************************************/
4231
4232/*
drh6b9d6dd2008-12-03 19:34:47 +00004233** This division contains definitions of sqlite3_io_methods objects that
4234** implement various file locking strategies. It also contains definitions
4235** of "finder" functions. A finder-function is used to locate the appropriate
4236** sqlite3_io_methods object for a particular database file. The pAppData
4237** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4238** the correct finder-function for that VFS.
4239**
4240** Most finder functions return a pointer to a fixed sqlite3_io_methods
4241** object. The only interesting finder-function is autolockIoFinder, which
4242** looks at the filesystem type and tries to guess the best locking
4243** strategy from that.
4244**
drh1875f7a2008-12-08 18:19:17 +00004245** For finder-funtion F, two objects are created:
4246**
4247** (1) The real finder-function named "FImpt()".
4248**
dane946c392009-08-22 11:39:46 +00004249** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004250**
4251**
4252** A pointer to the F pointer is used as the pAppData value for VFS
4253** objects. We have to do this instead of letting pAppData point
4254** directly at the finder-function since C90 rules prevent a void*
4255** from be cast into a function pointer.
4256**
drh6b9d6dd2008-12-03 19:34:47 +00004257**
drh7708e972008-11-29 00:56:52 +00004258** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004259**
drh7708e972008-11-29 00:56:52 +00004260** * A constant sqlite3_io_methods object call METHOD that has locking
4261** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4262**
4263** * An I/O method finder function called FINDER that returns a pointer
4264** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004265*/
drhd9e5c4f2010-05-12 18:01:39 +00004266#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004267static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004268 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004269 CLOSE, /* xClose */ \
4270 unixRead, /* xRead */ \
4271 unixWrite, /* xWrite */ \
4272 unixTruncate, /* xTruncate */ \
4273 unixSync, /* xSync */ \
4274 unixFileSize, /* xFileSize */ \
4275 LOCK, /* xLock */ \
4276 UNLOCK, /* xUnlock */ \
4277 CKLOCK, /* xCheckReservedLock */ \
4278 unixFileControl, /* xFileControl */ \
4279 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004280 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004281 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004282 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004283 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004284 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004285}; \
drh0c2694b2009-09-03 16:23:44 +00004286static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4287 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004288 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004289} \
drh0c2694b2009-09-03 16:23:44 +00004290static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004291 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004292
4293/*
4294** Here are all of the sqlite3_io_methods objects for each of the
4295** locking strategies. Functions that return pointers to these methods
4296** are also created.
4297*/
4298IOMETHODS(
4299 posixIoFinder, /* Finder function name */
4300 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004301 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004302 unixClose, /* xClose method */
4303 unixLock, /* xLock method */
4304 unixUnlock, /* xUnlock method */
4305 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004306)
drh7708e972008-11-29 00:56:52 +00004307IOMETHODS(
4308 nolockIoFinder, /* Finder function name */
4309 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004310 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004311 nolockClose, /* xClose method */
4312 nolockLock, /* xLock method */
4313 nolockUnlock, /* xUnlock method */
4314 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004315)
drh7708e972008-11-29 00:56:52 +00004316IOMETHODS(
4317 dotlockIoFinder, /* Finder function name */
4318 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004319 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004320 dotlockClose, /* xClose method */
4321 dotlockLock, /* xLock method */
4322 dotlockUnlock, /* xUnlock method */
4323 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004324)
drh7708e972008-11-29 00:56:52 +00004325
chw78a13182009-04-07 05:35:03 +00004326#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004327IOMETHODS(
4328 flockIoFinder, /* Finder function name */
4329 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004330 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004331 flockClose, /* xClose method */
4332 flockLock, /* xLock method */
4333 flockUnlock, /* xUnlock method */
4334 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004335)
drh7708e972008-11-29 00:56:52 +00004336#endif
4337
drh6c7d5c52008-11-21 20:32:33 +00004338#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004339IOMETHODS(
4340 semIoFinder, /* Finder function name */
4341 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004342 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004343 semClose, /* xClose method */
4344 semLock, /* xLock method */
4345 semUnlock, /* xUnlock method */
4346 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004347)
aswiftaebf4132008-11-21 00:10:35 +00004348#endif
drh7708e972008-11-29 00:56:52 +00004349
drhd2cb50b2009-01-09 21:41:17 +00004350#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004351IOMETHODS(
4352 afpIoFinder, /* Finder function name */
4353 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004354 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004355 afpClose, /* xClose method */
4356 afpLock, /* xLock method */
4357 afpUnlock, /* xUnlock method */
4358 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004359)
drh715ff302008-12-03 22:32:44 +00004360#endif
4361
4362/*
4363** The proxy locking method is a "super-method" in the sense that it
4364** opens secondary file descriptors for the conch and lock files and
4365** it uses proxy, dot-file, AFP, and flock() locking methods on those
4366** secondary files. For this reason, the division that implements
4367** proxy locking is located much further down in the file. But we need
4368** to go ahead and define the sqlite3_io_methods and finder function
4369** for proxy locking here. So we forward declare the I/O methods.
4370*/
drhd2cb50b2009-01-09 21:41:17 +00004371#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004372static int proxyClose(sqlite3_file*);
4373static int proxyLock(sqlite3_file*, int);
4374static int proxyUnlock(sqlite3_file*, int);
4375static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004376IOMETHODS(
4377 proxyIoFinder, /* Finder function name */
4378 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004379 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004380 proxyClose, /* xClose method */
4381 proxyLock, /* xLock method */
4382 proxyUnlock, /* xUnlock method */
4383 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004384)
aswiftaebf4132008-11-21 00:10:35 +00004385#endif
drh7708e972008-11-29 00:56:52 +00004386
drh7ed97b92010-01-20 13:07:21 +00004387/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4388#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4389IOMETHODS(
4390 nfsIoFinder, /* Finder function name */
4391 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004392 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004393 unixClose, /* xClose method */
4394 unixLock, /* xLock method */
4395 nfsUnlock, /* xUnlock method */
4396 unixCheckReservedLock /* xCheckReservedLock method */
4397)
4398#endif
drh7708e972008-11-29 00:56:52 +00004399
drhd2cb50b2009-01-09 21:41:17 +00004400#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004401/*
drh6b9d6dd2008-12-03 19:34:47 +00004402** This "finder" function attempts to determine the best locking strategy
4403** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004404** object that implements that strategy.
4405**
4406** This is for MacOSX only.
4407*/
drh1875f7a2008-12-08 18:19:17 +00004408static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004409 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004410 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004411){
4412 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004413 const char *zFilesystem; /* Filesystem type name */
4414 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004415 } aMap[] = {
4416 { "hfs", &posixIoMethods },
4417 { "ufs", &posixIoMethods },
4418 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004419 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004420 { "webdav", &nolockIoMethods },
4421 { 0, 0 }
4422 };
4423 int i;
4424 struct statfs fsInfo;
4425 struct flock lockInfo;
4426
4427 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004428 /* If filePath==NULL that means we are dealing with a transient file
4429 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004430 return &nolockIoMethods;
4431 }
4432 if( statfs(filePath, &fsInfo) != -1 ){
4433 if( fsInfo.f_flags & MNT_RDONLY ){
4434 return &nolockIoMethods;
4435 }
4436 for(i=0; aMap[i].zFilesystem; i++){
4437 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4438 return aMap[i].pMethods;
4439 }
4440 }
4441 }
4442
4443 /* Default case. Handles, amongst others, "nfs".
4444 ** Test byte-range lock using fcntl(). If the call succeeds,
4445 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004446 */
drh7708e972008-11-29 00:56:52 +00004447 lockInfo.l_len = 1;
4448 lockInfo.l_start = 0;
4449 lockInfo.l_whence = SEEK_SET;
4450 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004451 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004452 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4453 return &nfsIoMethods;
4454 } else {
4455 return &posixIoMethods;
4456 }
drh7708e972008-11-29 00:56:52 +00004457 }else{
4458 return &dotlockIoMethods;
4459 }
4460}
drh0c2694b2009-09-03 16:23:44 +00004461static const sqlite3_io_methods
4462 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004463
drhd2cb50b2009-01-09 21:41:17 +00004464#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004465
chw78a13182009-04-07 05:35:03 +00004466#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4467/*
4468** This "finder" function attempts to determine the best locking strategy
4469** for the database file "filePath". It then returns the sqlite3_io_methods
4470** object that implements that strategy.
4471**
4472** This is for VXWorks only.
4473*/
4474static const sqlite3_io_methods *autolockIoFinderImpl(
4475 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004476 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004477){
4478 struct flock lockInfo;
4479
4480 if( !filePath ){
4481 /* If filePath==NULL that means we are dealing with a transient file
4482 ** that does not need to be locked. */
4483 return &nolockIoMethods;
4484 }
4485
4486 /* Test if fcntl() is supported and use POSIX style locks.
4487 ** Otherwise fall back to the named semaphore method.
4488 */
4489 lockInfo.l_len = 1;
4490 lockInfo.l_start = 0;
4491 lockInfo.l_whence = SEEK_SET;
4492 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004493 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004494 return &posixIoMethods;
4495 }else{
4496 return &semIoMethods;
4497 }
4498}
drh0c2694b2009-09-03 16:23:44 +00004499static const sqlite3_io_methods
4500 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004501
4502#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4503
drh7708e972008-11-29 00:56:52 +00004504/*
4505** An abstract type for a pointer to a IO method finder function:
4506*/
drh0c2694b2009-09-03 16:23:44 +00004507typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004508
aswiftaebf4132008-11-21 00:10:35 +00004509
drh734c9862008-11-28 15:37:20 +00004510/****************************************************************************
4511**************************** sqlite3_vfs methods ****************************
4512**
4513** This division contains the implementation of methods on the
4514** sqlite3_vfs object.
4515*/
4516
danielk1977a3d4c882007-03-23 10:08:38 +00004517/*
danielk1977e339d652008-06-28 11:23:00 +00004518** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004519*/
4520static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004521 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004522 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004523 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004524 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004525 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004526 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004527 int isDelete, /* Delete on close if true */
4528 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004529){
drh7708e972008-11-29 00:56:52 +00004530 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004531 unixFile *pNew = (unixFile *)pId;
4532 int rc = SQLITE_OK;
4533
drh8af6c222010-05-14 12:43:01 +00004534 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004535
dane946c392009-08-22 11:39:46 +00004536 /* Parameter isDelete is only used on vxworks. Express this explicitly
4537 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004538 */
drh7708e972008-11-29 00:56:52 +00004539 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004540
dan00157392010-10-05 11:33:15 +00004541 /* Usually the path zFilename should not be a relative pathname. The
4542 ** exception is when opening the proxy "conch" file in builds that
4543 ** include the special Apple locking styles.
4544 */
dan00157392010-10-05 11:33:15 +00004545#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004546 assert( zFilename==0 || zFilename[0]=='/'
4547 || pVfs->pAppData==(void*)&autolockIoFinder );
4548#else
4549 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004550#endif
dan00157392010-10-05 11:33:15 +00004551
drh308c2a52010-05-14 11:30:18 +00004552 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004553 pNew->h = h;
drhd9e5c4f2010-05-12 18:01:39 +00004554 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004555 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4556 pNew->ctrlFlags = UNIXFILE_EXCL;
4557 }else{
4558 pNew->ctrlFlags = 0;
4559 }
drh77197112011-03-15 19:08:48 +00004560 if( isReadOnly ){
4561 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4562 }
drh0059eae2011-08-08 23:48:40 +00004563 if( syncDir ){
4564 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4565 }
drh339eb0b2008-03-07 15:34:11 +00004566
drh6c7d5c52008-11-21 20:32:33 +00004567#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004568 pNew->pId = vxworksFindFileId(zFilename);
4569 if( pNew->pId==0 ){
4570 noLock = 1;
4571 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004572 }
4573#endif
4574
drhda0e7682008-07-30 15:27:54 +00004575 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004576 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004577 }else{
drh0c2694b2009-09-03 16:23:44 +00004578 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004579#if SQLITE_ENABLE_LOCKING_STYLE
4580 /* Cache zFilename in the locking context (AFP and dotlock override) for
4581 ** proxyLock activation is possible (remote proxy is based on db name)
4582 ** zFilename remains valid until file is closed, to support */
4583 pNew->lockingContext = (void*)zFilename;
4584#endif
drhda0e7682008-07-30 15:27:54 +00004585 }
danielk1977e339d652008-06-28 11:23:00 +00004586
drh7ed97b92010-01-20 13:07:21 +00004587 if( pLockingStyle == &posixIoMethods
4588#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4589 || pLockingStyle == &nfsIoMethods
4590#endif
4591 ){
drh7708e972008-11-29 00:56:52 +00004592 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004593 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004594 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004595 /* If an error occured in findInodeInfo(), close the file descriptor
4596 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004597 ** in two scenarios:
4598 **
4599 ** (a) A call to fstat() failed.
4600 ** (b) A malloc failed.
4601 **
4602 ** Scenario (b) may only occur if the process is holding no other
4603 ** file descriptors open on the same file. If there were other file
4604 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004605 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004606 ** handle h - as it is guaranteed that no posix locks will be released
4607 ** by doing so.
4608 **
4609 ** If scenario (a) caused the error then things are not so safe. The
4610 ** implicit assumption here is that if fstat() fails, things are in
4611 ** such bad shape that dropping a lock or two doesn't matter much.
4612 */
drh0e9365c2011-03-02 02:08:13 +00004613 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004614 h = -1;
4615 }
drh7708e972008-11-29 00:56:52 +00004616 unixLeaveMutex();
4617 }
danielk1977e339d652008-06-28 11:23:00 +00004618
drhd2cb50b2009-01-09 21:41:17 +00004619#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004620 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004621 /* AFP locking uses the file path so it needs to be included in
4622 ** the afpLockingContext.
4623 */
4624 afpLockingContext *pCtx;
4625 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4626 if( pCtx==0 ){
4627 rc = SQLITE_NOMEM;
4628 }else{
4629 /* NB: zFilename exists and remains valid until the file is closed
4630 ** according to requirement F11141. So we do not need to make a
4631 ** copy of the filename. */
4632 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004633 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004634 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004635 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004636 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004637 if( rc!=SQLITE_OK ){
4638 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004639 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004640 h = -1;
4641 }
drh7708e972008-11-29 00:56:52 +00004642 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004643 }
drh7708e972008-11-29 00:56:52 +00004644 }
4645#endif
danielk1977e339d652008-06-28 11:23:00 +00004646
drh7708e972008-11-29 00:56:52 +00004647 else if( pLockingStyle == &dotlockIoMethods ){
4648 /* Dotfile locking uses the file path so it needs to be included in
4649 ** the dotlockLockingContext
4650 */
4651 char *zLockFile;
4652 int nFilename;
drhea678832008-12-10 19:26:22 +00004653 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004654 zLockFile = (char *)sqlite3_malloc(nFilename);
4655 if( zLockFile==0 ){
4656 rc = SQLITE_NOMEM;
4657 }else{
4658 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004659 }
drh7708e972008-11-29 00:56:52 +00004660 pNew->lockingContext = zLockFile;
4661 }
danielk1977e339d652008-06-28 11:23:00 +00004662
drh6c7d5c52008-11-21 20:32:33 +00004663#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004664 else if( pLockingStyle == &semIoMethods ){
4665 /* Named semaphore locking uses the file path so it needs to be
4666 ** included in the semLockingContext
4667 */
4668 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004669 rc = findInodeInfo(pNew, &pNew->pInode);
4670 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4671 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004672 int n;
drh2238dcc2009-08-27 17:56:20 +00004673 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004674 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004675 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004676 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004677 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4678 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004679 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004680 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004681 }
chw97185482008-11-17 08:05:31 +00004682 }
drh7708e972008-11-29 00:56:52 +00004683 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004684 }
drh7708e972008-11-29 00:56:52 +00004685#endif
aswift5b1a2562008-08-22 00:22:35 +00004686
4687 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004688#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004689 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004690 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004691 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004692 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004693 isDelete = 0;
4694 }
4695 pNew->isDelete = isDelete;
4696#endif
danielk1977e339d652008-06-28 11:23:00 +00004697 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004698 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004699 }else{
drh7708e972008-11-29 00:56:52 +00004700 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004701 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004702 }
danielk1977e339d652008-06-28 11:23:00 +00004703 return rc;
drh054889e2005-11-30 03:20:31 +00004704}
drh9c06c952005-11-26 00:25:00 +00004705
danielk1977ad94b582007-08-20 06:44:22 +00004706/*
drh8b3cf822010-06-01 21:02:51 +00004707** Return the name of a directory in which to put temporary files.
4708** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004709*/
drh7234c6d2010-06-19 15:10:09 +00004710static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004711 static const char *azDirs[] = {
4712 0,
aswiftaebf4132008-11-21 00:10:35 +00004713 0,
danielk197717b90b52008-06-06 11:11:25 +00004714 "/var/tmp",
4715 "/usr/tmp",
4716 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004717 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004718 };
drh8b3cf822010-06-01 21:02:51 +00004719 unsigned int i;
4720 struct stat buf;
4721 const char *zDir = 0;
4722
4723 azDirs[0] = sqlite3_temp_directory;
4724 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004725 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004726 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004727 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004728 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004729 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004730 break;
4731 }
4732 return zDir;
4733}
4734
4735/*
4736** Create a temporary file name in zBuf. zBuf must be allocated
4737** by the calling process and must be big enough to hold at least
4738** pVfs->mxPathname bytes.
4739*/
4740static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004741 static const unsigned char zChars[] =
4742 "abcdefghijklmnopqrstuvwxyz"
4743 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4744 "0123456789";
drh41022642008-11-21 00:24:42 +00004745 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004746 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004747
4748 /* It's odd to simulate an io-error here, but really this is just
4749 ** using the io-error infrastructure to test that SQLite handles this
4750 ** function failing.
4751 */
4752 SimulateIOError( return SQLITE_IOERR );
4753
drh7234c6d2010-06-19 15:10:09 +00004754 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004755 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004756
4757 /* Check that the output buffer is large enough for the temporary file
4758 ** name. If it is not, return SQLITE_ERROR.
4759 */
danielk197700e13612008-11-17 19:18:54 +00004760 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004761 return SQLITE_ERROR;
4762 }
4763
4764 do{
4765 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004766 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004767 sqlite3_randomness(15, &zBuf[j]);
4768 for(i=0; i<15; i++, j++){
4769 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4770 }
4771 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004772 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004773 return SQLITE_OK;
4774}
4775
drhd2cb50b2009-01-09 21:41:17 +00004776#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004777/*
4778** Routine to transform a unixFile into a proxy-locking unixFile.
4779** Implementation in the proxy-lock division, but used by unixOpen()
4780** if SQLITE_PREFER_PROXY_LOCKING is defined.
4781*/
4782static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004783#endif
drhc66d5b62008-12-03 22:48:32 +00004784
dan08da86a2009-08-21 17:18:03 +00004785/*
4786** Search for an unused file descriptor that was opened on the database
4787** file (not a journal or master-journal file) identified by pathname
4788** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4789** argument to this function.
4790**
4791** Such a file descriptor may exist if a database connection was closed
4792** but the associated file descriptor could not be closed because some
4793** other file descriptor open on the same file is holding a file-lock.
4794** Refer to comments in the unixClose() function and the lengthy comment
4795** describing "Posix Advisory Locking" at the start of this file for
4796** further details. Also, ticket #4018.
4797**
4798** If a suitable file descriptor is found, then it is returned. If no
4799** such file descriptor is located, -1 is returned.
4800*/
dane946c392009-08-22 11:39:46 +00004801static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4802 UnixUnusedFd *pUnused = 0;
4803
4804 /* Do not search for an unused file descriptor on vxworks. Not because
4805 ** vxworks would not benefit from the change (it might, we're not sure),
4806 ** but because no way to test it is currently available. It is better
4807 ** not to risk breaking vxworks support for the sake of such an obscure
4808 ** feature. */
4809#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004810 struct stat sStat; /* Results of stat() call */
4811
4812 /* A stat() call may fail for various reasons. If this happens, it is
4813 ** almost certain that an open() call on the same path will also fail.
4814 ** For this reason, if an error occurs in the stat() call here, it is
4815 ** ignored and -1 is returned. The caller will try to open a new file
4816 ** descriptor on the same path, fail, and return an error to SQLite.
4817 **
4818 ** Even if a subsequent open() call does succeed, the consequences of
4819 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004820 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004821 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004822
4823 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004824 pInode = inodeList;
4825 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4826 || pInode->fileId.ino!=sStat.st_ino) ){
4827 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004828 }
drh8af6c222010-05-14 12:43:01 +00004829 if( pInode ){
dane946c392009-08-22 11:39:46 +00004830 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004831 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004832 pUnused = *pp;
4833 if( pUnused ){
4834 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004835 }
4836 }
4837 unixLeaveMutex();
4838 }
dane946c392009-08-22 11:39:46 +00004839#endif /* if !OS_VXWORKS */
4840 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004841}
danielk197717b90b52008-06-06 11:11:25 +00004842
4843/*
danddb0ac42010-07-14 14:48:58 +00004844** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004845** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004846** and a value suitable for passing as the third argument to open(2) is
4847** written to *pMode. If an IO error occurs, an SQLite error code is
4848** returned and the value of *pMode is not modified.
4849**
4850** If the file being opened is a temporary file, it is always created with
4851** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004852** is a database or master journal file, it is created with the permissions
4853** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004854**
drh8ab58662010-07-15 18:38:39 +00004855** Finally, if the file being opened is a WAL or regular journal file, then
4856** this function queries the file-system for the permissions on the
4857** corresponding database file and sets *pMode to this value. Whenever
4858** possible, WAL and journal files are created using the same permissions
4859** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004860**
4861** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4862** original filename is unavailable. But 8_3_NAMES is only used for
4863** FAT filesystems and permissions do not matter there, so just use
4864** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004865*/
4866static int findCreateFileMode(
4867 const char *zPath, /* Path of file (possibly) being created */
4868 int flags, /* Flags passed as 4th argument to xOpen() */
4869 mode_t *pMode /* OUT: Permissions to open file with */
4870){
4871 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004872 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004873 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004874 char zDb[MAX_PATHNAME+1]; /* Database file path */
4875 int nDb; /* Number of valid bytes in zDb */
4876 struct stat sStat; /* Output of stat() on database file */
4877
dana0c989d2010-11-05 18:07:37 +00004878 /* zPath is a path to a WAL or journal file. The following block derives
4879 ** the path to the associated database file from zPath. This block handles
4880 ** the following naming conventions:
4881 **
4882 ** "<path to db>-journal"
4883 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004884 ** "<path to db>-journalNN"
4885 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004886 **
drh81cc5162011-05-17 20:36:21 +00004887 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004888 ** used by the test_multiplex.c module.
4889 */
4890 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004891#ifdef SQLITE_ENABLE_8_3_NAMES
4892 while( nDb>0 && zPath[nDb]!='-' && zPath[nDb]!='/' ) nDb--;
4893 if( nDb==0 || zPath[nDb]=='/' ) return SQLITE_OK;
4894#else
4895 while( zPath[nDb]!='-' ){
4896 assert( nDb>0 );
4897 assert( zPath[nDb]!='\n' );
4898 nDb--;
4899 }
4900#endif
danddb0ac42010-07-14 14:48:58 +00004901 memcpy(zDb, zPath, nDb);
4902 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004903
drh58384f12011-07-28 00:14:45 +00004904 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004905 *pMode = sStat.st_mode & 0777;
4906 }else{
4907 rc = SQLITE_IOERR_FSTAT;
4908 }
4909 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4910 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004911 }
4912 return rc;
4913}
4914
4915/*
danielk1977ad94b582007-08-20 06:44:22 +00004916** Open the file zPath.
4917**
danielk1977b4b47412007-08-17 15:53:36 +00004918** Previously, the SQLite OS layer used three functions in place of this
4919** one:
4920**
4921** sqlite3OsOpenReadWrite();
4922** sqlite3OsOpenReadOnly();
4923** sqlite3OsOpenExclusive();
4924**
4925** These calls correspond to the following combinations of flags:
4926**
4927** ReadWrite() -> (READWRITE | CREATE)
4928** ReadOnly() -> (READONLY)
4929** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4930**
4931** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4932** true, the file was configured to be automatically deleted when the
4933** file handle closed. To achieve the same effect using this new
4934** interface, add the DELETEONCLOSE flag to those specified above for
4935** OpenExclusive().
4936*/
4937static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004938 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4939 const char *zPath, /* Pathname of file to be opened */
4940 sqlite3_file *pFile, /* The file descriptor to be filled in */
4941 int flags, /* Input flags to control the opening */
4942 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004943){
dan08da86a2009-08-21 17:18:03 +00004944 unixFile *p = (unixFile *)pFile;
4945 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004946 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004947 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004948 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004949 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004950
4951 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4952 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4953 int isCreate = (flags & SQLITE_OPEN_CREATE);
4954 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4955 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004956#if SQLITE_ENABLE_LOCKING_STYLE
4957 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4958#endif
drh3d4435b2011-08-26 20:55:50 +00004959#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4960 struct statfs fsInfo;
4961#endif
danielk1977b4b47412007-08-17 15:53:36 +00004962
danielk1977fee2d252007-08-18 10:59:19 +00004963 /* If creating a master or main-file journal, this function will open
4964 ** a file-descriptor on the directory too. The first time unixSync()
4965 ** is called the directory file descriptor will be fsync()ed and close()d.
4966 */
drh0059eae2011-08-08 23:48:40 +00004967 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00004968 eType==SQLITE_OPEN_MASTER_JOURNAL
4969 || eType==SQLITE_OPEN_MAIN_JOURNAL
4970 || eType==SQLITE_OPEN_WAL
4971 ));
danielk1977fee2d252007-08-18 10:59:19 +00004972
danielk197717b90b52008-06-06 11:11:25 +00004973 /* If argument zPath is a NULL pointer, this function is required to open
4974 ** a temporary file. Use this buffer to store the file name in.
4975 */
4976 char zTmpname[MAX_PATHNAME+1];
4977 const char *zName = zPath;
4978
danielk1977fee2d252007-08-18 10:59:19 +00004979 /* Check the following statements are true:
4980 **
4981 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4982 ** (b) if CREATE is set, then READWRITE must also be set, and
4983 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004984 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004985 */
danielk1977b4b47412007-08-17 15:53:36 +00004986 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004987 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004988 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004989 assert(isDelete==0 || isCreate);
4990
danddb0ac42010-07-14 14:48:58 +00004991 /* The main DB, main journal, WAL file and master journal are never
4992 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004993 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4994 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4995 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004996 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004997
danielk1977fee2d252007-08-18 10:59:19 +00004998 /* Assert that the upper layer has set one of the "file-type" flags. */
4999 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5000 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5001 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005002 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005003 );
5004
dan08da86a2009-08-21 17:18:03 +00005005 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005006
dan08da86a2009-08-21 17:18:03 +00005007 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005008 UnixUnusedFd *pUnused;
5009 pUnused = findReusableFd(zName, flags);
5010 if( pUnused ){
5011 fd = pUnused->fd;
5012 }else{
dan6aa657f2009-08-24 18:57:58 +00005013 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005014 if( !pUnused ){
5015 return SQLITE_NOMEM;
5016 }
5017 }
5018 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00005019 }else if( !zName ){
5020 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005021 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00005022 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005023 if( rc!=SQLITE_OK ){
5024 return rc;
5025 }
5026 zName = zTmpname;
5027 }
5028
dan08da86a2009-08-21 17:18:03 +00005029 /* Determine the value of the flags parameter passed to POSIX function
5030 ** open(). These must be calculated even if open() is not called, as
5031 ** they may be stored as part of the file handle and used by the
5032 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005033 if( isReadonly ) openFlags |= O_RDONLY;
5034 if( isReadWrite ) openFlags |= O_RDWR;
5035 if( isCreate ) openFlags |= O_CREAT;
5036 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5037 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005038
danielk1977b4b47412007-08-17 15:53:36 +00005039 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005040 mode_t openMode; /* Permissions to create file with */
5041 rc = findCreateFileMode(zName, flags, &openMode);
5042 if( rc!=SQLITE_OK ){
5043 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005044 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005045 return rc;
5046 }
drhad4f1e52011-03-04 15:43:57 +00005047 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005048 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005049 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5050 /* Failed to open the file for read/write access. Try read-only. */
5051 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005052 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005053 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005054 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005055 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005056 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005057 }
5058 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005059 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005060 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005061 }
danielk1977b4b47412007-08-17 15:53:36 +00005062 }
dan08da86a2009-08-21 17:18:03 +00005063 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005064 if( pOutFlags ){
5065 *pOutFlags = flags;
5066 }
5067
dane946c392009-08-22 11:39:46 +00005068 if( p->pUnused ){
5069 p->pUnused->fd = fd;
5070 p->pUnused->flags = flags;
5071 }
5072
danielk1977b4b47412007-08-17 15:53:36 +00005073 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005074#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005075 zPath = zName;
5076#else
drh036ac7f2011-08-08 23:18:05 +00005077 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005078#endif
danielk1977b4b47412007-08-17 15:53:36 +00005079 }
drh41022642008-11-21 00:24:42 +00005080#if SQLITE_ENABLE_LOCKING_STYLE
5081 else{
dan08da86a2009-08-21 17:18:03 +00005082 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005083 }
5084#endif
5085
danielk1977e339d652008-06-28 11:23:00 +00005086#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005087 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005088#endif
5089
drhda0e7682008-07-30 15:27:54 +00005090 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005091
drh7ed97b92010-01-20 13:07:21 +00005092
5093#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005094 if( fstatfs(fd, &fsInfo) == -1 ){
5095 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005096 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005097 return SQLITE_IOERR_ACCESS;
5098 }
5099 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5100 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5101 }
5102#endif
5103
5104#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005105#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005106 isAutoProxy = 1;
5107#endif
5108 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005109 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5110 int useProxy = 0;
5111
dan08da86a2009-08-21 17:18:03 +00005112 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5113 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005114 if( envforce!=NULL ){
5115 useProxy = atoi(envforce)>0;
5116 }else{
aswiftaebf4132008-11-21 00:10:35 +00005117 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005118 /* In theory, the close(fd) call is sub-optimal. If the file opened
5119 ** with fd is a database file, and there are other connections open
5120 ** on that file that are currently holding advisory locks on it,
5121 ** then the call to close() will cancel those locks. In practice,
5122 ** we're assuming that statfs() doesn't fail very often. At least
5123 ** not while other file descriptors opened by the same process on
5124 ** the same file are working. */
5125 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005126 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005127 rc = SQLITE_IOERR_ACCESS;
5128 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005129 }
5130 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5131 }
5132 if( useProxy ){
drh0059eae2011-08-08 23:48:40 +00005133 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005134 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005135 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005136 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005137 if( rc!=SQLITE_OK ){
5138 /* Use unixClose to clean up the resources added in fillInUnixFile
5139 ** and clear all the structure's references. Specifically,
5140 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5141 */
5142 unixClose(pFile);
5143 return rc;
5144 }
aswiftaebf4132008-11-21 00:10:35 +00005145 }
dane946c392009-08-22 11:39:46 +00005146 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005147 }
5148 }
5149#endif
5150
drh0059eae2011-08-08 23:48:40 +00005151 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005152 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005153open_finished:
5154 if( rc!=SQLITE_OK ){
5155 sqlite3_free(p->pUnused);
5156 }
5157 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005158}
5159
dane946c392009-08-22 11:39:46 +00005160
danielk1977b4b47412007-08-17 15:53:36 +00005161/*
danielk1977fee2d252007-08-18 10:59:19 +00005162** Delete the file at zPath. If the dirSync argument is true, fsync()
5163** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005164*/
drh6b9d6dd2008-12-03 19:34:47 +00005165static int unixDelete(
5166 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5167 const char *zPath, /* Name of file to be deleted */
5168 int dirSync /* If true, fsync() directory after deleting file */
5169){
danielk1977fee2d252007-08-18 10:59:19 +00005170 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005171 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005172 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005173 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005174 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005175 }
danielk1977d39fa702008-10-16 13:27:40 +00005176#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005177 if( dirSync ){
5178 int fd;
drh90315a22011-08-10 01:52:12 +00005179 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005180 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005181#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005182 if( fsync(fd)==-1 )
5183#else
5184 if( fsync(fd) )
5185#endif
5186 {
dane18d4952011-02-21 11:46:24 +00005187 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005188 }
drh0e9365c2011-03-02 02:08:13 +00005189 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005190 }else if( rc==SQLITE_CANTOPEN ){
5191 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005192 }
5193 }
danielk1977d138dd82008-10-15 16:02:48 +00005194#endif
danielk1977fee2d252007-08-18 10:59:19 +00005195 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005196}
5197
danielk197790949c22007-08-17 16:50:38 +00005198/*
5199** Test the existance of or access permissions of file zPath. The
5200** test performed depends on the value of flags:
5201**
5202** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5203** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5204** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5205**
5206** Otherwise return 0.
5207*/
danielk1977861f7452008-06-05 11:39:11 +00005208static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005209 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5210 const char *zPath, /* Path of the file to examine */
5211 int flags, /* What do we want to learn about the zPath file? */
5212 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005213){
rse25c0d1a2007-09-20 08:38:14 +00005214 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005215 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005216 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005217 switch( flags ){
5218 case SQLITE_ACCESS_EXISTS:
5219 amode = F_OK;
5220 break;
5221 case SQLITE_ACCESS_READWRITE:
5222 amode = W_OK|R_OK;
5223 break;
drh50d3f902007-08-27 21:10:36 +00005224 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005225 amode = R_OK;
5226 break;
5227
5228 default:
5229 assert(!"Invalid flags argument");
5230 }
drh99ab3b12011-03-02 15:09:07 +00005231 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005232 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5233 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005234 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005235 *pResOut = 0;
5236 }
5237 }
danielk1977861f7452008-06-05 11:39:11 +00005238 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005239}
5240
danielk1977b4b47412007-08-17 15:53:36 +00005241
5242/*
5243** Turn a relative pathname into a full pathname. The relative path
5244** is stored as a nul-terminated string in the buffer pointed to by
5245** zPath.
5246**
5247** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5248** (in this case, MAX_PATHNAME bytes). The full-path is written to
5249** this buffer before returning.
5250*/
danielk1977adfb9b02007-09-17 07:02:56 +00005251static int unixFullPathname(
5252 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5253 const char *zPath, /* Possibly relative input path */
5254 int nOut, /* Size of output buffer in bytes */
5255 char *zOut /* Output buffer */
5256){
danielk1977843e65f2007-09-01 16:16:15 +00005257
5258 /* It's odd to simulate an io-error here, but really this is just
5259 ** using the io-error infrastructure to test that SQLite handles this
5260 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005261 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005262 */
5263 SimulateIOError( return SQLITE_ERROR );
5264
drh153c62c2007-08-24 03:51:33 +00005265 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005266 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005267
drh3c7f2dc2007-12-06 13:26:20 +00005268 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005269 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005270 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005271 }else{
5272 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005273 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005274 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005275 }
drhea678832008-12-10 19:26:22 +00005276 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005277 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005278 }
5279 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005280}
5281
drh0ccebe72005-06-07 22:22:50 +00005282
drh761df872006-12-21 01:29:22 +00005283#ifndef SQLITE_OMIT_LOAD_EXTENSION
5284/*
5285** Interfaces for opening a shared library, finding entry points
5286** within the shared library, and closing the shared library.
5287*/
5288#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005289static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5290 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005291 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5292}
danielk197795c8a542007-09-01 06:51:27 +00005293
5294/*
5295** SQLite calls this function immediately after a call to unixDlSym() or
5296** unixDlOpen() fails (returns a null pointer). If a more detailed error
5297** message is available, it is written to zBufOut. If no error message
5298** is available, zBufOut is left unmodified and SQLite uses a default
5299** error message.
5300*/
danielk1977397d65f2008-11-19 11:35:39 +00005301static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005302 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005303 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005304 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005305 zErr = dlerror();
5306 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005307 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005308 }
drh6c7d5c52008-11-21 20:32:33 +00005309 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005310}
drh1875f7a2008-12-08 18:19:17 +00005311static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5312 /*
5313 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5314 ** cast into a pointer to a function. And yet the library dlsym() routine
5315 ** returns a void* which is really a pointer to a function. So how do we
5316 ** use dlsym() with -pedantic-errors?
5317 **
5318 ** Variable x below is defined to be a pointer to a function taking
5319 ** parameters void* and const char* and returning a pointer to a function.
5320 ** We initialize x by assigning it a pointer to the dlsym() function.
5321 ** (That assignment requires a cast.) Then we call the function that
5322 ** x points to.
5323 **
5324 ** This work-around is unlikely to work correctly on any system where
5325 ** you really cannot cast a function pointer into void*. But then, on the
5326 ** other hand, dlsym() will not work on such a system either, so we have
5327 ** not really lost anything.
5328 */
5329 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005330 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005331 x = (void(*(*)(void*,const char*))(void))dlsym;
5332 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005333}
danielk1977397d65f2008-11-19 11:35:39 +00005334static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5335 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005336 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005337}
danielk1977b4b47412007-08-17 15:53:36 +00005338#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5339 #define unixDlOpen 0
5340 #define unixDlError 0
5341 #define unixDlSym 0
5342 #define unixDlClose 0
5343#endif
5344
5345/*
danielk197790949c22007-08-17 16:50:38 +00005346** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005347*/
danielk1977397d65f2008-11-19 11:35:39 +00005348static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5349 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005350 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005351
drhbbd42a62004-05-22 17:41:58 +00005352 /* We have to initialize zBuf to prevent valgrind from reporting
5353 ** errors. The reports issued by valgrind are incorrect - we would
5354 ** prefer that the randomness be increased by making use of the
5355 ** uninitialized space in zBuf - but valgrind errors tend to worry
5356 ** some users. Rather than argue, it seems easier just to initialize
5357 ** the whole array and silence valgrind, even if that means less randomness
5358 ** in the random seed.
5359 **
5360 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005361 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005362 ** tests repeatable.
5363 */
danielk1977b4b47412007-08-17 15:53:36 +00005364 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005365#if !defined(SQLITE_TEST)
5366 {
drh842b8642005-01-21 17:53:17 +00005367 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005368 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005369 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005370 time_t t;
5371 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005372 memcpy(zBuf, &t, sizeof(t));
5373 pid = getpid();
5374 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005375 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005376 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005377 }else{
drhe562be52011-03-02 18:01:10 +00005378 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005379 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005380 }
drhbbd42a62004-05-22 17:41:58 +00005381 }
5382#endif
drh72cbd072008-10-14 17:58:38 +00005383 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005384}
5385
danielk1977b4b47412007-08-17 15:53:36 +00005386
drhbbd42a62004-05-22 17:41:58 +00005387/*
5388** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005389** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005390** The return value is the number of microseconds of sleep actually
5391** requested from the underlying operating system, a number which
5392** might be greater than or equal to the argument, but not less
5393** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005394*/
danielk1977397d65f2008-11-19 11:35:39 +00005395static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005396#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005397 struct timespec sp;
5398
5399 sp.tv_sec = microseconds / 1000000;
5400 sp.tv_nsec = (microseconds % 1000000) * 1000;
5401 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005402 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005403 return microseconds;
5404#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005405 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005406 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005407 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005408#else
danielk1977b4b47412007-08-17 15:53:36 +00005409 int seconds = (microseconds+999999)/1000000;
5410 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005411 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005412 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005413#endif
drh88f474a2006-01-02 20:00:12 +00005414}
5415
5416/*
drh6b9d6dd2008-12-03 19:34:47 +00005417** The following variable, if set to a non-zero value, is interpreted as
5418** the number of seconds since 1970 and is used to set the result of
5419** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005420*/
5421#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005422int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005423#endif
5424
5425/*
drhb7e8ea22010-05-03 14:32:30 +00005426** Find the current time (in Universal Coordinated Time). Write into *piNow
5427** the current time and date as a Julian Day number times 86_400_000. In
5428** other words, write into *piNow the number of milliseconds since the Julian
5429** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5430** proleptic Gregorian calendar.
5431**
5432** On success, return 0. Return 1 if the time and date cannot be found.
5433*/
5434static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5435 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5436#if defined(NO_GETTOD)
5437 time_t t;
5438 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005439 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005440#elif OS_VXWORKS
5441 struct timespec sNow;
5442 clock_gettime(CLOCK_REALTIME, &sNow);
5443 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5444#else
5445 struct timeval sNow;
5446 gettimeofday(&sNow, 0);
5447 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5448#endif
5449
5450#ifdef SQLITE_TEST
5451 if( sqlite3_current_time ){
5452 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5453 }
5454#endif
5455 UNUSED_PARAMETER(NotUsed);
5456 return 0;
5457}
5458
5459/*
drhbbd42a62004-05-22 17:41:58 +00005460** Find the current time (in Universal Coordinated Time). Write the
5461** current time and date as a Julian Day number into *prNow and
5462** return 0. Return 1 if the time and date cannot be found.
5463*/
danielk1977397d65f2008-11-19 11:35:39 +00005464static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005465 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005466 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005467 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005468 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005469 return 0;
5470}
danielk1977b4b47412007-08-17 15:53:36 +00005471
drh6b9d6dd2008-12-03 19:34:47 +00005472/*
5473** We added the xGetLastError() method with the intention of providing
5474** better low-level error messages when operating-system problems come up
5475** during SQLite operation. But so far, none of that has been implemented
5476** in the core. So this routine is never called. For now, it is merely
5477** a place-holder.
5478*/
danielk1977397d65f2008-11-19 11:35:39 +00005479static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5480 UNUSED_PARAMETER(NotUsed);
5481 UNUSED_PARAMETER(NotUsed2);
5482 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005483 return 0;
5484}
5485
drhf2424c52010-04-26 00:04:55 +00005486
5487/*
drh734c9862008-11-28 15:37:20 +00005488************************ End of sqlite3_vfs methods ***************************
5489******************************************************************************/
5490
drh715ff302008-12-03 22:32:44 +00005491/******************************************************************************
5492************************** Begin Proxy Locking ********************************
5493**
5494** Proxy locking is a "uber-locking-method" in this sense: It uses the
5495** other locking methods on secondary lock files. Proxy locking is a
5496** meta-layer over top of the primitive locking implemented above. For
5497** this reason, the division that implements of proxy locking is deferred
5498** until late in the file (here) after all of the other I/O methods have
5499** been defined - so that the primitive locking methods are available
5500** as services to help with the implementation of proxy locking.
5501**
5502****
5503**
5504** The default locking schemes in SQLite use byte-range locks on the
5505** database file to coordinate safe, concurrent access by multiple readers
5506** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5507** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5508** as POSIX read & write locks over fixed set of locations (via fsctl),
5509** on AFP and SMB only exclusive byte-range locks are available via fsctl
5510** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5511** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5512** address in the shared range is taken for a SHARED lock, the entire
5513** shared range is taken for an EXCLUSIVE lock):
5514**
5515** PENDING_BYTE 0x40000000
5516** RESERVED_BYTE 0x40000001
5517** SHARED_RANGE 0x40000002 -> 0x40000200
5518**
5519** This works well on the local file system, but shows a nearly 100x
5520** slowdown in read performance on AFP because the AFP client disables
5521** the read cache when byte-range locks are present. Enabling the read
5522** cache exposes a cache coherency problem that is present on all OS X
5523** supported network file systems. NFS and AFP both observe the
5524** close-to-open semantics for ensuring cache coherency
5525** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5526** address the requirements for concurrent database access by multiple
5527** readers and writers
5528** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5529**
5530** To address the performance and cache coherency issues, proxy file locking
5531** changes the way database access is controlled by limiting access to a
5532** single host at a time and moving file locks off of the database file
5533** and onto a proxy file on the local file system.
5534**
5535**
5536** Using proxy locks
5537** -----------------
5538**
5539** C APIs
5540**
5541** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5542** <proxy_path> | ":auto:");
5543** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5544**
5545**
5546** SQL pragmas
5547**
5548** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5549** PRAGMA [database.]lock_proxy_file
5550**
5551** Specifying ":auto:" means that if there is a conch file with a matching
5552** host ID in it, the proxy path in the conch file will be used, otherwise
5553** a proxy path based on the user's temp dir
5554** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5555** actual proxy file name is generated from the name and path of the
5556** database file. For example:
5557**
5558** For database path "/Users/me/foo.db"
5559** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5560**
5561** Once a lock proxy is configured for a database connection, it can not
5562** be removed, however it may be switched to a different proxy path via
5563** the above APIs (assuming the conch file is not being held by another
5564** connection or process).
5565**
5566**
5567** How proxy locking works
5568** -----------------------
5569**
5570** Proxy file locking relies primarily on two new supporting files:
5571**
5572** * conch file to limit access to the database file to a single host
5573** at a time
5574**
5575** * proxy file to act as a proxy for the advisory locks normally
5576** taken on the database
5577**
5578** The conch file - to use a proxy file, sqlite must first "hold the conch"
5579** by taking an sqlite-style shared lock on the conch file, reading the
5580** contents and comparing the host's unique host ID (see below) and lock
5581** proxy path against the values stored in the conch. The conch file is
5582** stored in the same directory as the database file and the file name
5583** is patterned after the database file name as ".<databasename>-conch".
5584** If the conch file does not exist, or it's contents do not match the
5585** host ID and/or proxy path, then the lock is escalated to an exclusive
5586** lock and the conch file contents is updated with the host ID and proxy
5587** path and the lock is downgraded to a shared lock again. If the conch
5588** is held by another process (with a shared lock), the exclusive lock
5589** will fail and SQLITE_BUSY is returned.
5590**
5591** The proxy file - a single-byte file used for all advisory file locks
5592** normally taken on the database file. This allows for safe sharing
5593** of the database file for multiple readers and writers on the same
5594** host (the conch ensures that they all use the same local lock file).
5595**
drh715ff302008-12-03 22:32:44 +00005596** Requesting the lock proxy does not immediately take the conch, it is
5597** only taken when the first request to lock database file is made.
5598** This matches the semantics of the traditional locking behavior, where
5599** opening a connection to a database file does not take a lock on it.
5600** The shared lock and an open file descriptor are maintained until
5601** the connection to the database is closed.
5602**
5603** The proxy file and the lock file are never deleted so they only need
5604** to be created the first time they are used.
5605**
5606** Configuration options
5607** ---------------------
5608**
5609** SQLITE_PREFER_PROXY_LOCKING
5610**
5611** Database files accessed on non-local file systems are
5612** automatically configured for proxy locking, lock files are
5613** named automatically using the same logic as
5614** PRAGMA lock_proxy_file=":auto:"
5615**
5616** SQLITE_PROXY_DEBUG
5617**
5618** Enables the logging of error messages during host id file
5619** retrieval and creation
5620**
drh715ff302008-12-03 22:32:44 +00005621** LOCKPROXYDIR
5622**
5623** Overrides the default directory used for lock proxy files that
5624** are named automatically via the ":auto:" setting
5625**
5626** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5627**
5628** Permissions to use when creating a directory for storing the
5629** lock proxy files, only used when LOCKPROXYDIR is not set.
5630**
5631**
5632** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5633** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5634** force proxy locking to be used for every database file opened, and 0
5635** will force automatic proxy locking to be disabled for all database
5636** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5637** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5638*/
5639
5640/*
5641** Proxy locking is only available on MacOSX
5642*/
drhd2cb50b2009-01-09 21:41:17 +00005643#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005644
drh715ff302008-12-03 22:32:44 +00005645/*
5646** The proxyLockingContext has the path and file structures for the remote
5647** and local proxy files in it
5648*/
5649typedef struct proxyLockingContext proxyLockingContext;
5650struct proxyLockingContext {
5651 unixFile *conchFile; /* Open conch file */
5652 char *conchFilePath; /* Name of the conch file */
5653 unixFile *lockProxy; /* Open proxy lock file */
5654 char *lockProxyPath; /* Name of the proxy lock file */
5655 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005656 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005657 void *oldLockingContext; /* Original lockingcontext to restore on close */
5658 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5659};
5660
drh7ed97b92010-01-20 13:07:21 +00005661/*
5662** The proxy lock file path for the database at dbPath is written into lPath,
5663** which must point to valid, writable memory large enough for a maxLen length
5664** file path.
drh715ff302008-12-03 22:32:44 +00005665*/
drh715ff302008-12-03 22:32:44 +00005666static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5667 int len;
5668 int dbLen;
5669 int i;
5670
5671#ifdef LOCKPROXYDIR
5672 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5673#else
5674# ifdef _CS_DARWIN_USER_TEMP_DIR
5675 {
drh7ed97b92010-01-20 13:07:21 +00005676 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005677 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5678 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005679 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005680 }
drh7ed97b92010-01-20 13:07:21 +00005681 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005682 }
5683# else
5684 len = strlcpy(lPath, "/tmp/", maxLen);
5685# endif
5686#endif
5687
5688 if( lPath[len-1]!='/' ){
5689 len = strlcat(lPath, "/", maxLen);
5690 }
5691
5692 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005693 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005694 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005695 char c = dbPath[i];
5696 lPath[i+len] = (c=='/')?'_':c;
5697 }
5698 lPath[i+len]='\0';
5699 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005700 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005701 return SQLITE_OK;
5702}
5703
drh7ed97b92010-01-20 13:07:21 +00005704/*
5705 ** Creates the lock file and any missing directories in lockPath
5706 */
5707static int proxyCreateLockPath(const char *lockPath){
5708 int i, len;
5709 char buf[MAXPATHLEN];
5710 int start = 0;
5711
5712 assert(lockPath!=NULL);
5713 /* try to create all the intermediate directories */
5714 len = (int)strlen(lockPath);
5715 buf[0] = lockPath[0];
5716 for( i=1; i<len; i++ ){
5717 if( lockPath[i] == '/' && (i - start > 0) ){
5718 /* only mkdir if leaf dir != "." or "/" or ".." */
5719 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5720 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5721 buf[i]='\0';
5722 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5723 int err=errno;
5724 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005725 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005726 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005727 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005728 return err;
5729 }
5730 }
5731 }
5732 start=i+1;
5733 }
5734 buf[i] = lockPath[i];
5735 }
drh308c2a52010-05-14 11:30:18 +00005736 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005737 return 0;
5738}
5739
drh715ff302008-12-03 22:32:44 +00005740/*
5741** Create a new VFS file descriptor (stored in memory obtained from
5742** sqlite3_malloc) and open the file named "path" in the file descriptor.
5743**
5744** The caller is responsible not only for closing the file descriptor
5745** but also for freeing the memory associated with the file descriptor.
5746*/
drh7ed97b92010-01-20 13:07:21 +00005747static int proxyCreateUnixFile(
5748 const char *path, /* path for the new unixFile */
5749 unixFile **ppFile, /* unixFile created and returned by ref */
5750 int islockfile /* if non zero missing dirs will be created */
5751) {
5752 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005753 unixFile *pNew;
5754 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005755 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005756 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005757 int terrno = 0;
5758 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005759
drh7ed97b92010-01-20 13:07:21 +00005760 /* 1. first try to open/create the file
5761 ** 2. if that fails, and this is a lock file (not-conch), try creating
5762 ** the parent directories and then try again.
5763 ** 3. if that fails, try to open the file read-only
5764 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5765 */
5766 pUnused = findReusableFd(path, openFlags);
5767 if( pUnused ){
5768 fd = pUnused->fd;
5769 }else{
5770 pUnused = sqlite3_malloc(sizeof(*pUnused));
5771 if( !pUnused ){
5772 return SQLITE_NOMEM;
5773 }
5774 }
5775 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005776 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005777 terrno = errno;
5778 if( fd<0 && errno==ENOENT && islockfile ){
5779 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005780 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005781 }
5782 }
5783 }
5784 if( fd<0 ){
5785 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005786 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005787 terrno = errno;
5788 }
5789 if( fd<0 ){
5790 if( islockfile ){
5791 return SQLITE_BUSY;
5792 }
5793 switch (terrno) {
5794 case EACCES:
5795 return SQLITE_PERM;
5796 case EIO:
5797 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5798 default:
drh9978c972010-02-23 17:36:32 +00005799 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005800 }
5801 }
5802
5803 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5804 if( pNew==NULL ){
5805 rc = SQLITE_NOMEM;
5806 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005807 }
5808 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005809 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005810 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005811 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005812 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005813 pUnused->fd = fd;
5814 pUnused->flags = openFlags;
5815 pNew->pUnused = pUnused;
5816
drh0059eae2011-08-08 23:48:40 +00005817 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005818 if( rc==SQLITE_OK ){
5819 *ppFile = pNew;
5820 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005821 }
drh7ed97b92010-01-20 13:07:21 +00005822end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005823 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005824 sqlite3_free(pNew);
5825 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005826 return rc;
5827}
5828
drh7ed97b92010-01-20 13:07:21 +00005829#ifdef SQLITE_TEST
5830/* simulate multiple hosts by creating unique hostid file paths */
5831int sqlite3_hostid_num = 0;
5832#endif
5833
5834#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5835
drh0ab216a2010-07-02 17:10:40 +00005836/* Not always defined in the headers as it ought to be */
5837extern int gethostuuid(uuid_t id, const struct timespec *wait);
5838
drh7ed97b92010-01-20 13:07:21 +00005839/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5840** bytes of writable memory.
5841*/
5842static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005843 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5844 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005845#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5846 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005847 {
5848 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5849 if( gethostuuid(pHostID, &timeout) ){
5850 int err = errno;
5851 if( pError ){
5852 *pError = err;
5853 }
5854 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005855 }
drh7ed97b92010-01-20 13:07:21 +00005856 }
drh3d4435b2011-08-26 20:55:50 +00005857#else
5858 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005859#endif
drh7ed97b92010-01-20 13:07:21 +00005860#ifdef SQLITE_TEST
5861 /* simulate multiple hosts by creating unique hostid file paths */
5862 if( sqlite3_hostid_num != 0){
5863 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5864 }
5865#endif
5866
5867 return SQLITE_OK;
5868}
5869
5870/* The conch file contains the header, host id and lock file path
5871 */
5872#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5873#define PROXY_HEADERLEN 1 /* conch file header length */
5874#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5875#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5876
5877/*
5878** Takes an open conch file, copies the contents to a new path and then moves
5879** it back. The newly created file's file descriptor is assigned to the
5880** conch file structure and finally the original conch file descriptor is
5881** closed. Returns zero if successful.
5882*/
5883static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5884 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5885 unixFile *conchFile = pCtx->conchFile;
5886 char tPath[MAXPATHLEN];
5887 char buf[PROXY_MAXCONCHLEN];
5888 char *cPath = pCtx->conchFilePath;
5889 size_t readLen = 0;
5890 size_t pathLen = 0;
5891 char errmsg[64] = "";
5892 int fd = -1;
5893 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005894 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005895
5896 /* create a new path by replace the trailing '-conch' with '-break' */
5897 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5898 if( pathLen>MAXPATHLEN || pathLen<6 ||
5899 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005900 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005901 goto end_breaklock;
5902 }
5903 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005904 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005905 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005906 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005907 goto end_breaklock;
5908 }
5909 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005910 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5911 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005912 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005913 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005914 goto end_breaklock;
5915 }
drhe562be52011-03-02 18:01:10 +00005916 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005917 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005918 goto end_breaklock;
5919 }
5920 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005921 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005922 goto end_breaklock;
5923 }
5924 rc = 0;
5925 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005926 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005927 conchFile->h = fd;
5928 conchFile->openFlags = O_RDWR | O_CREAT;
5929
5930end_breaklock:
5931 if( rc ){
5932 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005933 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005934 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005935 }
5936 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5937 }
5938 return rc;
5939}
5940
5941/* Take the requested lock on the conch file and break a stale lock if the
5942** host id matches.
5943*/
5944static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5945 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5946 unixFile *conchFile = pCtx->conchFile;
5947 int rc = SQLITE_OK;
5948 int nTries = 0;
5949 struct timespec conchModTime;
5950
drh3d4435b2011-08-26 20:55:50 +00005951 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00005952 do {
5953 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5954 nTries ++;
5955 if( rc==SQLITE_BUSY ){
5956 /* If the lock failed (busy):
5957 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5958 * 2nd try: fail if the mod time changed or host id is different, wait
5959 * 10 sec and try again
5960 * 3rd try: break the lock unless the mod time has changed.
5961 */
5962 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005963 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005964 pFile->lastErrno = errno;
5965 return SQLITE_IOERR_LOCK;
5966 }
5967
5968 if( nTries==1 ){
5969 conchModTime = buf.st_mtimespec;
5970 usleep(500000); /* wait 0.5 sec and try the lock again*/
5971 continue;
5972 }
5973
5974 assert( nTries>1 );
5975 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5976 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5977 return SQLITE_BUSY;
5978 }
5979
5980 if( nTries==2 ){
5981 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005982 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005983 if( len<0 ){
5984 pFile->lastErrno = errno;
5985 return SQLITE_IOERR_LOCK;
5986 }
5987 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5988 /* don't break the lock if the host id doesn't match */
5989 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5990 return SQLITE_BUSY;
5991 }
5992 }else{
5993 /* don't break the lock on short read or a version mismatch */
5994 return SQLITE_BUSY;
5995 }
5996 usleep(10000000); /* wait 10 sec and try the lock again */
5997 continue;
5998 }
5999
6000 assert( nTries==3 );
6001 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6002 rc = SQLITE_OK;
6003 if( lockType==EXCLUSIVE_LOCK ){
6004 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6005 }
6006 if( !rc ){
6007 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6008 }
6009 }
6010 }
6011 } while( rc==SQLITE_BUSY && nTries<3 );
6012
6013 return rc;
6014}
6015
6016/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006017** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6018** lockPath means that the lockPath in the conch file will be used if the
6019** host IDs match, or a new lock path will be generated automatically
6020** and written to the conch file.
6021*/
6022static int proxyTakeConch(unixFile *pFile){
6023 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6024
drh7ed97b92010-01-20 13:07:21 +00006025 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006026 return SQLITE_OK;
6027 }else{
6028 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006029 uuid_t myHostID;
6030 int pError = 0;
6031 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006032 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006033 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006034 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006035 int createConch = 0;
6036 int hostIdMatch = 0;
6037 int readLen = 0;
6038 int tryOldLockPath = 0;
6039 int forceNewLockPath = 0;
6040
drh308c2a52010-05-14 11:30:18 +00006041 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6042 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006043
drh7ed97b92010-01-20 13:07:21 +00006044 rc = proxyGetHostID(myHostID, &pError);
6045 if( (rc&0xff)==SQLITE_IOERR ){
6046 pFile->lastErrno = pError;
6047 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006048 }
drh7ed97b92010-01-20 13:07:21 +00006049 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006050 if( rc!=SQLITE_OK ){
6051 goto end_takeconch;
6052 }
drh7ed97b92010-01-20 13:07:21 +00006053 /* read the existing conch file */
6054 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6055 if( readLen<0 ){
6056 /* I/O error: lastErrno set by seekAndRead */
6057 pFile->lastErrno = conchFile->lastErrno;
6058 rc = SQLITE_IOERR_READ;
6059 goto end_takeconch;
6060 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6061 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6062 /* a short read or version format mismatch means we need to create a new
6063 ** conch file.
6064 */
6065 createConch = 1;
6066 }
6067 /* if the host id matches and the lock path already exists in the conch
6068 ** we'll try to use the path there, if we can't open that path, we'll
6069 ** retry with a new auto-generated path
6070 */
6071 do { /* in case we need to try again for an :auto: named lock file */
6072
6073 if( !createConch && !forceNewLockPath ){
6074 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6075 PROXY_HOSTIDLEN);
6076 /* if the conch has data compare the contents */
6077 if( !pCtx->lockProxyPath ){
6078 /* for auto-named local lock file, just check the host ID and we'll
6079 ** use the local lock file path that's already in there
6080 */
6081 if( hostIdMatch ){
6082 size_t pathLen = (readLen - PROXY_PATHINDEX);
6083
6084 if( pathLen>=MAXPATHLEN ){
6085 pathLen=MAXPATHLEN-1;
6086 }
6087 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6088 lockPath[pathLen] = 0;
6089 tempLockPath = lockPath;
6090 tryOldLockPath = 1;
6091 /* create a copy of the lock path if the conch is taken */
6092 goto end_takeconch;
6093 }
6094 }else if( hostIdMatch
6095 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6096 readLen-PROXY_PATHINDEX)
6097 ){
6098 /* conch host and lock path match */
6099 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006100 }
drh7ed97b92010-01-20 13:07:21 +00006101 }
6102
6103 /* if the conch isn't writable and doesn't match, we can't take it */
6104 if( (conchFile->openFlags&O_RDWR) == 0 ){
6105 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006106 goto end_takeconch;
6107 }
drh7ed97b92010-01-20 13:07:21 +00006108
6109 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006110 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006111 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6112 tempLockPath = lockPath;
6113 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006114 }
drh7ed97b92010-01-20 13:07:21 +00006115
6116 /* update conch with host and path (this will fail if other process
6117 ** has a shared lock already), if the host id matches, use the big
6118 ** stick.
drh715ff302008-12-03 22:32:44 +00006119 */
drh7ed97b92010-01-20 13:07:21 +00006120 futimes(conchFile->h, NULL);
6121 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006122 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006123 /* We are trying for an exclusive lock but another thread in this
6124 ** same process is still holding a shared lock. */
6125 rc = SQLITE_BUSY;
6126 } else {
6127 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006128 }
drh715ff302008-12-03 22:32:44 +00006129 }else{
drh7ed97b92010-01-20 13:07:21 +00006130 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006131 }
drh7ed97b92010-01-20 13:07:21 +00006132 if( rc==SQLITE_OK ){
6133 char writeBuffer[PROXY_MAXCONCHLEN];
6134 int writeSize = 0;
6135
6136 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6137 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6138 if( pCtx->lockProxyPath!=NULL ){
6139 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6140 }else{
6141 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6142 }
6143 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006144 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006145 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6146 fsync(conchFile->h);
6147 /* If we created a new conch file (not just updated the contents of a
6148 ** valid conch file), try to match the permissions of the database
6149 */
6150 if( rc==SQLITE_OK && createConch ){
6151 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006152 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006153 if( err==0 ){
6154 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6155 S_IROTH|S_IWOTH);
6156 /* try to match the database file R/W permissions, ignore failure */
6157#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006158 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006159#else
drhff812312011-02-23 13:33:46 +00006160 do{
drhe562be52011-03-02 18:01:10 +00006161 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006162 }while( rc==(-1) && errno==EINTR );
6163 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006164 int code = errno;
6165 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6166 cmode, code, strerror(code));
6167 } else {
6168 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6169 }
6170 }else{
6171 int code = errno;
6172 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6173 err, code, strerror(code));
6174#endif
6175 }
drh715ff302008-12-03 22:32:44 +00006176 }
6177 }
drh7ed97b92010-01-20 13:07:21 +00006178 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6179
6180 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006181 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006182 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006183 int fd;
drh7ed97b92010-01-20 13:07:21 +00006184 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006185 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006186 }
6187 pFile->h = -1;
drh3d4435b2011-08-26 20:55:50 +00006188 fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006189 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006190 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006191 if( fd>=0 ){
6192 pFile->h = fd;
6193 }else{
drh9978c972010-02-23 17:36:32 +00006194 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006195 during locking */
6196 }
6197 }
6198 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6199 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6200 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6201 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6202 /* we couldn't create the proxy lock file with the old lock file path
6203 ** so try again via auto-naming
6204 */
6205 forceNewLockPath = 1;
6206 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006207 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006208 }
6209 }
6210 if( rc==SQLITE_OK ){
6211 /* Need to make a copy of path if we extracted the value
6212 ** from the conch file or the path was allocated on the stack
6213 */
6214 if( tempLockPath ){
6215 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6216 if( !pCtx->lockProxyPath ){
6217 rc = SQLITE_NOMEM;
6218 }
6219 }
6220 }
6221 if( rc==SQLITE_OK ){
6222 pCtx->conchHeld = 1;
6223
6224 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6225 afpLockingContext *afpCtx;
6226 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6227 afpCtx->dbPath = pCtx->lockProxyPath;
6228 }
6229 } else {
6230 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6231 }
drh308c2a52010-05-14 11:30:18 +00006232 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6233 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006234 return rc;
drh308c2a52010-05-14 11:30:18 +00006235 } while (1); /* in case we need to retry the :auto: lock file -
6236 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006237 }
6238}
6239
6240/*
6241** If pFile holds a lock on a conch file, then release that lock.
6242*/
6243static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006244 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006245 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6246 unixFile *conchFile; /* Name of the conch file */
6247
6248 pCtx = (proxyLockingContext *)pFile->lockingContext;
6249 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006250 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006251 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006252 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006253 if( pCtx->conchHeld>0 ){
6254 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6255 }
drh715ff302008-12-03 22:32:44 +00006256 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006257 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6258 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006259 return rc;
6260}
6261
6262/*
6263** Given the name of a database file, compute the name of its conch file.
6264** Store the conch filename in memory obtained from sqlite3_malloc().
6265** Make *pConchPath point to the new name. Return SQLITE_OK on success
6266** or SQLITE_NOMEM if unable to obtain memory.
6267**
6268** The caller is responsible for ensuring that the allocated memory
6269** space is eventually freed.
6270**
6271** *pConchPath is set to NULL if a memory allocation error occurs.
6272*/
6273static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6274 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006275 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006276 char *conchPath; /* buffer in which to construct conch name */
6277
6278 /* Allocate space for the conch filename and initialize the name to
6279 ** the name of the original database file. */
6280 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6281 if( conchPath==0 ){
6282 return SQLITE_NOMEM;
6283 }
6284 memcpy(conchPath, dbPath, len+1);
6285
6286 /* now insert a "." before the last / character */
6287 for( i=(len-1); i>=0; i-- ){
6288 if( conchPath[i]=='/' ){
6289 i++;
6290 break;
6291 }
6292 }
6293 conchPath[i]='.';
6294 while ( i<len ){
6295 conchPath[i+1]=dbPath[i];
6296 i++;
6297 }
6298
6299 /* append the "-conch" suffix to the file */
6300 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006301 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006302
6303 return SQLITE_OK;
6304}
6305
6306
6307/* Takes a fully configured proxy locking-style unix file and switches
6308** the local lock file path
6309*/
6310static int switchLockProxyPath(unixFile *pFile, const char *path) {
6311 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6312 char *oldPath = pCtx->lockProxyPath;
6313 int rc = SQLITE_OK;
6314
drh308c2a52010-05-14 11:30:18 +00006315 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006316 return SQLITE_BUSY;
6317 }
6318
6319 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6320 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6321 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6322 return SQLITE_OK;
6323 }else{
6324 unixFile *lockProxy = pCtx->lockProxy;
6325 pCtx->lockProxy=NULL;
6326 pCtx->conchHeld = 0;
6327 if( lockProxy!=NULL ){
6328 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6329 if( rc ) return rc;
6330 sqlite3_free(lockProxy);
6331 }
6332 sqlite3_free(oldPath);
6333 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6334 }
6335
6336 return rc;
6337}
6338
6339/*
6340** pFile is a file that has been opened by a prior xOpen call. dbPath
6341** is a string buffer at least MAXPATHLEN+1 characters in size.
6342**
6343** This routine find the filename associated with pFile and writes it
6344** int dbPath.
6345*/
6346static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006347#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006348 if( pFile->pMethod == &afpIoMethods ){
6349 /* afp style keeps a reference to the db path in the filePath field
6350 ** of the struct */
drhea678832008-12-10 19:26:22 +00006351 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006352 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6353 } else
drh715ff302008-12-03 22:32:44 +00006354#endif
6355 if( pFile->pMethod == &dotlockIoMethods ){
6356 /* dot lock style uses the locking context to store the dot lock
6357 ** file path */
6358 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6359 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6360 }else{
6361 /* all other styles use the locking context to store the db file path */
6362 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006363 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006364 }
6365 return SQLITE_OK;
6366}
6367
6368/*
6369** Takes an already filled in unix file and alters it so all file locking
6370** will be performed on the local proxy lock file. The following fields
6371** are preserved in the locking context so that they can be restored and
6372** the unix structure properly cleaned up at close time:
6373** ->lockingContext
6374** ->pMethod
6375*/
6376static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6377 proxyLockingContext *pCtx;
6378 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6379 char *lockPath=NULL;
6380 int rc = SQLITE_OK;
6381
drh308c2a52010-05-14 11:30:18 +00006382 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006383 return SQLITE_BUSY;
6384 }
6385 proxyGetDbPathForUnixFile(pFile, dbPath);
6386 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6387 lockPath=NULL;
6388 }else{
6389 lockPath=(char *)path;
6390 }
6391
drh308c2a52010-05-14 11:30:18 +00006392 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6393 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006394
6395 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6396 if( pCtx==0 ){
6397 return SQLITE_NOMEM;
6398 }
6399 memset(pCtx, 0, sizeof(*pCtx));
6400
6401 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6402 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006403 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6404 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6405 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6406 ** (c) the file system is read-only, then enable no-locking access.
6407 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6408 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6409 */
6410 struct statfs fsInfo;
6411 struct stat conchInfo;
6412 int goLockless = 0;
6413
drh99ab3b12011-03-02 15:09:07 +00006414 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006415 int err = errno;
6416 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6417 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6418 }
6419 }
6420 if( goLockless ){
6421 pCtx->conchHeld = -1; /* read only FS/ lockless */
6422 rc = SQLITE_OK;
6423 }
6424 }
drh715ff302008-12-03 22:32:44 +00006425 }
6426 if( rc==SQLITE_OK && lockPath ){
6427 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6428 }
6429
6430 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006431 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6432 if( pCtx->dbPath==NULL ){
6433 rc = SQLITE_NOMEM;
6434 }
6435 }
6436 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006437 /* all memory is allocated, proxys are created and assigned,
6438 ** switch the locking context and pMethod then return.
6439 */
drh715ff302008-12-03 22:32:44 +00006440 pCtx->oldLockingContext = pFile->lockingContext;
6441 pFile->lockingContext = pCtx;
6442 pCtx->pOldMethod = pFile->pMethod;
6443 pFile->pMethod = &proxyIoMethods;
6444 }else{
6445 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006446 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006447 sqlite3_free(pCtx->conchFile);
6448 }
drhd56b1212010-08-11 06:14:15 +00006449 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006450 sqlite3_free(pCtx->conchFilePath);
6451 sqlite3_free(pCtx);
6452 }
drh308c2a52010-05-14 11:30:18 +00006453 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6454 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006455 return rc;
6456}
6457
6458
6459/*
6460** This routine handles sqlite3_file_control() calls that are specific
6461** to proxy locking.
6462*/
6463static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6464 switch( op ){
6465 case SQLITE_GET_LOCKPROXYFILE: {
6466 unixFile *pFile = (unixFile*)id;
6467 if( pFile->pMethod == &proxyIoMethods ){
6468 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6469 proxyTakeConch(pFile);
6470 if( pCtx->lockProxyPath ){
6471 *(const char **)pArg = pCtx->lockProxyPath;
6472 }else{
6473 *(const char **)pArg = ":auto: (not held)";
6474 }
6475 } else {
6476 *(const char **)pArg = NULL;
6477 }
6478 return SQLITE_OK;
6479 }
6480 case SQLITE_SET_LOCKPROXYFILE: {
6481 unixFile *pFile = (unixFile*)id;
6482 int rc = SQLITE_OK;
6483 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6484 if( pArg==NULL || (const char *)pArg==0 ){
6485 if( isProxyStyle ){
6486 /* turn off proxy locking - not supported */
6487 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6488 }else{
6489 /* turn off proxy locking - already off - NOOP */
6490 rc = SQLITE_OK;
6491 }
6492 }else{
6493 const char *proxyPath = (const char *)pArg;
6494 if( isProxyStyle ){
6495 proxyLockingContext *pCtx =
6496 (proxyLockingContext*)pFile->lockingContext;
6497 if( !strcmp(pArg, ":auto:")
6498 || (pCtx->lockProxyPath &&
6499 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6500 ){
6501 rc = SQLITE_OK;
6502 }else{
6503 rc = switchLockProxyPath(pFile, proxyPath);
6504 }
6505 }else{
6506 /* turn on proxy file locking */
6507 rc = proxyTransformUnixFile(pFile, proxyPath);
6508 }
6509 }
6510 return rc;
6511 }
6512 default: {
6513 assert( 0 ); /* The call assures that only valid opcodes are sent */
6514 }
6515 }
6516 /*NOTREACHED*/
6517 return SQLITE_ERROR;
6518}
6519
6520/*
6521** Within this division (the proxying locking implementation) the procedures
6522** above this point are all utilities. The lock-related methods of the
6523** proxy-locking sqlite3_io_method object follow.
6524*/
6525
6526
6527/*
6528** This routine checks if there is a RESERVED lock held on the specified
6529** file by this or any other process. If such a lock is held, set *pResOut
6530** to a non-zero value otherwise *pResOut is set to zero. The return value
6531** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6532*/
6533static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6534 unixFile *pFile = (unixFile*)id;
6535 int rc = proxyTakeConch(pFile);
6536 if( rc==SQLITE_OK ){
6537 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006538 if( pCtx->conchHeld>0 ){
6539 unixFile *proxy = pCtx->lockProxy;
6540 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6541 }else{ /* conchHeld < 0 is lockless */
6542 pResOut=0;
6543 }
drh715ff302008-12-03 22:32:44 +00006544 }
6545 return rc;
6546}
6547
6548/*
drh308c2a52010-05-14 11:30:18 +00006549** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006550** of the following:
6551**
6552** (1) SHARED_LOCK
6553** (2) RESERVED_LOCK
6554** (3) PENDING_LOCK
6555** (4) EXCLUSIVE_LOCK
6556**
6557** Sometimes when requesting one lock state, additional lock states
6558** are inserted in between. The locking might fail on one of the later
6559** transitions leaving the lock state different from what it started but
6560** still short of its goal. The following chart shows the allowed
6561** transitions and the inserted intermediate states:
6562**
6563** UNLOCKED -> SHARED
6564** SHARED -> RESERVED
6565** SHARED -> (PENDING) -> EXCLUSIVE
6566** RESERVED -> (PENDING) -> EXCLUSIVE
6567** PENDING -> EXCLUSIVE
6568**
6569** This routine will only increase a lock. Use the sqlite3OsUnlock()
6570** routine to lower a locking level.
6571*/
drh308c2a52010-05-14 11:30:18 +00006572static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006573 unixFile *pFile = (unixFile*)id;
6574 int rc = proxyTakeConch(pFile);
6575 if( rc==SQLITE_OK ){
6576 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006577 if( pCtx->conchHeld>0 ){
6578 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006579 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6580 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006581 }else{
6582 /* conchHeld < 0 is lockless */
6583 }
drh715ff302008-12-03 22:32:44 +00006584 }
6585 return rc;
6586}
6587
6588
6589/*
drh308c2a52010-05-14 11:30:18 +00006590** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006591** must be either NO_LOCK or SHARED_LOCK.
6592**
6593** If the locking level of the file descriptor is already at or below
6594** the requested locking level, this routine is a no-op.
6595*/
drh308c2a52010-05-14 11:30:18 +00006596static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006597 unixFile *pFile = (unixFile*)id;
6598 int rc = proxyTakeConch(pFile);
6599 if( rc==SQLITE_OK ){
6600 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006601 if( pCtx->conchHeld>0 ){
6602 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006603 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6604 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006605 }else{
6606 /* conchHeld < 0 is lockless */
6607 }
drh715ff302008-12-03 22:32:44 +00006608 }
6609 return rc;
6610}
6611
6612/*
6613** Close a file that uses proxy locks.
6614*/
6615static int proxyClose(sqlite3_file *id) {
6616 if( id ){
6617 unixFile *pFile = (unixFile*)id;
6618 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6619 unixFile *lockProxy = pCtx->lockProxy;
6620 unixFile *conchFile = pCtx->conchFile;
6621 int rc = SQLITE_OK;
6622
6623 if( lockProxy ){
6624 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6625 if( rc ) return rc;
6626 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6627 if( rc ) return rc;
6628 sqlite3_free(lockProxy);
6629 pCtx->lockProxy = 0;
6630 }
6631 if( conchFile ){
6632 if( pCtx->conchHeld ){
6633 rc = proxyReleaseConch(pFile);
6634 if( rc ) return rc;
6635 }
6636 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6637 if( rc ) return rc;
6638 sqlite3_free(conchFile);
6639 }
drhd56b1212010-08-11 06:14:15 +00006640 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006641 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006642 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006643 /* restore the original locking context and pMethod then close it */
6644 pFile->lockingContext = pCtx->oldLockingContext;
6645 pFile->pMethod = pCtx->pOldMethod;
6646 sqlite3_free(pCtx);
6647 return pFile->pMethod->xClose(id);
6648 }
6649 return SQLITE_OK;
6650}
6651
6652
6653
drhd2cb50b2009-01-09 21:41:17 +00006654#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006655/*
6656** The proxy locking style is intended for use with AFP filesystems.
6657** And since AFP is only supported on MacOSX, the proxy locking is also
6658** restricted to MacOSX.
6659**
6660**
6661******************* End of the proxy lock implementation **********************
6662******************************************************************************/
6663
drh734c9862008-11-28 15:37:20 +00006664/*
danielk1977e339d652008-06-28 11:23:00 +00006665** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006666**
6667** This routine registers all VFS implementations for unix-like operating
6668** systems. This routine, and the sqlite3_os_end() routine that follows,
6669** should be the only routines in this file that are visible from other
6670** files.
drh6b9d6dd2008-12-03 19:34:47 +00006671**
6672** This routine is called once during SQLite initialization and by a
6673** single thread. The memory allocation and mutex subsystems have not
6674** necessarily been initialized when this routine is called, and so they
6675** should not be used.
drh153c62c2007-08-24 03:51:33 +00006676*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006677int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006678 /*
6679 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006680 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6681 ** to the "finder" function. (pAppData is a pointer to a pointer because
6682 ** silly C90 rules prohibit a void* from being cast to a function pointer
6683 ** and so we have to go through the intermediate pointer to avoid problems
6684 ** when compiling with -pedantic-errors on GCC.)
6685 **
6686 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006687 ** finder-function. The finder-function returns a pointer to the
6688 ** sqlite_io_methods object that implements the desired locking
6689 ** behaviors. See the division above that contains the IOMETHODS
6690 ** macro for addition information on finder-functions.
6691 **
6692 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6693 ** object. But the "autolockIoFinder" available on MacOSX does a little
6694 ** more than that; it looks at the filesystem type that hosts the
6695 ** database file and tries to choose an locking method appropriate for
6696 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006697 */
drh7708e972008-11-29 00:56:52 +00006698 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006699 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006700 sizeof(unixFile), /* szOsFile */ \
6701 MAX_PATHNAME, /* mxPathname */ \
6702 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006703 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006704 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006705 unixOpen, /* xOpen */ \
6706 unixDelete, /* xDelete */ \
6707 unixAccess, /* xAccess */ \
6708 unixFullPathname, /* xFullPathname */ \
6709 unixDlOpen, /* xDlOpen */ \
6710 unixDlError, /* xDlError */ \
6711 unixDlSym, /* xDlSym */ \
6712 unixDlClose, /* xDlClose */ \
6713 unixRandomness, /* xRandomness */ \
6714 unixSleep, /* xSleep */ \
6715 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006716 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006717 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006718 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006719 unixGetSystemCall, /* xGetSystemCall */ \
6720 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006721 }
6722
drh6b9d6dd2008-12-03 19:34:47 +00006723 /*
6724 ** All default VFSes for unix are contained in the following array.
6725 **
6726 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6727 ** by the SQLite core when the VFS is registered. So the following
6728 ** array cannot be const.
6729 */
danielk1977e339d652008-06-28 11:23:00 +00006730 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006731#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006732 UNIXVFS("unix", autolockIoFinder ),
6733#else
6734 UNIXVFS("unix", posixIoFinder ),
6735#endif
6736 UNIXVFS("unix-none", nolockIoFinder ),
6737 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006738 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006739#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006740 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006741#endif
6742#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006743 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006744#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006745 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006746#endif
chw78a13182009-04-07 05:35:03 +00006747#endif
drhd2cb50b2009-01-09 21:41:17 +00006748#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006749 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006750 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006751 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006752#endif
drh153c62c2007-08-24 03:51:33 +00006753 };
drh6b9d6dd2008-12-03 19:34:47 +00006754 unsigned int i; /* Loop counter */
6755
drh2aa5a002011-04-13 13:42:25 +00006756 /* Double-check that the aSyscall[] array has been constructed
6757 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh90315a22011-08-10 01:52:12 +00006758 assert( ArraySize(aSyscall)==18 );
drh2aa5a002011-04-13 13:42:25 +00006759
drh6b9d6dd2008-12-03 19:34:47 +00006760 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006761 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006762 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006763 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006764 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006765}
danielk1977e339d652008-06-28 11:23:00 +00006766
6767/*
drh6b9d6dd2008-12-03 19:34:47 +00006768** Shutdown the operating system interface.
6769**
6770** Some operating systems might need to do some cleanup in this routine,
6771** to release dynamically allocated objects. But not on unix.
6772** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006773*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006774int sqlite3_os_end(void){
6775 return SQLITE_OK;
6776}
drhdce8bdb2007-08-16 13:01:44 +00006777
danielk197729bafea2008-06-26 10:41:19 +00006778#endif /* SQLITE_OS_UNIX */